diff options
author | Lester Solbakken <lester.solbakken@gmail.com> | 2024-04-12 13:04:01 +0200 |
---|---|---|
committer | Lester Solbakken <lester.solbakken@gmail.com> | 2024-04-12 13:04:01 +0200 |
commit | b4d6c0856e0313e8925505265121ce743f079ada (patch) | |
tree | fd8a28fb707d7dae4ac9c4f19d48aad082cf01ff | |
parent | e11438c6335038f6d99ea50eef086511eb204d43 (diff) | |
parent | dd996cbeb9ddf7c22089b6115966f03227b35a48 (diff) |
Merge branch 'master' into lesters/add-local-llms
710 files changed, 3222 insertions, 2986 deletions
diff --git a/abi-check-plugin/src/main/java/com/yahoo/abicheck/classtree/ClassFileTree.java b/abi-check-plugin/src/main/java/com/yahoo/abicheck/classtree/ClassFileTree.java index 32571b4a1c6..4cb73cc3533 100644 --- a/abi-check-plugin/src/main/java/com/yahoo/abicheck/classtree/ClassFileTree.java +++ b/abi-check-plugin/src/main/java/com/yahoo/abicheck/classtree/ClassFileTree.java @@ -4,12 +4,12 @@ package com.yahoo.abicheck.classtree; import java.io.IOException; import java.io.InputStream; import java.util.ArrayDeque; -import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.JarEntry; @@ -24,7 +24,7 @@ public abstract class ClassFileTree implements AutoCloseable { while (jarEntries.hasMoreElements()) { JarEntry entry = jarEntries.nextElement(); if (!entry.isDirectory() && entry.getName().endsWith(".class")) { - Deque<String> parts = new ArrayDeque<>(Arrays.asList(entry.getName().split("/"))); + Deque<String> parts = new ArrayDeque<>(List.of(entry.getName().split("/"))); String className = parts.removeLast(); Package pkg = rootPackages .computeIfAbsent(parts.removeFirst(), name -> new Package(null, name)); diff --git a/abi-check-plugin/src/test/java/com/yahoo/abicheck/AccessConversionTest.java b/abi-check-plugin/src/test/java/com/yahoo/abicheck/AccessConversionTest.java index d592a2ce1e3..1631eac866f 100644 --- a/abi-check-plugin/src/test/java/com/yahoo/abicheck/AccessConversionTest.java +++ b/abi-check-plugin/src/test/java/com/yahoo/abicheck/AccessConversionTest.java @@ -5,17 +5,18 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import com.yahoo.abicheck.collector.Util; -import java.util.Arrays; import org.junit.jupiter.api.Test; import org.objectweb.asm.Opcodes; +import java.util.List; + public class AccessConversionTest { @Test public void testClassFlags() { // ACC_SUPER should be ignored assertEquals( - Arrays.asList("public", "abstract"), + List.of("public", "abstract"), Util.convertAccess( Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_ABSTRACT, Util.classFlags)); @@ -25,7 +26,7 @@ public class AccessConversionTest { public void testMethodFlags() { // ACC_DEPRECATED should be ignored assertEquals( - Arrays.asList("protected", "varargs"), + List.of("protected", "varargs"), Util.convertAccess( Opcodes.ACC_PROTECTED | Opcodes.ACC_VARARGS | Opcodes.ACC_DEPRECATED, Util.methodFlags)); @@ -34,7 +35,7 @@ public class AccessConversionTest { @Test public void testFieldFlags() { assertEquals( - Arrays.asList("private", "volatile"), + List.of("private", "volatile"), Util.convertAccess( Opcodes.ACC_PRIVATE | Opcodes.ACC_VOLATILE, Util.fieldFlags)); diff --git a/abi-check-plugin/src/test/java/com/yahoo/abicheck/ClassFileTreeTest.java b/abi-check-plugin/src/test/java/com/yahoo/abicheck/ClassFileTreeTest.java index 3f90ba01848..1667a6b87d0 100644 --- a/abi-check-plugin/src/test/java/com/yahoo/abicheck/ClassFileTreeTest.java +++ b/abi-check-plugin/src/test/java/com/yahoo/abicheck/ClassFileTreeTest.java @@ -12,8 +12,8 @@ import com.google.common.collect.Iterables; import com.yahoo.abicheck.classtree.ClassFileTree; import java.io.IOException; import java.io.InputStream; -import java.util.Arrays; import java.util.Collections; +import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.junit.jupiter.api.Test; @@ -27,7 +27,7 @@ public class ClassFileTreeTest { JarEntry dirJarEntry = new JarEntry("com/yahoo/"); InputStream jarEntryStream = mock(InputStream.class); when(jarFile.entries()) - .thenReturn(Collections.enumeration(Arrays.asList(dirJarEntry, classJarEntry))); + .thenReturn(Collections.enumeration(List.of(dirJarEntry, classJarEntry))); when(jarFile.getInputStream(classJarEntry)).thenReturn(jarEntryStream); try (ClassFileTree cft = ClassFileTree.fromJar(jarFile)) { diff --git a/abi-check-plugin/src/test/java/com/yahoo/abicheck/mojo/AbiCheckTest.java b/abi-check-plugin/src/test/java/com/yahoo/abicheck/mojo/AbiCheckTest.java index 6821a03818e..9bc330ad130 100644 --- a/abi-check-plugin/src/test/java/com/yahoo/abicheck/mojo/AbiCheckTest.java +++ b/abi-check-plugin/src/test/java/com/yahoo/abicheck/mojo/AbiCheckTest.java @@ -12,9 +12,9 @@ import com.yahoo.abicheck.Public; import com.yahoo.abicheck.classtree.ClassFileTree; import com.yahoo.abicheck.signature.JavaClassSignature; import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.maven.plugin.logging.Log; import org.junit.jupiter.api.Test; import root.Root; @@ -30,9 +30,9 @@ public class AbiCheckTest { ClassFileTree.ClassFile rootPkgClass = mock(ClassFileTree.ClassFile.class); ClassFileTree.ClassFile subPkgClass = mock(ClassFileTree.ClassFile.class); - when(rootPkg.getSubPackages()).thenReturn(Collections.singleton(subPkg)); - when(rootPkg.getClassFiles()).thenReturn(Arrays.asList(rootPkgClass, rootPkgInfoClass)); - when(subPkg.getClassFiles()).thenReturn(Collections.singleton(subPkgClass)); + when(rootPkg.getSubPackages()).thenReturn(Set.of(subPkg)); + when(rootPkg.getClassFiles()).thenReturn(List.of(rootPkgClass, rootPkgInfoClass)); + when(subPkg.getClassFiles()).thenReturn(Set.of(subPkgClass)); when(rootPkgInfoClass.getName()).thenReturn("package-info.class"); when(rootPkgInfoClass.getInputStream()) @@ -68,16 +68,16 @@ public class AbiCheckTest { JavaClassSignature signatureA = new JavaClassSignature( "java.lang.Object", - Collections.emptySet(), - Collections.singletonList("public"), - Collections.singleton("public void foo()"), - Collections.singleton("public int bar")); + Set.of(), + List.of("public"), + Set.of("public void foo()"), + Set.of("public int bar")); JavaClassSignature signatureB = new JavaClassSignature( "java.lang.Exception", - Collections.singleton("java.lang.Runnable"), - Collections.singletonList("protected"), - Collections.singleton("public void foo(int)"), - Collections.singleton("public boolean bar")); + Set.of("java.lang.Runnable"), + List.of("protected"), + Set.of("public void foo(int)"), + Set.of("public boolean bar")); Map<String, JavaClassSignature> expected = ImmutableMap.<String, JavaClassSignature>builder() .put("test.Missing", signatureA) diff --git a/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java b/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java index 9514749138c..4079fc377d6 100644 --- a/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java +++ b/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java @@ -3,11 +3,7 @@ package com.yahoo.application.container.handler; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -66,9 +62,9 @@ public class HeadersTestCase { @Test void requireThatContainsValueWorksAsExpected() { Headers headers = new Headers(); - assertFalse(headers.containsValue(Arrays.asList("bar"))); + assertFalse(headers.containsValue(List.of("bar"))); headers.add("foo", "bar"); - assertTrue(headers.containsValue(Arrays.asList("bar"))); + assertTrue(headers.containsValue(List.of("bar"))); } @Test @@ -104,19 +100,19 @@ public class HeadersTestCase { Headers headers = new Headers(); assertNull(headers.get("foo")); headers.add("foo", "bar"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); + assertEquals(List.of("bar"), headers.get("foo")); headers.add("foo", "baz"); - assertEquals(Arrays.asList("bar", "baz"), headers.get("foo")); + assertEquals(List.of("bar", "baz"), headers.get("foo")); } @Test void requireThatAddListWorksAsExpected() { Headers headers = new Headers(); assertNull(headers.get("foo")); - headers.add("foo", Arrays.asList("bar")); - assertEquals(Arrays.asList("bar"), headers.get("foo")); - headers.add("foo", Arrays.asList("baz", "cox")); - assertEquals(Arrays.asList("bar", "baz", "cox"), headers.get("foo")); + headers.add("foo", List.of("bar")); + assertEquals(List.of("bar"), headers.get("foo")); + headers.add("foo", List.of("baz", "cox")); + assertEquals(List.of("bar", "baz", "cox"), headers.get("foo")); } @Test @@ -124,16 +120,14 @@ public class HeadersTestCase { Headers headers = new Headers(); headers.add("foo", "bar"); headers.add("bar", "baz"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); - assertEquals(Arrays.asList("baz"), headers.get("bar")); + assertEquals(List.of("bar"), headers.get("foo")); + assertEquals(List.of("baz"), headers.get("bar")); - Map<String, List<String>> map = new HashMap<>(); - map.put("foo", Arrays.asList("baz", "cox")); - map.put("bar", Arrays.asList("cox")); + Map<String, List<String>> map = Map.of("foo", List.of("baz", "cox"), "bar", List.of("cox")); headers.addAll(map); - assertEquals(Arrays.asList("bar", "baz", "cox"), headers.get("foo")); - assertEquals(Arrays.asList("baz", "cox"), headers.get("bar")); + assertEquals(List.of("bar", "baz", "cox"), headers.get("foo")); + assertEquals(List.of("baz", "cox"), headers.get("bar")); } @Test @@ -141,19 +135,19 @@ public class HeadersTestCase { Headers headers = new Headers(); assertNull(headers.get("foo")); headers.put("foo", "bar"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); + assertEquals(List.of("bar"), headers.get("foo")); headers.put("foo", "baz"); - assertEquals(Arrays.asList("baz"), headers.get("foo")); + assertEquals(List.of("baz"), headers.get("foo")); } @Test void requireThatPutListWorksAsExpected() { Headers headers = new Headers(); assertNull(headers.get("foo")); - headers.put("foo", Arrays.asList("bar")); - assertEquals(Arrays.asList("bar"), headers.get("foo")); - headers.put("foo", Arrays.asList("baz", "cox")); - assertEquals(Arrays.asList("baz", "cox"), headers.get("foo")); + headers.put("foo", List.of("bar")); + assertEquals(List.of("bar"), headers.get("foo")); + headers.put("foo", List.of("baz", "cox")); + assertEquals(List.of("baz", "cox"), headers.get("foo")); } @Test @@ -161,24 +155,22 @@ public class HeadersTestCase { Headers headers = new Headers(); headers.add("foo", "bar"); headers.add("bar", "baz"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); - assertEquals(Arrays.asList("baz"), headers.get("bar")); + assertEquals(List.of("bar"), headers.get("foo")); + assertEquals(List.of("baz"), headers.get("bar")); - Map<String, List<String>> map = new HashMap<>(); - map.put("foo", Arrays.asList("baz", "cox")); - map.put("bar", Arrays.asList("cox")); + Map<String, List<String>> map = Map.of("foo", List.of("baz", "cox"), "bar", List.of("cox")); headers.putAll(map); - assertEquals(Arrays.asList("baz", "cox"), headers.get("foo")); - assertEquals(Arrays.asList("cox"), headers.get("bar")); + assertEquals(List.of("baz", "cox"), headers.get("foo")); + assertEquals(List.of("cox"), headers.get("bar")); } @Test void requireThatRemoveWorksAsExpected() { Headers headers = new Headers(); - headers.put("foo", Arrays.asList("bar", "baz")); - assertEquals(Arrays.asList("bar", "baz"), headers.get("foo")); - assertEquals(Arrays.asList("bar", "baz"), headers.remove("foo")); + headers.put("foo", List.of("bar", "baz")); + assertEquals(List.of("bar", "baz"), headers.get("foo")); + assertEquals(List.of("bar", "baz"), headers.remove("foo")); assertNull(headers.get("foo")); assertNull(headers.remove("foo")); } @@ -186,11 +178,11 @@ public class HeadersTestCase { @Test void requireThatRemoveStringWorksAsExpected() { Headers headers = new Headers(); - headers.put("foo", Arrays.asList("bar", "baz")); - assertEquals(Arrays.asList("bar", "baz"), headers.get("foo")); + headers.put("foo", List.of("bar", "baz")); + assertEquals(List.of("bar", "baz"), headers.get("foo")); assertTrue(headers.remove("foo", "bar")); assertFalse(headers.remove("foo", "cox")); - assertEquals(Arrays.asList("baz"), headers.get("foo")); + assertEquals(List.of("baz"), headers.get("foo")); assertTrue(headers.remove("foo", "baz")); assertFalse(headers.remove("foo", "cox")); assertNull(headers.get("foo")); @@ -201,8 +193,8 @@ public class HeadersTestCase { Headers headers = new Headers(); headers.add("foo", "bar"); headers.add("bar", "baz"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); - assertEquals(Arrays.asList("baz"), headers.get("bar")); + assertEquals(List.of("bar"), headers.get("foo")); + assertEquals(List.of("baz"), headers.get("bar")); headers.clear(); assertNull(headers.get("foo")); assertNull(headers.get("bar")); @@ -213,14 +205,14 @@ public class HeadersTestCase { Headers headers = new Headers(); assertNull(headers.get("foo")); headers.add("foo", "bar"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); + assertEquals(List.of("bar"), headers.get("foo")); } @Test void requireThatGetFirstWorksAsExpected() { Headers headers = new Headers(); assertNull(headers.getFirst("foo")); - headers.add("foo", Arrays.asList("bar", "baz")); + headers.add("foo", List.of("bar", "baz")); assertEquals("bar", headers.getFirst("foo")); } @@ -228,28 +220,28 @@ public class HeadersTestCase { void requireThatIsTrueWorksAsExpected() { Headers headers = new Headers(); assertFalse(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("true")); + headers.put("foo", List.of("true")); assertTrue(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("true", "true")); + headers.put("foo", List.of("true", "true")); assertTrue(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("true", "false")); + headers.put("foo", List.of("true", "false")); assertFalse(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("false", "true")); + headers.put("foo", List.of("false", "true")); assertFalse(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("false", "false")); + headers.put("foo", List.of("false", "false")); assertFalse(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("false")); + headers.put("foo", List.of("false")); assertFalse(headers.isTrue("foo")); } @Test void requireThatKeySetWorksAsExpected() { Headers headers = new Headers(); - assertEquals(Collections.<Set<String>>emptySet(), headers.keySet()); + assertEquals(Set.of(), headers.keySet()); headers.add("foo", "bar"); - assertEquals(new HashSet<>(Arrays.asList("foo")), headers.keySet()); + assertEquals(Set.of("foo"), headers.keySet()); headers.add("bar", "baz"); - assertEquals(new HashSet<>(Arrays.asList("foo", "bar")), headers.keySet()); + assertEquals(Set.of("foo", "bar"), headers.keySet()); } @Test @@ -259,34 +251,34 @@ public class HeadersTestCase { headers.add("foo", "bar"); Collection<List<String>> values = headers.values(); assertEquals(1, values.size()); - assertTrue(values.contains(Arrays.asList("bar"))); + assertTrue(values.contains(List.of("bar"))); headers.add("bar", "baz"); values = headers.values(); assertEquals(2, values.size()); - assertTrue(values.contains(Arrays.asList("bar"))); - assertTrue(values.contains(Arrays.asList("baz"))); + assertTrue(values.contains(List.of("bar"))); + assertTrue(values.contains(List.of("baz"))); } @Test void requireThatEntrySetWorksAsExpected() { Headers headers = new Headers(); - assertEquals(Collections.emptySet(), headers.entrySet()); - headers.put("foo", Arrays.asList("bar", "baz")); + assertEquals(Set.of(), headers.entrySet()); + headers.put("foo", List.of("bar", "baz")); Set<Map.Entry<String, List<String>>> entries = headers.entrySet(); assertEquals(1, entries.size()); Map.Entry<String, List<String>> entry = entries.iterator().next(); assertNotNull(entry); assertEquals("foo", entry.getKey()); - assertEquals(Arrays.asList("bar", "baz"), entry.getValue()); + assertEquals(List.of("bar", "baz"), entry.getValue()); } @Test void requireThatEntriesWorksAsExpected() { Headers headers = new Headers(); - assertEquals(Collections.emptyList(), headers.entries()); - headers.put("foo", Arrays.asList("bar", "baz")); + assertEquals(List.of(), headers.entries()); + headers.put("foo", List.of("bar", "baz")); List<Map.Entry<String, String>> entries = headers.entries(); assertEquals(2, entries.size()); diff --git a/build_settings.cmake b/build_settings.cmake index 3477531cb56..1549ac83c74 100644 --- a/build_settings.cmake +++ b/build_settings.cmake @@ -90,12 +90,6 @@ else() message("-- liburing not found") endif() -if(VESPA_OS_DISTRO_COMBINED STREQUAL "debian 10") - unset(VESPA_XXHASH_DEFINE) -else() - set(VESPA_XXHASH_DEFINE "-DXXH_INLINE_ALL") -endif() - # Disable dangling reference and overloaded virtual warnings when using gcc 13 # Disable stringop-oveflow, stringop-overread and array-bounds warning when using gcc 13. # The latter heuristics are sufficiently broken to be useless in practice. @@ -111,7 +105,7 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND VESPA_USE_LTO) endif() # C and C++ compiler flags -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O3 -fno-omit-frame-pointer ${C_WARN_OPTS} -fPIC ${VESPA_CXX_ABI_FLAGS} ${VESPA_XXHASH_DEFINE} -DBOOST_DISABLE_ASSERTS ${VESPA_CPU_ARCH_FLAGS} ${EXTRA_C_FLAGS}") +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O3 -fno-omit-frame-pointer ${C_WARN_OPTS} -fPIC ${VESPA_CXX_ABI_FLAGS} -DXXH_INLINE_ALL -DBOOST_DISABLE_ASSERTS ${VESPA_CPU_ARCH_FLAGS} ${EXTRA_C_FLAGS}") # AddressSanitizer/ThreadSanitizer work for both GCC and Clang if (VESPA_USE_SANITIZER) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=${VESPA_USE_SANITIZER}") diff --git a/bundle-plugin/src/main/java/com/yahoo/container/plugin/bundle/AnalyzeBundle.java b/bundle-plugin/src/main/java/com/yahoo/container/plugin/bundle/AnalyzeBundle.java index cbe5e97374c..e8c0e7a4800 100644 --- a/bundle-plugin/src/main/java/com/yahoo/container/plugin/bundle/AnalyzeBundle.java +++ b/bundle-plugin/src/main/java/com/yahoo/container/plugin/bundle/AnalyzeBundle.java @@ -7,9 +7,7 @@ import com.yahoo.container.plugin.util.JarFiles; import java.io.File; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.jar.Manifest; @@ -37,7 +35,7 @@ public class AnalyzeBundle { static List<Export> exportedPackages(File jarFile) { var manifest = getOsgiManifest(jarFile); - if (manifest == null) return Collections.emptyList(); + if (manifest == null) return List.of(); try { return parseExports(manifest); } catch (Exception e) { @@ -55,9 +53,9 @@ public class AnalyzeBundle { private static List<String> nonPublicApiPackages(File jarFile) { var manifest = getOsgiManifest(jarFile); - if (manifest == null) return Collections.emptyList(); + if (manifest == null) return List.of(); return getMainAttributeValue(manifest, "X-JDisc-Non-PublicApi-Export-Package") - .map(s -> Arrays.asList(s.split(","))) + .map(s -> List.of(s.split(","))) .orElseGet(ArrayList::new); } diff --git a/bundle-plugin/src/main/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassVisitor.java b/bundle-plugin/src/main/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassVisitor.java index 6b8f3f6ba12..5546d3c4f32 100644 --- a/bundle-plugin/src/main/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassVisitor.java +++ b/bundle-plugin/src/main/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassVisitor.java @@ -14,8 +14,8 @@ import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import java.util.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Optional; import java.util.Set; @@ -55,9 +55,9 @@ class AnalyzeClassVisitor extends ClassVisitor implements ImportCollector { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { Analyze.getClassName(Type.getReturnType(desc)).ifPresent(imports::add); - Arrays.asList(Type.getArgumentTypes(desc)).forEach(argType -> Analyze.getClassName(argType).ifPresent(imports::add)); + List.of(Type.getArgumentTypes(desc)).forEach(argType -> Analyze.getClassName(argType).ifPresent(imports::add)); if (exceptions != null) { - Arrays.asList(exceptions).forEach(ex -> Analyze.internalNameToClassName(ex).ifPresent(imports::add)); + List.of(exceptions).forEach(ex -> Analyze.internalNameToClassName(ex).ifPresent(imports::add)); } AnalyzeSignatureVisitor.analyzeMethod(signature, this); @@ -83,7 +83,7 @@ class AnalyzeClassVisitor extends ClassVisitor implements ImportCollector { } addImportWithInternalName(superName); - Arrays.asList(interfaces).forEach(this::addImportWithInternalName); + List.of(interfaces).forEach(this::addImportWithInternalName); AnalyzeSignatureVisitor.analyzeClass(signature, this); } diff --git a/bundle-plugin/src/main/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodVisitor.java b/bundle-plugin/src/main/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodVisitor.java index 788fa346a37..d7991810024 100644 --- a/bundle-plugin/src/main/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodVisitor.java +++ b/bundle-plugin/src/main/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodVisitor.java @@ -9,8 +9,8 @@ import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; -import java.util.Arrays; import java.util.HashSet; +import java.util.List; import java.util.Set; /** @@ -70,7 +70,7 @@ class AnalyzeMethodVisitor extends MethodVisitor implements ImportCollector { @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { addImportWithInternalName(owner); - Arrays.asList(Type.getArgumentTypes(desc)).forEach(this::addImport); + List.of(Type.getArgumentTypes(desc)).forEach(this::addImport); addImport(Type.getReturnType(desc)); } @@ -112,7 +112,7 @@ class AnalyzeMethodVisitor extends MethodVisitor implements ImportCollector { addImport((Type) arg); } else if (arg instanceof Handle) { addImportWithInternalName(((Handle) arg).getOwner()); - Arrays.asList(Type.getArgumentTypes(desc)).forEach(this::addImport); + List.of(Type.getArgumentTypes(desc)).forEach(this::addImport); } else if ( ! (arg instanceof Number) && ! (arg instanceof String)) { throw new AssertionError("Unexpected type " + arg.getClass() + " with value '" + arg + "'"); } diff --git a/bundle-plugin/src/main/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojo.java b/bundle-plugin/src/main/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojo.java index adcbdb68553..74acf3dffa1 100644 --- a/bundle-plugin/src/main/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojo.java +++ b/bundle-plugin/src/main/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojo.java @@ -16,9 +16,9 @@ import org.codehaus.plexus.component.annotations.Requirement; import java.io.FileNotFoundException; import java.io.IOException; -import java.util.Arrays; import java.util.Collection; import java.util.Iterator; +import java.util.List; import java.util.Properties; import java.util.regex.Pattern; @@ -145,7 +145,7 @@ public class GenerateSourcesMojo extends AbstractMojo { if (parts.length <= 3) { return mavenVersion; } else { - return stringJoin(Arrays.asList(parts).subList(0, 3), "."); + return stringJoin(List.of(parts).subList(0, 3), "."); } } } diff --git a/bundle-plugin/src/main/java/com/yahoo/container/plugin/util/JarFiles.java b/bundle-plugin/src/main/java/com/yahoo/container/plugin/util/JarFiles.java index af403946f39..c66aa61a8ee 100644 --- a/bundle-plugin/src/main/java/com/yahoo/container/plugin/util/JarFiles.java +++ b/bundle-plugin/src/main/java/com/yahoo/container/plugin/util/JarFiles.java @@ -4,7 +4,6 @@ package com.yahoo.container.plugin.util; import java.io.File; import java.io.InputStream; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.jar.JarFile; @@ -25,8 +24,8 @@ public class JarFiles { .map(s -> Arrays.stream(s.split(",")) .map(ArtifactId::fromStringValue) .toList()) - .orElse(Collections.emptyList())) - .orElse(Collections.emptyList()); + .orElse(List.of())) + .orElse(List.of()); } diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java index caaa8d5c6c0..7ad1afff01d 100644 --- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java +++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java @@ -6,7 +6,6 @@ import com.yahoo.container.plugin.osgi.ExportPackages.Parameter; import com.yahoo.container.plugin.osgi.ImportPackages.Import; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -23,8 +22,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; */ public class ImportPackageTest { private static final String PACKAGE_NAME = "com.yahoo.exported"; - private final Set<String> referencedPackages = Collections.singleton(PACKAGE_NAME); - private final Map<String, Export> exports = exportByPackageName(new Export(List.of(PACKAGE_NAME), Collections.emptyList())); + private final Set<String> referencedPackages = Set.of(PACKAGE_NAME); + private final Map<String, Export> exports = exportByPackageName(new Export(List.of(PACKAGE_NAME), List.of())); private final Map<String, Export> exportsWithVersion = exportByPackageName( new Export(List.of(PACKAGE_NAME), List.of(new Parameter("version", "1.3")))); diff --git a/client/src/main/java/ai/vespa/client/dsl/Sources.java b/client/src/main/java/ai/vespa/client/dsl/Sources.java index b6dd1b06536..cecf27aa240 100644 --- a/client/src/main/java/ai/vespa/client/dsl/Sources.java +++ b/client/src/main/java/ai/vespa/client/dsl/Sources.java @@ -3,7 +3,6 @@ package ai.vespa.client.dsl; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -19,7 +18,7 @@ public class Sources { } Sources(Select select, String searchDefinition) { - this(select, Collections.singletonList(searchDefinition)); + this(select, List.of(searchDefinition)); } Sources(Select select, String searchDefinition, String... others) { diff --git a/client/src/test/java/ai/vespa/client/dsl/QTest.java b/client/src/test/java/ai/vespa/client/dsl/QTest.java index 3dbf714ed62..75e74c8919a 100644 --- a/client/src/test/java/ai/vespa/client/dsl/QTest.java +++ b/client/src/test/java/ai/vespa/client/dsl/QTest.java @@ -3,10 +3,9 @@ package ai.vespa.client.dsl; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -224,9 +223,9 @@ class QTest { String q = Q.select("*") .from("sd1") .where(Q.wand("f1", stringIntMap("a", 1, "b", 2, "c", 3))) - .and(Q.wand("f2", Arrays.asList(Arrays.asList(1, 1), Arrays.asList(2, 2)))) + .and(Q.wand("f2", List.of(List.of(1, 1), List.of(2, 2)))) .and( - Q.wand("f3", Arrays.asList(Arrays.asList(1, 1), Arrays.asList(2, 2))) + Q.wand("f3", List.of(List.of(1, 1), List.of(2, 2))) .annotate(A.a("scoreThreshold", 0.13)) ) .build(); @@ -421,7 +420,7 @@ class QTest { { String q1 = Q.p("f1").containsPhrase("p1", "p2", "p3") .build(); - String q2 = Q.p("f1").containsPhrase(Arrays.asList("p1", "p2", "p3")) + String q2 = Q.p("f1").containsPhrase(List.of("p1", "p2", "p3")) .build(); assertEquals(q1, "yql=select * from sources * where f1 contains phrase(\"p1\", \"p2\", \"p3\")"); assertEquals(q2, "yql=select * from sources * where f1 contains phrase(\"p1\", \"p2\", \"p3\")"); @@ -429,7 +428,7 @@ class QTest { { String q1 = Q.p("f1").containsNear("p1", "p2", "p3") .build(); - String q2 = Q.p("f1").containsNear(Arrays.asList("p1", "p2", "p3")) + String q2 = Q.p("f1").containsNear(List.of("p1", "p2", "p3")) .build(); assertEquals(q1, "yql=select * from sources * where f1 contains near(\"p1\", \"p2\", \"p3\")"); assertEquals(q2, "yql=select * from sources * where f1 contains near(\"p1\", \"p2\", \"p3\")"); @@ -437,7 +436,7 @@ class QTest { { String q1 = Q.p("f1").containsOnear("p1", "p2", "p3") .build(); - String q2 = Q.p("f1").containsOnear(Arrays.asList("p1", "p2", "p3")) + String q2 = Q.p("f1").containsOnear(List.of("p1", "p2", "p3")) .build(); assertEquals(q1, "yql=select * from sources * where f1 contains onear(\"p1\", \"p2\", \"p3\")"); assertEquals(q2, "yql=select * from sources * where f1 contains onear(\"p1\", \"p2\", \"p3\")"); @@ -445,7 +444,7 @@ class QTest { { String q1 = Q.p("f1").containsEquiv("p1", "p2", "p3") .build(); - String q2 = Q.p("f1").containsEquiv(Arrays.asList("p1", "p2", "p3")) + String q2 = Q.p("f1").containsEquiv(List.of("p1", "p2", "p3")) .build(); assertEquals(q1, "yql=select * from sources * where f1 contains equiv(\"p1\", \"p2\", \"p3\")"); assertEquals(q2, "yql=select * from sources * where f1 contains equiv(\"p1\", \"p2\", \"p3\")"); @@ -498,7 +497,7 @@ class QTest { @Test void use_contains_instead_of_contains_equiv_when_input_size_is_1() { - String q = Q.p("f1").containsEquiv(Collections.singletonList("p1")) + String q = Q.p("f1").containsEquiv(List.of("p1")) .build(); assertEquals(q, "yql=select * from sources * where f1 contains \"p1\""); @@ -506,16 +505,16 @@ class QTest { @Test void contains_phrase_near_onear_equiv_empty_list_should_throw_illegal_argument_exception() { - assertThrows(IllegalArgumentException.class, () -> Q.p("f1").containsPhrase(Collections.emptyList()) + assertThrows(IllegalArgumentException.class, () -> Q.p("f1").containsPhrase(List.of()) .build()); - assertThrows(IllegalArgumentException.class, () -> Q.p("f1").containsNear(Collections.emptyList()) + assertThrows(IllegalArgumentException.class, () -> Q.p("f1").containsNear(List.of()) .build()); - assertThrows(IllegalArgumentException.class, () -> Q.p("f1").containsOnear(Collections.emptyList()) + assertThrows(IllegalArgumentException.class, () -> Q.p("f1").containsOnear(List.of()) .build()); - assertThrows(IllegalArgumentException.class, () -> Q.p("f1").containsEquiv(Collections.emptyList()) + assertThrows(IllegalArgumentException.class, () -> Q.p("f1").containsEquiv(List.of()) .build()); } @@ -586,7 +585,7 @@ class QTest { @Test void arbitrary_annotations() { - Annotation a = A.a("a1", "v1", "a2", 2, "a3", stringObjMap("k", "v", "k2", 1), "a4", 4D, "a5", Arrays.asList(1, 2, 3)); + Annotation a = A.a("a1", "v1", "a2", 2, "a3", stringObjMap("k", "v", "k2", 1), "a4", 4D, "a5", List.of(1, 2, 3)); assertEquals(a.toString(), "{\"a1\":\"v1\",\"a2\":2,\"a3\":{\"k\":\"v\",\"k2\":1},\"a4\":4.0,\"a5\":[1,2,3]}"); } diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/AnnotatedClusterState.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/AnnotatedClusterState.java index e0ddf16ab5f..7991e1c34b6 100644 --- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/AnnotatedClusterState.java +++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/AnnotatedClusterState.java @@ -4,7 +4,6 @@ package com.yahoo.vespa.clustercontroller.core; import com.yahoo.vdslib.state.ClusterState; import com.yahoo.vdslib.state.Node; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -47,7 +46,7 @@ public class AnnotatedClusterState implements Cloneable { Map<Node, NodeStateReason> nodeStateReasons) { this.clusterState = Objects.requireNonNull(clusterState, "Cluster state cannot be null"); this.clusterStateReason = Objects.requireNonNull(clusterStateReason, "Cluster state reason cannot be null"); - this.nodeStateReasons = Objects.requireNonNull(nodeStateReasons, "Node state reasons cannot be null"); + this.nodeStateReasons = Map.copyOf(Objects.requireNonNull(nodeStateReasons, "Node state reasons cannot be null")); } public static AnnotatedClusterState emptyState() { @@ -59,7 +58,7 @@ public class AnnotatedClusterState implements Cloneable { } static Map<Node, NodeStateReason> emptyNodeStateReasons() { - return Collections.emptyMap(); + return Map.of(); } public ClusterState getClusterState() { @@ -67,7 +66,7 @@ public class AnnotatedClusterState implements Cloneable { } public Map<Node, NodeStateReason> getNodeStateReasons() { - return Collections.unmodifiableMap(nodeStateReasons); + return nodeStateReasons; } public Optional<ClusterStateReason> getClusterStateReason() { diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundle.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundle.java index 53a39968720..de56272d0e8 100644 --- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundle.java +++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundle.java @@ -3,8 +3,7 @@ package com.yahoo.vespa.clustercontroller.core; import com.yahoo.vdslib.state.ClusterState; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -56,7 +55,7 @@ public class ClusterStateBundle { public FeedBlock(boolean blockFeedInCluster, String description) { this.blockFeedInCluster = blockFeedInCluster; this.description = description; - this.concreteExhaustions = Collections.emptySet(); + this.concreteExhaustions = Set.of(); } public FeedBlock(boolean blockFeedInCluster, String description, @@ -138,7 +137,7 @@ public class ClusterStateBundle { } public Builder bucketSpaces(String... bucketSpaces) { - return bucketSpaces(new TreeSet<>(Arrays.asList(bucketSpaces))); + return bucketSpaces(new TreeSet<>(List.of(bucketSpaces))); } public Builder explicitDerivedStates(Map<String, AnnotatedClusterState> derivedStates) { @@ -165,14 +164,10 @@ public class ClusterStateBundle { return ClusterStateBundle.ofBaselineOnly(baselineState, feedBlock, deferredActivation); } Map<String, AnnotatedClusterState> derived; - if (explicitDerivedStates != null) { - derived = explicitDerivedStates; - } else { - derived = bucketSpaces.stream() - .collect(Collectors.toMap( - Function.identity(), - s -> stateDeriver.derivedFrom(baselineState, s))); - } + derived = Objects.requireNonNullElseGet(explicitDerivedStates, () -> bucketSpaces.stream() + .collect(Collectors.toUnmodifiableMap( + Function.identity(), + s -> stateDeriver.derivedFrom(baselineState, s)))); return new ClusterStateBundle(baselineState, derived, feedBlock, deferredActivation); } } @@ -186,7 +181,7 @@ public class ClusterStateBundle { FeedBlock feedBlock, boolean deferredActivation) { this.baselineState = baselineState; - this.derivedBucketSpaceStates = Collections.unmodifiableMap(derivedBucketSpaceStates); + this.derivedBucketSpaceStates = Map.copyOf(derivedBucketSpaceStates); this.feedBlock = feedBlock; this.deferredActivation = deferredActivation; } @@ -209,11 +204,11 @@ public class ClusterStateBundle { public static ClusterStateBundle ofBaselineOnly(AnnotatedClusterState baselineState, FeedBlock feedBlock, boolean deferredActivation) { - return new ClusterStateBundle(baselineState, Collections.emptyMap(), feedBlock, deferredActivation); + return new ClusterStateBundle(baselineState, Map.of(), feedBlock, deferredActivation); } public static ClusterStateBundle ofBaselineOnly(AnnotatedClusterState baselineState) { - return new ClusterStateBundle(baselineState, Collections.emptyMap()); + return new ClusterStateBundle(baselineState, Map.of()); } public static ClusterStateBundle empty() { @@ -238,7 +233,7 @@ public class ClusterStateBundle { AnnotatedClusterState clonedBaseline = baselineState.cloneWithClusterState( mapper.apply(baselineState.getClusterState().clone())); Map<String, AnnotatedClusterState> clonedDerived = derivedBucketSpaceStates.entrySet().stream() - .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().cloneWithClusterState( + .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().cloneWithClusterState( mapper.apply(e.getValue().getClusterState().clone())))); return new ClusterStateBundle(clonedBaseline, clonedDerived, feedBlock, deferredActivation); } diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculator.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculator.java index 5c29228b858..d57f32ee3cb 100644 --- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculator.java +++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculator.java @@ -9,7 +9,6 @@ import com.yahoo.vdslib.state.NodeType; import com.yahoo.vdslib.state.State; import java.util.ArrayList; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -174,8 +173,8 @@ public class EventDiffCalculator { private static void emitNodeResourceExhaustionEvents(PerStateParams params, List<Event> events, ContentCluster cluster) { // Feed block events are not ordered by node - Set<NodeResourceExhaustion> fromBlockSet = params.feedBlockFrom != null ? params.feedBlockFrom.getConcreteExhaustions() : Collections.emptySet(); - Set<NodeResourceExhaustion> toBlockSet = params.feedBlockTo != null ? params.feedBlockTo.getConcreteExhaustions() : Collections.emptySet(); + Set<NodeResourceExhaustion> fromBlockSet = params.feedBlockFrom != null ? params.feedBlockFrom.getConcreteExhaustions() : Set.of(); + Set<NodeResourceExhaustion> toBlockSet = params.feedBlockTo != null ? params.feedBlockTo.getConcreteExhaustions() : Set.of(); for (var ex : setSubtraction(fromBlockSet, toBlockSet)) { var info = cluster.getNodeInfo(ex.node); diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/FleetControllerOptions.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/FleetControllerOptions.java index a0efaa70b58..44b2c8833db 100644 --- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/FleetControllerOptions.java +++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/FleetControllerOptions.java @@ -10,7 +10,6 @@ import com.yahoo.vespa.clustercontroller.core.database.ZooKeeperDatabaseFactory; import java.time.Duration; import java.util.Collection; -import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -433,7 +432,7 @@ public class FleetControllerOptions { private double minMergeCompletionRatio = 1.0; private int maxDivergentNodesPrintedInTaskErrorMessages = 10; private boolean clusterFeedBlockEnabled = false; - private Map<String, Double> clusterFeedBlockLimit = Collections.emptyMap(); + private Map<String, Double> clusterFeedBlockLimit = Map.of(); private double clusterFeedBlockNoiseLevel = 0.01; private int maxNumberOfGroupsAllowedToBeDown = 1; private Function<FleetControllerContext, DatabaseFactory> dbFactoryFn = ZooKeeperDatabaseFactory::new; diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculator.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculator.java index 200a5564c64..4ed1ab967fd 100644 --- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculator.java +++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculator.java @@ -4,7 +4,6 @@ package com.yahoo.vespa.clustercontroller.core; import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo; import java.util.Collection; -import java.util.Collections; import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; @@ -60,7 +59,7 @@ public class ResourceExhaustionCalculator { this.feedBlockEnabled = feedBlockEnabled; this.feedBlockLimits = feedBlockLimits; this.feedBlockNoiseLevel = 0.0; - this.previouslyBlockedNodeResources = Collections.emptySet(); + this.previouslyBlockedNodeResources = Set.of(); } public ResourceExhaustionCalculator(boolean feedBlockEnabled, Map<String, Double> feedBlockLimits, @@ -74,7 +73,7 @@ public class ResourceExhaustionCalculator { .map(ex -> NodeAndResourceType.of(ex.node.getIndex(), ex.resourceType)) .collect(Collectors.toSet()); } else { - this.previouslyBlockedNodeResources = Collections.emptySet(); + this.previouslyBlockedNodeResources = Set.of(); } } @@ -124,12 +123,12 @@ public class ResourceExhaustionCalculator { effectiveLimit, nodeInfo.getRpcAddress())); } } - return (exceedingLimit != null) ? exceedingLimit : Collections.emptySet(); + return (exceedingLimit != null) ? exceedingLimit : Set.of(); } public Set<NodeResourceExhaustion> enumerateNodeResourceExhaustions(NodeInfo nodeInfo) { if (!nodeInfo.isStorage()) { - return Collections.emptySet(); + return Set.of(); } return resourceExhaustionsFromHostInfo(nodeInfo, nodeInfo.getHostInfo()); } diff --git a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodec.java b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodec.java index 12db5c27375..3a6b9a635fa 100644 --- a/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodec.java +++ b/clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodec.java @@ -41,11 +41,10 @@ public class SlimeClusterStateBundleCodec implements ClusterStateBundleCodec, En // TODO add another function that is not toString for this..! states.setString("baseline", stateBundle.getBaselineClusterState().toString()); Cursor spaces = states.setObject("spaces"); - stateBundle.getDerivedBucketSpaceStates().entrySet() - .forEach(entry -> spaces.setString(entry.getKey(), entry.getValue().toString())); + stateBundle.getDerivedBucketSpaceStates().forEach((key, value) -> spaces.setString(key, value.toString())); // Only bother to encode feed block state if cluster is actually blocked - if (stateBundle.getFeedBlock().map(fb -> fb.blockFeedInCluster()).orElse(false)) { + if (stateBundle.getFeedBlock().map(ClusterStateBundle.FeedBlock::blockFeedInCluster).orElse(false)) { Cursor feedBlock = root.setObject("feed-block"); feedBlock.setBool("block-feed-in-cluster", true); feedBlock.setString("description", stateBundle.getFeedBlock().get().getDescription()); diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleUtil.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleUtil.java index 7c39135291c..8280706bcd2 100644 --- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleUtil.java +++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleUtil.java @@ -14,13 +14,13 @@ public class ClusterStateBundleUtil { public static ClusterStateBundle.Builder makeBundleBuilder(String baselineState, StateMapping... bucketSpaceStates) { return ClusterStateBundle.builder(AnnotatedClusterState.withoutAnnotations(ClusterState.stateFromString(baselineState))) - .explicitDerivedStates(Stream.of(bucketSpaceStates).collect(Collectors.toMap(sm -> sm.bucketSpace, + .explicitDerivedStates(Stream.of(bucketSpaceStates).collect(Collectors.toUnmodifiableMap(sm -> sm.bucketSpace, sm -> AnnotatedClusterState.withoutAnnotations(sm.state)))); } public static ClusterStateBundle makeBundle(String baselineState, StateMapping... bucketSpaceStates) { return ClusterStateBundle.of(AnnotatedClusterState.withoutAnnotations(ClusterState.stateFromString(baselineState)), - Stream.of(bucketSpaceStates).collect(Collectors.toMap(sm -> sm.bucketSpace, + Stream.of(bucketSpaceStates).collect(Collectors.toUnmodifiableMap(sm -> sm.bucketSpace, sm -> AnnotatedClusterState.withoutAnnotations(sm.state)))); } diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java index 175b7de8f4f..8048e77b05c 100644 --- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java +++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java @@ -11,7 +11,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.Collections; import java.util.Map; import java.util.TreeMap; @@ -53,7 +52,7 @@ public class ContentClusterHtmlRendererTest { statsAggregator, 1.0, 10, - Collections.emptyMap(), + Map.of(), eventLog, "pathPrefix", "name"); diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java index ee0506070b5..3b26e3b6965 100644 --- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java +++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java @@ -28,7 +28,6 @@ import org.junit.jupiter.api.AfterEach; import java.io.IOException; import java.time.Duration; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; @@ -221,7 +220,7 @@ public abstract class FleetControllerTest implements Waiter { } static Set<Integer> asIntSet(Integer... idx) { - return new HashSet<>(Arrays.asList(idx)); + return new HashSet<>(List.of(idx)); } static Set<ConfiguredNode> asConfiguredNodes(Set<Integer> indices) { diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java index cab67c0b498..17f58ff40f0 100644 --- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java +++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java @@ -5,7 +5,9 @@ import com.yahoo.document.FixedBucketSpaces; import com.yahoo.vdslib.state.ClusterState; import org.junit.jupiter.api.Test; + import java.util.Arrays; +import java.util.List; import static com.yahoo.vespa.clustercontroller.core.NodeStateReason.MAY_HAVE_MERGES_PENDING; import static com.yahoo.vespa.clustercontroller.core.NodeStateReason.NODE_TOO_UNSTABLE; @@ -110,8 +112,8 @@ public class MaintenanceWhenPendingGlobalMergesTest { @Test void node_with_pending_merges_only_set_to_maintenance_if_eligible() { Fixture f = new Fixture(); - Arrays.asList(1, 2, 3).forEach(idx -> when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), idx)).thenReturn(true)); - Arrays.asList(1, 2, 4).forEach(idx -> when(f.mockTransitionConstraint.maintenanceTransitionAllowed(idx)).thenReturn(false)); + List.of(1, 2, 3).forEach(idx -> when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), idx)).thenReturn(true)); + List.of(1, 2, 4).forEach(idx -> when(f.mockTransitionConstraint.maintenanceTransitionAllowed(idx)).thenReturn(false)); AnnotatedClusterState derived = f.deriver.derivedFrom(stateFromString("distributor:5 storage:5"), defaultSpace()); assertThat(derived, equalTo(AnnotatedClusterStateBuilder.ofState("distributor:5 storage:5 .3.s:m") .reason(MAY_HAVE_MERGES_PENDING, 3).build())); diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java index b4246806079..168fe6521d5 100644 --- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java +++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java @@ -4,7 +4,7 @@ package com.yahoo.vespa.clustercontroller.core; import org.junit.jupiter.api.Test; import java.util.Collection; -import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -46,20 +46,20 @@ public class ResourceUsageStatsTest { @Test void nodes_above_limit_is_zero_without_feed_block_status() { - var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(), Optional.empty()); + var stats = ResourceUsageStats.calculateFrom(List.of(), Map.of(), Optional.empty()); assertEquals(0, stats.getNodesAboveLimit()); } @Test void nodes_above_limit_is_equal_to_node_resource_exhaustions() { - var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(), + var stats = ResourceUsageStats.calculateFrom(List.of(), Map.of(), createFeedBlock(exhaustion(1, "disk"), exhaustion(2, "memory"))); assertEquals(2, stats.getNodesAboveLimit()); } @Test void nodes_above_limit_counts_each_node_only_once() { - var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(), + var stats = ResourceUsageStats.calculateFrom(List.of(), Map.of(), createFeedBlock(exhaustion(1, "disk"), exhaustion(1, "memory"))); assertEquals(1, stats.getNodesAboveLimit()); } diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/Waiter.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/Waiter.java index 9e7665e65ee..bf8ba7756e2 100644 --- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/Waiter.java +++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/testutils/Waiter.java @@ -8,7 +8,6 @@ import com.yahoo.vespa.clustercontroller.core.DummyVdsNode; import com.yahoo.vespa.clustercontroller.core.FleetController; import java.time.Duration; import java.time.Instant; -import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Objects; @@ -62,13 +61,13 @@ public interface Waiter { return waitForState(state, data.getTimeout()); } public ClusterState waitForStateInAllSpaces(String state) { - return waitForState(state, data.getTimeout(), true, Collections.emptySet()); + return waitForState(state, data.getTimeout(), true, Set.of()); } public ClusterState waitForStateInSpace(String space, String state) { - return waitForState(state, data.getTimeout(), false, Collections.singleton(space)); + return waitForState(state, data.getTimeout(), false, Set.of(space)); } public ClusterState waitForState(String state, Duration timeoutMS) { - return waitForState(state, timeoutMS, false, Collections.emptySet()); + return waitForState(state, timeoutMS, false, Set.of()); } public ClusterState waitForStableSystem() { return waitForStableSystem(data.getDummyNodes().size() / 2); diff --git a/config-application-package/src/main/java/com/yahoo/config/model/application/provider/Bundle.java b/config-application-package/src/main/java/com/yahoo/config/model/application/provider/Bundle.java index 990e11cae15..6dbf0e4bbac 100644 --- a/config-application-package/src/main/java/com/yahoo/config/model/application/provider/Bundle.java +++ b/config-application-package/src/main/java/com/yahoo/config/model/application/provider/Bundle.java @@ -56,7 +56,7 @@ public class Bundle { if (!bundleDir.isDirectory()) { return new ArrayList<>(); } - return Arrays.asList(bundleDir.listFiles((dir, name) -> name.endsWith(".jar"))); + return List.of(bundleDir.listFiles((dir, name) -> name.endsWith(".jar"))); } public List<DefEntry> getDefEntries() { diff --git a/config-application-package/src/main/java/com/yahoo/config/model/application/provider/FilesApplicationPackage.java b/config-application-package/src/main/java/com/yahoo/config/model/application/provider/FilesApplicationPackage.java index 7d8f827bf31..28bf8e10a93 100644 --- a/config-application-package/src/main/java/com/yahoo/config/model/application/provider/FilesApplicationPackage.java +++ b/config-application-package/src/main/java/com/yahoo/config/model/application/provider/FilesApplicationPackage.java @@ -55,7 +55,6 @@ import java.io.StringReader; import java.nio.file.Files; import java.security.MessageDigest; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; @@ -435,11 +434,11 @@ public class FilesApplicationPackage extends AbstractApplicationPackage { File sdDir = applicationFile(appDir, SEARCH_DEFINITIONS_DIR.getRelative()); if (sdDir.isDirectory()) - schemaFiles.addAll(Arrays.asList(sdDir.listFiles((dir, name) -> validSchemaFilename(name)))); + schemaFiles.addAll(List.of(sdDir.listFiles((dir, name) -> validSchemaFilename(name)))); sdDir = applicationFile(appDir, SCHEMAS_DIR.getRelative()); if (sdDir.isDirectory()) - schemaFiles.addAll(Arrays.asList(sdDir.listFiles((dir, name) -> validSchemaFilename(name)))); + schemaFiles.addAll(List.of(sdDir.listFiles((dir, name) -> validSchemaFilename(name)))); return schemaFiles; } diff --git a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java index 39c2890c30c..27041f8db39 100644 --- a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java +++ b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java @@ -12,8 +12,8 @@ import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import static com.yahoo.foo.StructtypesConfig.Simple.Gender.Enum.FEMALE; @@ -176,7 +176,7 @@ public class ConfigInstanceBuilderTest { doublearr(123.0). stringarr("bar"). enumarr(Enumarr.VALUES). - refarr(Arrays.asList(":parent:", ":parent", "parent:")). // test collection based setter + refarr(List.of(":parent:", ":parent", "parent:")). // test collection based setter fileArr("bin"). intMap("one", 1). intMap("two", 2). diff --git a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java index c50656eac12..2ac679aa9ab 100644 --- a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java +++ b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java @@ -6,7 +6,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.File; -import java.util.Arrays; +import java.util.List; import java.util.Optional; import static com.yahoo.test.FunctionTestConfig.BasicStruct; @@ -136,7 +136,7 @@ public class ConfigInstanceEqualsTest { doublearr(123.0). stringarr("bar"). enumarr(Enumarr.VALUES). - refarr(Arrays.asList(":parent:", ":parent", "parent:")). // test collection based setter + refarr(List.of(":parent:", ":parent", "parent:")). // test collection based setter fileArr("bin"). urlArr(new UrlReference("http://docs.vespa.ai")). modelArr(ModelReference.unresolved(Optional.empty(), diff --git a/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java b/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java index a9151692bb5..f8d16fa7ac3 100644 --- a/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java +++ b/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java @@ -3,7 +3,6 @@ package com.yahoo.config; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -73,7 +72,7 @@ public class NodeVectorTest { assertTrue(v.contains(val)); assertFalse(v.contains(barNode())); assertTrue(v.contains(val)); - assertFalse(v.containsAll(Arrays.asList(val, barNode()))); + assertFalse(v.containsAll(List.of(val, barNode()))); } @Test @@ -114,7 +113,7 @@ public class NodeVectorTest { private static class TestNodeVector extends LeafNodeVector<String, StringNode> { TestNodeVector(String... values) { - super(Arrays.asList(values), new StringNode()); + super(List.of(values), new StringNode()); } } diff --git a/config-model-api/src/main/java/com/yahoo/config/application/api/ApplicationPackage.java b/config-model-api/src/main/java/com/yahoo/config/application/api/ApplicationPackage.java index 0f89608f9bd..deef16cfe8c 100644 --- a/config-model-api/src/main/java/com/yahoo/config/application/api/ApplicationPackage.java +++ b/config-model-api/src/main/java/com/yahoo/config/application/api/ApplicationPackage.java @@ -14,7 +14,6 @@ import java.io.File; import java.io.IOException; import java.io.Reader; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -213,11 +212,11 @@ public interface ApplicationPackage { } default Map<Version, FileRegistry> getFileRegistries() { - return Collections.emptyMap(); + return Map.of(); } default Map<String, String> legacyOverrides() { - return Collections.emptyMap(); + return Map.of(); } /** diff --git a/config-model-api/src/main/java/com/yahoo/config/application/api/DeploymentSpec.java b/config-model-api/src/main/java/com/yahoo/config/application/api/DeploymentSpec.java index 16cd7bf7e88..4308e0c2a0e 100644 --- a/config-model-api/src/main/java/com/yahoo/config/application/api/DeploymentSpec.java +++ b/config-model-api/src/main/java/com/yahoo/config/application/api/DeploymentSpec.java @@ -386,7 +386,7 @@ public class DeploymentSpec { public abstract boolean concerns(Environment environment, Optional<RegionName> region); /** Returns the zones deployed to in this step. */ - public List<DeclaredZone> zones() { return Collections.emptyList(); } + public List<DeclaredZone> zones() { return List.of(); } /** The delay introduced by this step (beyond the time it takes to execute the step). */ public Duration delay() { return Duration.ZERO; } diff --git a/config-model-api/src/main/java/com/yahoo/config/application/api/Notifications.java b/config-model-api/src/main/java/com/yahoo/config/application/api/Notifications.java index 9eef386d7d0..08fb4d75183 100644 --- a/config-model-api/src/main/java/com/yahoo/config/application/api/Notifications.java +++ b/config-model-api/src/main/java/com/yahoo/config/application/api/Notifications.java @@ -4,14 +4,11 @@ package com.yahoo.config.application.api; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; -import static java.util.Collections.emptyList; - /** * Configuration of notifications for deployment jobs. * @@ -25,7 +22,7 @@ import static java.util.Collections.emptyList; */ public class Notifications { - private static final Notifications none = new Notifications(Collections.emptyMap(), Collections.emptyMap()); + private static final Notifications none = new Notifications(Map.of(), Map.of()); public static Notifications none() { return none; } private final Map<When, List<String>> emailAddresses; @@ -60,7 +57,7 @@ public class Notifications { /** Returns all email addresses to notify for the given condition. */ public Set<String> emailAddressesFor(When when) { ImmutableSet.Builder<String> addresses = ImmutableSet.builder(); - addresses.addAll(emailAddresses.getOrDefault(when, emptyList())); + addresses.addAll(emailAddresses.getOrDefault(when, List.of())); for (When include : when.includes) addresses.addAll(emailAddressesFor(include)); return addresses.build(); @@ -69,7 +66,7 @@ public class Notifications { /** Returns all roles for which email notification is to be sent for the given condition. */ public Set<Role> emailRolesFor(When when) { ImmutableSet.Builder<Role> roles = ImmutableSet.builder(); - roles.addAll(emailRoles.getOrDefault(when, emptyList())); + roles.addAll(emailRoles.getOrDefault(when, List.of())); for (When include : when.includes) roles.addAll(emailRolesFor(include)); return roles.build(); @@ -82,17 +79,17 @@ public class Notifications { author; public static String toValue(Role role) { - switch (role) { - case author: return "author"; - default: throw new IllegalArgumentException("Unexpected constant '" + role.name() + "'."); + if (Objects.requireNonNull(role) == Role.author) { + return "author"; } + throw new IllegalArgumentException("Unexpected constant '" + role.name() + "'."); } public static Role fromValue(String value) { - switch (value) { - case "author": return author; - default: throw new IllegalArgumentException("Unknown value '" + value + "'."); + if (value.equals("author")) { + return author; } + throw new IllegalArgumentException("Unknown value '" + value + "'."); } } @@ -109,15 +106,15 @@ public class Notifications { private final List<When> includes; When(When... includes) { - this.includes = Arrays.asList(includes); + this.includes = List.of(includes); } public static String toValue(When when) { - switch (when) { - case failing: return "failing"; - case failingCommit: return "failing-commit"; - default: throw new IllegalArgumentException("Unexpected constant '" + when.name() + "'."); - } + return switch (when) { + case failing -> "failing"; + case failingCommit -> "failing-commit"; + default -> throw new IllegalArgumentException("Unexpected constant '" + when.name() + "'."); + }; } public static When fromValue(String value) { diff --git a/config-model-api/src/main/java/com/yahoo/config/model/api/SuperModel.java b/config-model-api/src/main/java/com/yahoo/config/model/api/SuperModel.java index 3424dad4ee5..f6bc8c34aa6 100644 --- a/config-model-api/src/main/java/com/yahoo/config/model/api/SuperModel.java +++ b/config-model-api/src/main/java/com/yahoo/config/model/api/SuperModel.java @@ -6,7 +6,6 @@ import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.TenantName; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -23,7 +22,7 @@ public class SuperModel { private final boolean complete; public SuperModel() { - this(Collections.emptyMap(), false); + this(Map.of(), false); } public SuperModel(Map<ApplicationId, ApplicationInfo> models, boolean complete) { diff --git a/config-model-api/src/test/java/com/yahoo/config/application/api/DeploymentSpecTest.java b/config-model-api/src/test/java/com/yahoo/config/application/api/DeploymentSpecTest.java index 99c9dad02de..05807ae6cc1 100644 --- a/config-model-api/src/test/java/com/yahoo/config/application/api/DeploymentSpecTest.java +++ b/config-model-api/src/test/java/com/yahoo/config/application/api/DeploymentSpecTest.java @@ -23,7 +23,6 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -1152,7 +1151,7 @@ public class DeploymentSpecTest { <instance id='default'/> </deployment> """); - assertEquals(Collections.emptyList(), spec.requireInstance("default").endpoints()); + assertEquals(List.of(), spec.requireInstance("default").endpoints()); assertEquals(ZoneEndpoint.defaultEndpoint, spec.zoneEndpoint(InstanceName.defaultName(), defaultId(), ClusterSpec.Id.from("cluster"))); diff --git a/config-model-api/src/test/java/com/yahoo/config/application/api/DeploymentSpecWithoutInstanceTest.java b/config-model-api/src/test/java/com/yahoo/config/application/api/DeploymentSpecWithoutInstanceTest.java index e102e3afaa7..e25069fdc3a 100644 --- a/config-model-api/src/test/java/com/yahoo/config/application/api/DeploymentSpecWithoutInstanceTest.java +++ b/config-model-api/src/test/java/com/yahoo/config/application/api/DeploymentSpecWithoutInstanceTest.java @@ -16,7 +16,6 @@ import java.io.StringReader; import java.time.Duration; import java.time.Instant; import java.time.ZoneId; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -599,7 +598,7 @@ public class DeploymentSpecWithoutInstanceTest { @Test public void emptyEndpoints() { var spec = DeploymentSpec.fromXml("<deployment><endpoints/></deployment>"); - assertEquals(Collections.emptyList(), spec.requireInstance("default").endpoints()); + assertEquals(List.of(), spec.requireInstance("default").endpoints()); } @Test diff --git a/config-model-api/src/test/java/com/yahoo/config/model/api/HostInfoTest.java b/config-model-api/src/test/java/com/yahoo/config/model/api/HostInfoTest.java index 6bd94d0aa74..7e4b0a07952 100644 --- a/config-model-api/src/test/java/com/yahoo/config/model/api/HostInfoTest.java +++ b/config-model-api/src/test/java/com/yahoo/config/model/api/HostInfoTest.java @@ -2,7 +2,8 @@ package com.yahoo.config.model.api; import org.junit.Test; -import java.util.Arrays; + +import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -10,10 +11,10 @@ import static org.junit.Assert.assertNotEquals; public class HostInfoTest { @Test public void testEquals() { - HostInfo a = new HostInfo("foo.yahoo.com", Arrays.asList(new ServiceInfo("foo", "bar", null, null, "config-id", "host-name"))); - HostInfo b = new HostInfo("foo.yahoo.com", Arrays.asList(new ServiceInfo("foo", "bar", null, null, "config-id", "host-name"))); - HostInfo c = new HostInfo("foo.yahoo.com", Arrays.asList(new ServiceInfo("foo", "baz", null, null, "config-id", "host-name"))); - HostInfo d = new HostInfo("foo.yahoo.com", Arrays.asList(new ServiceInfo("bar", "baz", null, null, "config-id", "host-name"))); + HostInfo a = new HostInfo("foo.yahoo.com", List.of(new ServiceInfo("foo", "bar", null, null, "config-id", "host-name"))); + HostInfo b = new HostInfo("foo.yahoo.com", List.of(new ServiceInfo("foo", "bar", null, null, "config-id", "host-name"))); + HostInfo c = new HostInfo("foo.yahoo.com", List.of(new ServiceInfo("foo", "baz", null, null, "config-id", "host-name"))); + HostInfo d = new HostInfo("foo.yahoo.com", List.of(new ServiceInfo("bar", "baz", null, null, "config-id", "host-name"))); HostInfo e = new HostInfo("bar.yahoo.com", null); assertEquals(a, b); assertNotEquals(a, c); diff --git a/config-model-api/src/test/java/com/yahoo/config/model/api/PortInfoTest.java b/config-model-api/src/test/java/com/yahoo/config/model/api/PortInfoTest.java index 08e00e5c771..3ee9217e67f 100644 --- a/config-model-api/src/test/java/com/yahoo/config/model/api/PortInfoTest.java +++ b/config-model-api/src/test/java/com/yahoo/config/model/api/PortInfoTest.java @@ -3,7 +3,7 @@ package com.yahoo.config.model.api; import org.junit.Test; -import java.util.Arrays; +import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -11,10 +11,10 @@ import static org.junit.Assert.assertNotEquals; public class PortInfoTest { @Test public void testEquals() { - PortInfo a = new PortInfo(1234, Arrays.asList("foo")); - PortInfo b = new PortInfo(1234, Arrays.asList("foo")); - PortInfo c = new PortInfo(1234, Arrays.asList("foo", "bar")); - PortInfo d = new PortInfo(12345, Arrays.asList("foo")); + PortInfo a = new PortInfo(1234, List.of("foo")); + PortInfo b = new PortInfo(1234, List.of("foo")); + PortInfo c = new PortInfo(1234, List.of("foo", "bar")); + PortInfo d = new PortInfo(12345, List.of("foo")); assertEquals(a, b); assertNotEquals(a, c); assertNotEquals(a, d); diff --git a/config-model-api/src/test/java/com/yahoo/config/model/api/ServiceInfoTest.java b/config-model-api/src/test/java/com/yahoo/config/model/api/ServiceInfoTest.java index f1824763c12..b249b82d818 100644 --- a/config-model-api/src/test/java/com/yahoo/config/model/api/ServiceInfoTest.java +++ b/config-model-api/src/test/java/com/yahoo/config/model/api/ServiceInfoTest.java @@ -3,8 +3,8 @@ package com.yahoo.config.model.api; import org.junit.Test; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -17,14 +17,14 @@ public class ServiceInfoTest { String commonConfigId = "common-config-id"; String commonHostName = "common-host"; - ServiceInfo a = new ServiceInfo("0", "0", Arrays.asList(new PortInfo(33, null)), Collections.singletonMap("foo", "bar"), commonConfigId, commonHostName); - ServiceInfo b = new ServiceInfo("0", "0", Arrays.asList(new PortInfo(33, null)), Collections.singletonMap("foo", "bar"), commonConfigId, commonHostName); - ServiceInfo c = new ServiceInfo("0", "0", Arrays.asList(new PortInfo(33, null)), Collections.singletonMap("foo", "baz"), commonConfigId, commonHostName); - ServiceInfo d = new ServiceInfo("0", "0", Arrays.asList(new PortInfo(33, null)), Collections.singletonMap("bar", "bar"), commonConfigId, commonHostName); - ServiceInfo e = new ServiceInfo("0", "1", Arrays.asList(new PortInfo(33, null)), Collections.singletonMap("foo", "bar"), commonConfigId, commonHostName); - ServiceInfo f = new ServiceInfo("1", "0", Arrays.asList(new PortInfo(33, null)), Collections.singletonMap("foo", "bar"), commonConfigId, commonHostName); - ServiceInfo g = new ServiceInfo("1", "0", Arrays.asList(new PortInfo(33, null)), Collections.singletonMap("foo", "bar"), "different-config-id", commonHostName); - ServiceInfo h = new ServiceInfo("1", "0", Arrays.asList(new PortInfo(33, null)), Collections.singletonMap("foo", "bar"), commonConfigId, "different-host"); + ServiceInfo a = new ServiceInfo("0", "0", List.of(new PortInfo(33, null)), Map.of("foo", "bar"), commonConfigId, commonHostName); + ServiceInfo b = new ServiceInfo("0", "0", List.of(new PortInfo(33, null)), Map.of("foo", "bar"), commonConfigId, commonHostName); + ServiceInfo c = new ServiceInfo("0", "0", List.of(new PortInfo(33, null)), Map.of("foo", "baz"), commonConfigId, commonHostName); + ServiceInfo d = new ServiceInfo("0", "0", List.of(new PortInfo(33, null)), Map.of("bar", "bar"), commonConfigId, commonHostName); + ServiceInfo e = new ServiceInfo("0", "1", List.of(new PortInfo(33, null)), Map.of("foo", "bar"), commonConfigId, commonHostName); + ServiceInfo f = new ServiceInfo("1", "0", List.of(new PortInfo(33, null)), Map.of("foo", "bar"), commonConfigId, commonHostName); + ServiceInfo g = new ServiceInfo("1", "0", List.of(new PortInfo(33, null)), Map.of("foo", "bar"), "different-config-id", commonHostName); + ServiceInfo h = new ServiceInfo("1", "0", List.of(new PortInfo(33, null)), Map.of("foo", "bar"), commonConfigId, "different-host"); assertEquals(a, b); assertNotEquals(a, c); diff --git a/config-model/src/main/java/com/yahoo/config/model/ConfigModelRegistry.java b/config-model/src/main/java/com/yahoo/config/model/ConfigModelRegistry.java index 51bd01de5bc..f25f130eed0 100644 --- a/config-model/src/main/java/com/yahoo/config/model/ConfigModelRegistry.java +++ b/config-model/src/main/java/com/yahoo/config/model/ConfigModelRegistry.java @@ -5,7 +5,7 @@ import com.yahoo.config.model.builder.xml.ConfigModelBuilder; import com.yahoo.config.model.builder.xml.ConfigModelId; import java.util.Collection; -import java.util.Collections; +import java.util.List; /** * A resolver of implementations of named config models. @@ -44,7 +44,7 @@ public abstract class ConfigModelRegistry { @Override public Collection<ConfigModelBuilder> resolve(ConfigModelId id) { - return Collections.emptyList(); + return List.of(); } } diff --git a/config-model/src/main/java/com/yahoo/config/model/MapConfigModelRegistry.java b/config-model/src/main/java/com/yahoo/config/model/MapConfigModelRegistry.java index 8fe1372ef2f..7242d3de1dd 100644 --- a/config-model/src/main/java/com/yahoo/config/model/MapConfigModelRegistry.java +++ b/config-model/src/main/java/com/yahoo/config/model/MapConfigModelRegistry.java @@ -7,7 +7,6 @@ import com.yahoo.config.model.builder.xml.ConfigModelBuilder; import com.yahoo.config.model.builder.xml.ConfigModelId; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; @@ -58,7 +57,7 @@ public class MapConfigModelRegistry extends ConfigModelRegistry { @SafeVarargs @SuppressWarnings("varargs") public static ConfigModelRegistry createFromList(ConfigModelBuilder<? extends ConfigModel> ... builders) { - return new MapConfigModelRegistry(Arrays.asList(builders)); + return new MapConfigModelRegistry(List.of(builders)); } } diff --git a/config-model/src/main/java/com/yahoo/config/model/deploy/DeployState.java b/config-model/src/main/java/com/yahoo/config/model/deploy/DeployState.java index f19341098f4..57a75bd8a38 100644 --- a/config-model/src/main/java/com/yahoo/config/model/deploy/DeployState.java +++ b/config-model/src/main/java/com/yahoo/config/model/deploy/DeployState.java @@ -50,7 +50,6 @@ import java.io.Reader; import java.io.UncheckedIOException; import java.time.Instant; import java.util.Collection; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -329,7 +328,7 @@ public class DeployState implements ConfigDefinitionStore { private Optional<ConfigDefinitionRepo> configDefinitionRepo = Optional.empty(); private Optional<Model> previousModel = Optional.empty(); private Set<ContainerEndpoint> endpoints = Set.of(); - private Collection<MlModelImporter> modelImporters = Collections.emptyList(); + private Collection<MlModelImporter> modelImporters = List.of(); private Zone zone = Zone.defaultZone(); private Instant now = Instant.now(); private Version wantedNodeVespaVersion = Vtag.currentVersion; diff --git a/config-model/src/main/java/com/yahoo/config/model/deploy/TestProperties.java b/config-model/src/main/java/com/yahoo/config/model/deploy/TestProperties.java index 11d3a48ee51..3e91b8afe88 100644 --- a/config-model/src/main/java/com/yahoo/config/model/deploy/TestProperties.java +++ b/config-model/src/main/java/com/yahoo/config/model/deploy/TestProperties.java @@ -19,7 +19,6 @@ import com.yahoo.vespa.model.container.ApplicationContainerCluster; import java.net.URI; import java.security.cert.X509Certificate; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; @@ -35,10 +34,10 @@ public class TestProperties implements ModelContext.Properties, ModelContext.Fea private boolean multitenant = false; private ApplicationId applicationId = ApplicationId.defaultId(); - private List<ConfigServerSpec> configServerSpecs = Collections.emptyList(); + private List<ConfigServerSpec> configServerSpecs = List.of(); private boolean hostedVespa = false; private Zone zone = Zone.defaultZone(); - private final Set<ContainerEndpoint> endpoints = Collections.emptySet(); + private final Set<ContainerEndpoint> endpoints = Set.of(); private boolean useDedicatedNodeForLogserver = false; private double defaultTermwiseLimit = 1.0; private String jvmGCOptions = null; @@ -55,10 +54,10 @@ public class TestProperties implements ModelContext.Properties, ModelContext.Fea private double feedConcurrency = 0.5; private double feedNiceness = 0.0; private int maxActivationInhibitedOutOfSyncGroups = 0; - private List<TenantSecretStore> tenantSecretStores = Collections.emptyList(); + private List<TenantSecretStore> tenantSecretStores = List.of(); private String jvmOmitStackTraceInFastThrowOption; private boolean allowDisableMtls = true; - private List<X509Certificate> operatorCertificates = Collections.emptyList(); + private List<X509Certificate> operatorCertificates = List.of(); private double resourceLimitDisk = 0.75; private double resourceLimitMemory = 0.8; private double minNodeRatioPerGroup = 0.0; diff --git a/config-model/src/main/java/com/yahoo/config/model/graph/ModelNode.java b/config-model/src/main/java/com/yahoo/config/model/graph/ModelNode.java index e411a8e3e77..dcf1c8629a4 100644 --- a/config-model/src/main/java/com/yahoo/config/model/graph/ModelNode.java +++ b/config-model/src/main/java/com/yahoo/config/model/graph/ModelNode.java @@ -135,7 +135,7 @@ public class ModelNode<MODEL extends ConfigModel> implements ConfigModelInstance } // For collections, we don't require that dependency has been added, we just give an empty collection if (isCollection(param)) - return Collections.emptyList(); + return List.of(); throw new IllegalArgumentException("Unable to find constructor argument " + param + " for " + clazz.getName()); } diff --git a/config-model/src/main/java/com/yahoo/config/model/test/MockApplicationPackage.java b/config-model/src/main/java/com/yahoo/config/model/test/MockApplicationPackage.java index 5d3db7f676a..365543a549b 100644 --- a/config-model/src/main/java/com/yahoo/config/model/test/MockApplicationPackage.java +++ b/config-model/src/main/java/com/yahoo/config/model/test/MockApplicationPackage.java @@ -31,7 +31,6 @@ import java.io.UncheckedIOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; @@ -143,7 +142,7 @@ public class MockApplicationPackage implements ApplicationPackage { @Override public Map<ConfigDefinitionKey, UnparsedConfigDefinition> getAllExistingConfigDefs() { - return Collections.emptyMap(); + return Map.of(); } @Override @@ -203,7 +202,7 @@ public class MockApplicationPackage implements ApplicationPackage { } public List<ComponentInfo> getComponentsInfo(Version vespaVersion) { - return Collections.emptyList(); + return List.of(); } public QueryProfileRegistry getQueryProfiles() { return queryProfileRegistry; } @@ -240,7 +239,7 @@ public class MockApplicationPackage implements ApplicationPackage { private File root = new File("nonexisting"); private String hosts = null; private String services = null; - private List<String> schemas = Collections.emptyList(); + private List<String> schemas = List.of(); private Map<Path, MockApplicationFile> files = new LinkedHashMap<>(); private String schemaDir = null; private String deploymentSpec = null; @@ -277,12 +276,12 @@ public class MockApplicationPackage implements ApplicationPackage { } public Builder withSearchDefinition(String searchDefinition) { - this.schemas = Collections.singletonList(searchDefinition); + this.schemas = List.of(searchDefinition); return this; } public Builder withSchemas(List<String> searchDefinition) { - this.schemas = Collections.unmodifiableList(searchDefinition); + this.schemas = List.copyOf(searchDefinition); return this; } @@ -369,8 +368,8 @@ public class MockApplicationPackage implements ApplicationPackage { } private List<NamedReader> asNamedReaderList(String value) { - if (value == null) return Collections.emptyList(); - return Collections.singletonList(new NamedReader(extractId(value) + ".xml", new StringReader(value))); + if (value == null) return List.of(); + return List.of(new NamedReader(extractId(value) + ".xml", new StringReader(value))); } private String extractId(String xmlStringWithIdAttribute) { diff --git a/config-model/src/main/java/com/yahoo/config/model/test/TestUtil.java b/config-model/src/main/java/com/yahoo/config/model/test/TestUtil.java index 94969aa5324..509c10c7fc9 100644 --- a/config-model/src/main/java/com/yahoo/config/model/test/TestUtil.java +++ b/config-model/src/main/java/com/yahoo/config/model/test/TestUtil.java @@ -6,7 +6,6 @@ import com.yahoo.config.model.builder.xml.XmlHelper; import org.w3c.dom.Element; import java.io.StringReader; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -20,7 +19,7 @@ public class TestUtil { public static Element parse(String... xmlLines) { List<String> lines = new ArrayList<>(); lines.add("<?xml version='1.0' encoding='utf-8' ?>"); - lines.addAll(Arrays.asList(xmlLines)); + lines.addAll(List.of(xmlLines)); try { return XmlHelper.getDocument(new StringReader(CollectionUtil.mkString(lines, "\n").replace("'", "\""))).getDocumentElement(); diff --git a/config-model/src/main/java/com/yahoo/documentmodel/NewDocumentType.java b/config-model/src/main/java/com/yahoo/documentmodel/NewDocumentType.java index 77e123fefef..c5140dd6fc8 100644 --- a/config-model/src/main/java/com/yahoo/documentmodel/NewDocumentType.java +++ b/config-model/src/main/java/com/yahoo/documentmodel/NewDocumentType.java @@ -25,7 +25,6 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import static java.util.Collections.emptySet; /** * @author baldersheim @@ -47,7 +46,7 @@ public final class NewDocumentType extends StructuredDataType implements DataTyp private final Set<String> importedFieldNames; public NewDocumentType(Name name) { - this(name, emptySet()); + this(name, Set.of()); } public NewDocumentType(Name name, Set<Name> documentReferences, Set<String> importedFieldNames) { @@ -60,7 +59,7 @@ public final class NewDocumentType extends StructuredDataType implements DataTyp } public NewDocumentType(Name name, Set<Name> documentReferences) { - this(name, documentReferences, emptySet()); + this(name, documentReferences, Set.of()); } public NewDocumentType(Name name, @@ -74,8 +73,8 @@ public final class NewDocumentType extends StructuredDataType implements DataTyp if (fs != null) { this.fieldSets.addAll(fs.userFieldSets().values()); for (FieldSet f : fs.builtInFieldSets().values()) { - if ((f.getName() != BuiltInFieldSets.INTERNAL_FIELDSET_NAME) && - (f.getName() != BuiltInFieldSets.SEARCH_FIELDSET_NAME)) { + if (!BuiltInFieldSets.INTERNAL_FIELDSET_NAME.equals(f.getName()) && + !BuiltInFieldSets.SEARCH_FIELDSET_NAME.equals(f.getName())) { fieldSets.add(f); } } diff --git a/config-model/src/main/java/com/yahoo/schema/ApplicationBuilder.java b/config-model/src/main/java/com/yahoo/schema/ApplicationBuilder.java index 2e964ac3624..749cdbfd8b7 100644 --- a/config-model/src/main/java/com/yahoo/schema/ApplicationBuilder.java +++ b/config-model/src/main/java/com/yahoo/schema/ApplicationBuilder.java @@ -27,7 +27,6 @@ import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; @@ -351,7 +350,7 @@ public class ApplicationBuilder { RankProfileRegistry rankProfileRegistry, QueryProfileRegistry queryprofileRegistry) throws IOException, ParseException { - return createFromFiles(Collections.singletonList(fileName), new MockFileRegistry(), deployLogger, new TestProperties(), + return createFromFiles(List.of(fileName), new MockFileRegistry(), deployLogger, new TestProperties(), rankProfileRegistry, queryprofileRegistry); } @@ -414,8 +413,8 @@ public class ApplicationBuilder { queryProfileRegistry); var fnli = Files.list(new File(dir).toPath()) - .map(p -> p.toString()) - .filter(fn -> AbstractApplicationPackage.validSchemaFilename(fn)) + .map(java.nio.file.Path::toString) + .filter(AbstractApplicationPackage::validSchemaFilename) .sorted(); for (var i = fnli.iterator(); i.hasNext(); ) { builder.addSchemaFile(i.next()); diff --git a/config-model/src/main/java/com/yahoo/schema/FieldSets.java b/config-model/src/main/java/com/yahoo/schema/FieldSets.java index 1dbf496992b..6464bd1681e 100644 --- a/config-model/src/main/java/com/yahoo/schema/FieldSets.java +++ b/config-model/src/main/java/com/yahoo/schema/FieldSets.java @@ -47,11 +47,7 @@ public class FieldSets { * @param field field to add to field set */ public void addBuiltInFieldSetItem(String setName, String field) { - if (builtInFieldSets.get(setName) == null) { - // First entry in this set - builtInFieldSets.put(setName, new FieldSet(setName)); - } - builtInFieldSets.get(setName).addFieldName(field); + builtInFieldSets.computeIfAbsent(setName, FieldSet::new).addFieldName(field); } /** Returns the built in field sets, unmodifiable */ diff --git a/config-model/src/main/java/com/yahoo/schema/RankProfile.java b/config-model/src/main/java/com/yahoo/schema/RankProfile.java index 22bf1880cd7..82ed45028b3 100644 --- a/config-model/src/main/java/com/yahoo/schema/RankProfile.java +++ b/config-model/src/main/java/com/yahoo/schema/RankProfile.java @@ -32,7 +32,6 @@ import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -487,12 +486,12 @@ public class RankProfile implements Cloneable { } void setFirstPhaseRanking(RankingExpression rankingExpression) { - this.firstPhaseRanking = new RankingExpressionFunction(new ExpressionFunction(FIRST_PHASE, Collections.emptyList(), rankingExpression), false); + this.firstPhaseRanking = new RankingExpressionFunction(new ExpressionFunction(FIRST_PHASE, List.of(), rankingExpression), false); } public void setFirstPhaseRanking(String expression) { try { - firstPhaseRanking = new RankingExpressionFunction(parseRankingExpression(FIRST_PHASE, Collections.emptyList(), expression), false); + firstPhaseRanking = new RankingExpressionFunction(parseRankingExpression(FIRST_PHASE, List.of(), expression), false); } catch (ParseException e) { throw new IllegalArgumentException("Illegal first phase ranking function", e); } @@ -515,7 +514,7 @@ public class RankProfile implements Cloneable { public void setSecondPhaseRanking(String expression) { try { - secondPhaseRanking = new RankingExpressionFunction(parseRankingExpression(SECOND_PHASE, Collections.emptyList(), expression), false); + secondPhaseRanking = new RankingExpressionFunction(parseRankingExpression(SECOND_PHASE, List.of(), expression), false); } catch (ParseException e) { throw new IllegalArgumentException("Illegal second phase ranking function", e); @@ -535,7 +534,7 @@ public class RankProfile implements Cloneable { public void setGlobalPhaseRanking(String expression) { try { - globalPhaseRanking = new RankingExpressionFunction(parseRankingExpression(GLOBAL_PHASE, Collections.emptyList(), expression), false); + globalPhaseRanking = new RankingExpressionFunction(parseRankingExpression(GLOBAL_PHASE, List.of(), expression), false); } catch (ParseException e) { throw new IllegalArgumentException("Illegal global-phase ranking function", e); @@ -1036,7 +1035,7 @@ public class RankProfile implements Cloneable { Map<Reference, TensorType> featureTypes = featureTypes(); // Function compiling first pass: compile inline functions without resolving other functions Map<String, RankingExpressionFunction> inlineFunctions = - compileFunctions(this::getInlineFunctions, queryProfiles, featureTypes, importedModels, Collections.emptyMap(), expressionTransforms); + compileFunctions(this::getInlineFunctions, queryProfiles, featureTypes, importedModels, Map.of(), expressionTransforms); firstPhaseRanking = compile(this.getFirstPhase(), queryProfiles, featureTypes, importedModels, constants(), inlineFunctions, expressionTransforms); secondPhaseRanking = compile(this.getSecondPhase(), queryProfiles, featureTypes, importedModels, constants(), inlineFunctions, expressionTransforms); diff --git a/config-model/src/main/java/com/yahoo/schema/RankProfileRegistry.java b/config-model/src/main/java/com/yahoo/schema/RankProfileRegistry.java index 0fddcbd4cc7..4deee1dce9f 100644 --- a/config-model/src/main/java/com/yahoo/schema/RankProfileRegistry.java +++ b/config-model/src/main/java/com/yahoo/schema/RankProfileRegistry.java @@ -4,9 +4,7 @@ package com.yahoo.schema; import com.yahoo.schema.document.SDDocumentType; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -27,7 +25,7 @@ public class RankProfileRegistry { private static final String globalRankProfilesKey = "[global]"; /* These rank profiles can be overridden: 'default' rank profile, as that is documented to work. And 'unranked'. */ - static final Set<String> overridableRankProfileNames = new HashSet<>(Arrays.asList("default", "unranked")); + static final Set<String> overridableRankProfileNames = Set.of("default", "unranked"); public static RankProfileRegistry createRankProfileRegistryWithBuiltinRankProfiles(Schema schema) { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); diff --git a/config-model/src/main/java/com/yahoo/schema/derived/Deriver.java b/config-model/src/main/java/com/yahoo/schema/derived/Deriver.java index 9774868db9c..0c669e29538 100644 --- a/config-model/src/main/java/com/yahoo/schema/derived/Deriver.java +++ b/config-model/src/main/java/com/yahoo/schema/derived/Deriver.java @@ -7,7 +7,6 @@ import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.configmodel.producers.DocumentManager; import com.yahoo.vespa.configmodel.producers.DocumentTypes; import java.io.IOException; -import java.util.Collections; import java.util.List; /** @@ -30,7 +29,7 @@ public class Deriver { } public static DocumentmanagerConfig.Builder getDocumentManagerConfig(String sd) { - return getDocumentManagerConfig(Collections.singletonList(sd)); + return getDocumentManagerConfig(List.of(sd)); } public static DocumentmanagerConfig.Builder getDocumentManagerConfig(List<String> schemas) { @@ -38,7 +37,7 @@ public class Deriver { } public static DocumenttypesConfig.Builder getDocumentTypesConfig(String schema) { - return getDocumentTypesConfig(Collections.singletonList(schema)); + return getDocumentTypesConfig(List.of(schema)); } public static DocumenttypesConfig.Builder getDocumentTypesConfig(List<String> schemas) { diff --git a/config-model/src/main/java/com/yahoo/schema/derived/IndexSchema.java b/config-model/src/main/java/com/yahoo/schema/derived/IndexSchema.java index 34ed9f2f60c..677e4b31bdf 100644 --- a/config-model/src/main/java/com/yahoo/schema/derived/IndexSchema.java +++ b/config-model/src/main/java/com/yahoo/schema/derived/IndexSchema.java @@ -14,7 +14,6 @@ import com.yahoo.vespa.config.search.IndexschemaConfig; import java.io.IOException; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; @@ -147,7 +146,7 @@ public class IndexSchema extends Derived { static List<Field> flattenField(Field field) { DataType fieldType = field.getDataType(); if (fieldType.getPrimitiveType() != null){ - return Collections.singletonList(field); + return List.of(field); } if (fieldType instanceof ArrayDataType) { List<Field> ret = new LinkedList<>(); diff --git a/config-model/src/main/java/com/yahoo/schema/document/Attribute.java b/config-model/src/main/java/com/yahoo/schema/document/Attribute.java index 999d040b48c..ac936ee989e 100644 --- a/config-model/src/main/java/com/yahoo/schema/document/Attribute.java +++ b/config-model/src/main/java/com/yahoo/schema/document/Attribute.java @@ -5,7 +5,9 @@ import com.yahoo.document.ArrayDataType; import com.yahoo.document.CollectionDataType; import com.yahoo.document.DataType; import com.yahoo.document.DocumentType; +import com.yahoo.document.MapDataType; import com.yahoo.document.PrimitiveDataType; +import com.yahoo.document.StructDataType; import com.yahoo.documentmodel.NewDocumentReferenceDataType; import com.yahoo.document.StructuredDataType; import com.yahoo.document.TensorDataType; @@ -143,8 +145,8 @@ public final class Attribute implements Cloneable, Serializable { } /** Creates an attribute with default settings */ - public Attribute(String name, DataType fieldType) { - this(name, convertDataType(fieldType), convertCollectionType(fieldType), convertTensorType(fieldType), convertTargetType(fieldType)); + public Attribute(String schemaName, String fieldName, String name, DataType fieldType) { + this(name, convertDataType(schemaName, fieldName, fieldType), convertCollectionType(fieldType), convertTensorType(fieldType), convertTargetType(fieldType)); setRemoveIfZero(fieldType instanceof WeightedSetDataType wsdt && wsdt.removeIfZero()); setCreateIfNonExistent(fieldType instanceof WeightedSetDataType wsdt && wsdt.createIfNonExistent()); } @@ -266,12 +268,26 @@ public final class Attribute implements Cloneable, Serializable { private void setType(Type type) { this.type=type; } public void setCollectionType(CollectionType type) { this.collectionType=type; } + private static void failDataType(String schemaName, String fieldName, String dataType) throws IllegalArgumentException { + throw new IllegalArgumentException("For schema '" + schemaName + "': Field '" + fieldName + "' of type '" + dataType + "' cannot be an attribute. " + + "Instead specify the struct fields to be searchable as attribute"); + } + public static void validateDataType(String schemaName, String fieldName, DataType fieldType) throws IllegalArgumentException { + if (fieldType instanceof MapDataType mapType) { + failDataType(schemaName, fieldName, "map<" + mapType.getKeyType().getName() + "," + mapType.getValueType().getName() + ">"); + } + if (fieldType instanceof ArrayDataType arrayType && arrayType.getNestedType() instanceof StructDataType nestedType) { + failDataType(schemaName, fieldName, "array<" + nestedType.getName() + ">"); + } + } + /** Converts to the right attribute type from a field datatype */ - public static Type convertDataType(DataType fieldType) { + public static Type convertDataType(String schemaName, String fieldName, DataType fieldType) { + validateDataType(schemaName, fieldName, fieldType); if (fieldType instanceof NewDocumentReferenceDataType) { return Type.REFERENCE; } else if (fieldType instanceof CollectionDataType) { - return convertDataType(((CollectionDataType) fieldType).getNestedType()); + return convertDataType(schemaName, fieldName, ((CollectionDataType) fieldType).getNestedType()); } FieldValue fval = fieldType.createFieldValue(); if (fval instanceof StringFieldValue) { diff --git a/config-model/src/main/java/com/yahoo/schema/document/ImmutableImportedSDField.java b/config-model/src/main/java/com/yahoo/schema/document/ImmutableImportedSDField.java index cb98cb79e01..7ade7ada061 100644 --- a/config-model/src/main/java/com/yahoo/schema/document/ImmutableImportedSDField.java +++ b/config-model/src/main/java/com/yahoo/schema/document/ImmutableImportedSDField.java @@ -10,7 +10,6 @@ import com.yahoo.vespa.indexinglanguage.expressions.Expression; import com.yahoo.vespa.indexinglanguage.expressions.ScriptExpression; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Map; @@ -131,7 +130,7 @@ public class ImmutableImportedSDField implements ImmutableSDField { @Override public Map<String, String> getAliasToName() { - return Collections.emptyMap(); + return Map.of(); } @Override diff --git a/config-model/src/main/java/com/yahoo/schema/document/SDField.java b/config-model/src/main/java/com/yahoo/schema/document/SDField.java index 538cb56d210..f165141b16e 100644 --- a/config-model/src/main/java/com/yahoo/schema/document/SDField.java +++ b/config-model/src/main/java/com/yahoo/schema/document/SDField.java @@ -398,22 +398,23 @@ public class SDField extends Field implements TypedKey, ImmutableSDField { } /** Parse an indexing expression which will use the simple linguistics implementation suitable for testing */ - public void parseIndexingScript(String script) { - parseIndexingScript(script, new SimpleLinguistics(), Embedder.throwsOnUse.asMap()); + public void parseIndexingScript(String schemaName, String script) { + parseIndexingScript(schemaName, script, new SimpleLinguistics(), Embedder.throwsOnUse.asMap()); } - public void parseIndexingScript(String script, Linguistics linguistics, Map<String, Embedder> embedders) { + public void parseIndexingScript(String schemaName, String script, Linguistics linguistics, Map<String, Embedder> embedders) { try { ScriptParserContext config = new ScriptParserContext(linguistics, embedders); config.setInputStream(new IndexingInput(script)); - setIndexingScript(ScriptExpression.newInstance(config)); + setIndexingScript(schemaName, ScriptExpression.newInstance(config)); } catch (ParseException e) { throw new IllegalArgumentException("Failed to parse script '" + script + "'", e); } } /** Sets the indexing script of this, or null to not use a script */ - public void setIndexingScript(ScriptExpression exp) { + + public void setIndexingScript(String schemaName, ScriptExpression exp) { if (exp == null) { exp = new ScriptExpression(); } @@ -441,13 +442,13 @@ public class SDField extends Field implements TypedKey, ImmutableSDField { } Attribute attribute = attributes.get(fieldName); if (attribute == null) { - addAttribute(new Attribute(fieldName, getDataType())); + addAttribute(new Attribute(schemaName, fieldName, fieldName, getDataType())); } } }.visit(indexingScript); } for (SDField structField : getStructFields()) { - structField.setIndexingScript(exp); + structField.setIndexingScript(schemaName, exp); } } diff --git a/config-model/src/main/java/com/yahoo/schema/fieldoperation/FieldOperation.java b/config-model/src/main/java/com/yahoo/schema/fieldoperation/FieldOperation.java index 22a9eed2914..5a0c2c3c915 100644 --- a/config-model/src/main/java/com/yahoo/schema/fieldoperation/FieldOperation.java +++ b/config-model/src/main/java/com/yahoo/schema/fieldoperation/FieldOperation.java @@ -12,7 +12,7 @@ import com.yahoo.schema.document.SDField; public interface FieldOperation extends Comparable<FieldOperation> { /** Apply this operation on the given field */ - void apply(SDField field); + void apply(String schemaName, SDField field); @Override default int compareTo(FieldOperation other) { diff --git a/config-model/src/main/java/com/yahoo/schema/fieldoperation/IndexingOperation.java b/config-model/src/main/java/com/yahoo/schema/fieldoperation/IndexingOperation.java index f5366c4b07a..11065f040ea 100644 --- a/config-model/src/main/java/com/yahoo/schema/fieldoperation/IndexingOperation.java +++ b/config-model/src/main/java/com/yahoo/schema/fieldoperation/IndexingOperation.java @@ -28,8 +28,8 @@ public class IndexingOperation implements FieldOperation { public ScriptExpression getScript() { return script; } - public void apply(SDField field) { - field.setIndexingScript(script); + public void apply(String schemaName, SDField field) { + field.setIndexingScript(schemaName, script); } /** Creates an indexing operation which will use the simple linguistics implementation suitable for testing */ diff --git a/config-model/src/main/java/com/yahoo/schema/parser/ConvertParsedFields.java b/config-model/src/main/java/com/yahoo/schema/parser/ConvertParsedFields.java index e3ca0090408..053a5ac777b 100644 --- a/config-model/src/main/java/com/yahoo/schema/parser/ConvertParsedFields.java +++ b/config-model/src/main/java/com/yahoo/schema/parser/ConvertParsedFields.java @@ -2,6 +2,7 @@ package com.yahoo.schema.parser; import com.yahoo.document.DataType; +import com.yahoo.schema.document.GeoPos; import com.yahoo.schema.parser.ConvertParsedTypes.TypeResolver; import com.yahoo.schema.Index; import com.yahoo.schema.Schema; @@ -49,10 +50,10 @@ public class ConvertParsedFields { (exactMatchTerminator -> field.getMatching().setExactMatchTerminator(exactMatchTerminator)); } - void convertSorting(SDField field, ParsedSorting parsed, String name) { + void convertSorting(Schema schema, SDField field, ParsedSorting parsed, String name) { Attribute attribute = field.getAttributes().get(name); if (attribute == null) { - attribute = new Attribute(name, field.getDataType()); + attribute = new Attribute(schema.getName(), field.getName(), name, field.getDataType()); field.addAttribute(attribute); } Sorting sorting = attribute.getSorting(); @@ -66,7 +67,7 @@ public class ConvertParsedFields { parsed.getLocale().ifPresent(locale -> sorting.setLocale(locale)); } - void convertAttribute(SDField field, ParsedAttribute parsed) { + void convertAttribute(Schema schema, SDField field, ParsedAttribute parsed) { String name = parsed.name(); String fieldName = field.getName(); Attribute attribute = null; @@ -76,7 +77,7 @@ public class ConvertParsedFields { if (attribute == null) { attribute = field.getAttributes().get(name); if (attribute == null) { - attribute = new Attribute(name, field.getDataType()); + attribute = new Attribute(schema.getName(), field.getName(), name, field.getDataType()); field.addAttribute(attribute); } } @@ -102,7 +103,7 @@ public class ConvertParsedFields { } var sorting = parsed.getSorting(); if (sorting.isPresent()) { - convertSorting(field, sorting.get(), name); + convertSorting(schema, field, sorting.get(), name); } } @@ -143,13 +144,16 @@ public class ConvertParsedFields { convertMatchSettings(field, parsed.matchSettings()); var indexing = parsed.getIndexing(); if (indexing.isPresent()) { - field.setIndexingScript(indexing.get().script()); + field.setIndexingScript(schema.getName(), indexing.get().script()); + } + if (field.doesAttributing() && !GeoPos.isAnyPos(field.getDataType())) { + Attribute.validateDataType(schema.getName(), field.getName(), field.getDataType()); } parsed.getWeight().ifPresent(value -> field.setWeight(value)); parsed.getStemming().ifPresent(value -> field.setStemming(value)); parsed.getNormalizing().ifPresent(value -> convertNormalizing(field, value)); for (var attribute : parsed.getAttributes()) { - convertAttribute(field, attribute); + convertAttribute(schema, field, attribute); } for (var summaryField : parsed.getSummaryFields()) { var dataType = field.getDataType(); @@ -190,7 +194,7 @@ public class ConvertParsedFields { convertCommonFieldSettings(schema, structField, parsed); } - private void convertExtraFieldSettings(SDField field, ParsedField parsed) { + private void convertExtraFieldSettings(Schema schema, SDField field, ParsedField parsed) { String name = parsed.name(); for (var dictOp : parsed.getDictionaryOptions()) { var dictionary = field.getOrSetDictionary(); @@ -208,7 +212,7 @@ public class ConvertParsedFields { field.getAliasToName().put(alias, parsed.lookupAliasedFrom(alias)); } parsed.getRankTypes().forEach((indexName, rankType) -> convertRankType(field, indexName, rankType)); - parsed.getSorting().ifPresent(sortInfo -> convertSorting(field, sortInfo, name)); + parsed.getSorting().ifPresent(sortInfo -> convertSorting(schema, field, sortInfo, name)); if (parsed.hasBolding()) { // TODO must it be so ugly: SummaryField summaryField = field.getSummaryField(name, true); @@ -288,7 +292,7 @@ public class ConvertParsedFields { DataType dataType = context.resolveType(parsed.getType()); var field = new SDField(document, name, dataType); convertCommonFieldSettings(schema, field, parsed); - convertExtraFieldSettings(field, parsed); + convertExtraFieldSettings(schema, field, parsed); document.addField(field); return field; } @@ -298,7 +302,7 @@ public class ConvertParsedFields { DataType dataType = context.resolveType(parsed.getType()); var field = new SDField(schema.getDocument(), name, dataType); convertCommonFieldSettings(schema, field, parsed); - convertExtraFieldSettings(field, parsed); + convertExtraFieldSettings(schema, field, parsed); schema.addExtraField(field); } diff --git a/config-model/src/main/java/com/yahoo/schema/processing/CreatePositionZCurve.java b/config-model/src/main/java/com/yahoo/schema/processing/CreatePositionZCurve.java index 7bd66ad8f0b..deb57e157f3 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/CreatePositionZCurve.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/CreatePositionZCurve.java @@ -86,14 +86,14 @@ public class CreatePositionZCurve extends Processor { SummaryTransform.DISTANCE, summaryTo, validate); } // clear indexing script - field.setIndexingScript(null); + field.setIndexingScript(schema.getName(), null); SDField posX = field.getStructField(PositionDataType.FIELD_X); if (posX != null) { - posX.setIndexingScript(null); + posX.setIndexingScript(schema.getName(), null); } SDField posY = field.getStructField(PositionDataType.FIELD_Y); if (posY != null) { - posY.setIndexingScript(null); + posY.setIndexingScript(schema.getName(), null); } if (doesSummary) ensureCompatibleSummary(field, zName, field.getName(), @@ -118,7 +118,7 @@ public class CreatePositionZCurve extends Processor { ScriptExpression script = inputField.getIndexingScript(); script = (ScriptExpression)new RemoveSummary(inputField.getName()).convert(script); script = (ScriptExpression)new PerformZCurve(field, fieldName).convert(script); - field.setIndexingScript(script); + field.setIndexingScript(schema.getName(), script); return field; } diff --git a/config-model/src/main/java/com/yahoo/schema/processing/ExactMatch.java b/config-model/src/main/java/com/yahoo/schema/processing/ExactMatch.java index a12183262c4..056c37a9830 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/ExactMatch.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/ExactMatch.java @@ -75,7 +75,7 @@ public class ExactMatch extends Processor { } ScriptExpression script = field.getIndexingScript(); if (new ExpressionSearcher<>(IndexExpression.class).containedIn(script)) { - field.setIndexingScript((ScriptExpression)new MyProvider(schema).convert(field.getIndexingScript())); + field.setIndexingScript(schema.getName(), (ScriptExpression)new MyProvider(schema).convert(field.getIndexingScript())); } } diff --git a/config-model/src/main/java/com/yahoo/schema/processing/IndexingInputs.java b/config-model/src/main/java/com/yahoo/schema/processing/IndexingInputs.java index 53ebd136e08..a5ba67d6976 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/IndexingInputs.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/IndexingInputs.java @@ -36,7 +36,7 @@ public class IndexingInputs extends Processor { if (validate) new VerifyInputExpression(schema, field).visit(script); - field.setIndexingScript(script); + field.setIndexingScript(schema.getName(), script); } } diff --git a/config-model/src/main/java/com/yahoo/schema/processing/IndexingOutputs.java b/config-model/src/main/java/com/yahoo/schema/processing/IndexingOutputs.java index 071c2878ae8..b5d1cf71809 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/IndexingOutputs.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/IndexingOutputs.java @@ -37,7 +37,7 @@ public class IndexingOutputs extends Processor { Set<String> summaryFields = new TreeSet<>(); findSummaryTo(schema, field, summaryFields, summaryFields); MyConverter converter = new MyConverter(schema, field, summaryFields, validate); - field.setIndexingScript((ScriptExpression)converter.convert(script)); + field.setIndexingScript(schema.getName(), (ScriptExpression)converter.convert(script)); } } @@ -106,7 +106,7 @@ public class IndexingOutputs extends Processor { MyConverter(Schema schema, Field field, Set<String> summaryFields, boolean validate) { this.schema = schema; this.field = field; - this.summaryFields = summaryFields.isEmpty() ? Collections.singleton(field.getName()) : summaryFields; + this.summaryFields = summaryFields.isEmpty() ? Set.of(field.getName()) : summaryFields; this.validate = validate; } diff --git a/config-model/src/main/java/com/yahoo/schema/processing/IntegerIndex2Attribute.java b/config-model/src/main/java/com/yahoo/schema/processing/IntegerIndex2Attribute.java index 0d296783cfb..37815ef5396 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/IntegerIndex2Attribute.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/IntegerIndex2Attribute.java @@ -38,7 +38,7 @@ public class IntegerIndex2Attribute extends Processor { ScriptExpression script = field.getIndexingScript(); Set<String> attributeNames = new HashSet<>(); new MyVisitor(attributeNames).visit(script); - field.setIndexingScript((ScriptExpression)new MyConverter(attributeNames).convert(script)); + field.setIndexingScript(schema.getName(), (ScriptExpression)new MyConverter(attributeNames).convert(script)); warn(schema, field, "Changed to attribute because numerical indexes (field has type " + field.getDataType().getName() + ") is not currently supported." + " Index-only settings may fail. Ignore this warning for streaming search."); diff --git a/config-model/src/main/java/com/yahoo/schema/processing/NGramMatch.java b/config-model/src/main/java/com/yahoo/schema/processing/NGramMatch.java index 2ec5c03e04c..c06e0565109 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/NGramMatch.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/NGramMatch.java @@ -46,7 +46,7 @@ public class NGramMatch extends Processor { field.getNormalizing().inferCodepoint(); field.setStemming(Stemming.NONE); // not compatible with stemming and normalizing field.addQueryCommand("ngram " + n); - field.setIndexingScript((ScriptExpression)new MyProvider(schema, n).convert(field.getIndexingScript())); + field.setIndexingScript(schema.getName(), (ScriptExpression)new MyProvider(schema, n).convert(field.getIndexingScript())); } private static class MyProvider extends TypedTransformProvider { diff --git a/config-model/src/main/java/com/yahoo/schema/processing/OptimizeIlscript.java b/config-model/src/main/java/com/yahoo/schema/processing/OptimizeIlscript.java index b268a7a9c03..fbb49497837 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/OptimizeIlscript.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/OptimizeIlscript.java @@ -27,7 +27,7 @@ public class OptimizeIlscript extends Processor { ScriptExpression script = field.getIndexingScript(); if (script == null) continue; - field.setIndexingScript((ScriptExpression)new ExpressionOptimizer().convert(script)); + field.setIndexingScript(schema.getName(), (ScriptExpression)new ExpressionOptimizer().convert(script)); if ( ! field.getIndexingScript().toString().equals(script.toString())) { info(schema, field, "Rewrote ilscript from:\n" + script.toString() + "\nto\n" + field.getIndexingScript().toString()); diff --git a/config-model/src/main/java/com/yahoo/schema/processing/PredicateProcessor.java b/config-model/src/main/java/com/yahoo/schema/processing/PredicateProcessor.java index 2a654991835..c451df6370d 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/PredicateProcessor.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/PredicateProcessor.java @@ -107,7 +107,7 @@ public class PredicateProcessor extends Processor { script = new StatementExpression(makeSetPredicateVariablesScript(booleanIndexDefiniton), script); ExpressionConverter converter = new PredicateOutputTransformer(schema); - field.setIndexingScript(new ScriptExpression((StatementExpression)converter.convert(script))); + field.setIndexingScript(schema.getName(), new ScriptExpression((StatementExpression)converter.convert(script))); } private Expression makeSetPredicateVariablesScript(BooleanIndexDefinition options) { diff --git a/config-model/src/main/java/com/yahoo/schema/processing/Processing.java b/config-model/src/main/java/com/yahoo/schema/processing/Processing.java index c23d87e9eba..52078326aec 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/Processing.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/Processing.java @@ -9,8 +9,8 @@ import com.yahoo.vespa.model.container.search.QueryProfiles; import com.yahoo.config.model.api.ModelContext; import com.yahoo.config.model.deploy.TestProperties; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import java.util.Set; /** @@ -28,7 +28,7 @@ public class Processing { public Processing(ModelContext.Properties properties) { this.properties = properties; } private Collection<ProcessorFactory> processors() { - return Arrays.asList( + return List.<ProcessorFactory>of( SearchMustHaveDocument::new, UrlFieldValidator::new, BuiltInFieldSets::new, @@ -99,7 +99,7 @@ public class Processing { /** Processors of rank profiles only (those who tolerate and do something useful when the search field is null) */ private Collection<ProcessorFactory> rankProfileProcessors() { - return Arrays.asList( + return List.of( RankProfileTypeSettingsProcessor::new, ReservedFunctionNames::new, RankingExpressionTypeResolver::new); diff --git a/config-model/src/main/java/com/yahoo/schema/processing/Processor.java b/config-model/src/main/java/com/yahoo/schema/processing/Processor.java index beaff13c613..dd36bbb3b61 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/Processor.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/Processor.java @@ -87,7 +87,7 @@ public abstract class Processor { implementationField.setRankType(RankType.EMPTY); implementationField.setStemming(Stemming.NONE); implementationField.getNormalizing().inferCodepoint(); - implementationField.parseIndexingScript(indexing); + implementationField.parseIndexingScript(schema.getName(), indexing); String indexName = field.getName(); String implementationIndexName = indexName + "_" + suffix; Index implementationIndex = new Index(implementationIndexName); diff --git a/config-model/src/main/java/com/yahoo/schema/processing/TextMatch.java b/config-model/src/main/java/com/yahoo/schema/processing/TextMatch.java index e6fed35b821..e29f683761f 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/TextMatch.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/TextMatch.java @@ -48,7 +48,7 @@ public class TextMatch extends Processor { if ( ! visitor.requiresTokenize) continue; ExpressionConverter converter = new MyStringTokenizer(schema, findAnnotatorConfig(schema, field)); - field.setIndexingScript((ScriptExpression)converter.convert(script)); + field.setIndexingScript(schema.getName(), (ScriptExpression)converter.convert(script)); } } diff --git a/config-model/src/main/java/com/yahoo/schema/processing/UriHack.java b/config-model/src/main/java/com/yahoo/schema/processing/UriHack.java index e4e2ac9f5be..9a4c4038953 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/UriHack.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/UriHack.java @@ -12,7 +12,6 @@ import com.yahoo.schema.document.SDField; import com.yahoo.schema.document.Stemming; import com.yahoo.vespa.model.container.search.QueryProfiles; -import java.util.Arrays; import java.util.List; /** @@ -21,7 +20,7 @@ import java.util.List; public class UriHack extends Processor { private static final List<String> URL_SUFFIX = - Arrays.asList("scheme", "host", "port", "path", "query", "fragment", "hostname"); + List.of("scheme", "host", "port", "path", "query", "fragment", "hostname"); UriHack(Schema schema, DeployLogger deployLogger, @@ -52,8 +51,7 @@ public class UriHack extends Processor { if (uriField.getDataType() instanceof ArrayDataType) { generatedType = new ArrayDataType(DataType.STRING); } - else if (uriField.getDataType() instanceof WeightedSetDataType) { - WeightedSetDataType wdt = (WeightedSetDataType) uriField.getDataType(); + else if (uriField.getDataType() instanceof WeightedSetDataType wdt) { generatedType = new WeightedSetDataType(DataType.STRING, wdt.createIfNonExistent(), wdt.removeIfZero()); } diff --git a/config-model/src/main/java/com/yahoo/schema/processing/multifieldresolver/IndexCommandResolver.java b/config-model/src/main/java/com/yahoo/schema/processing/multifieldresolver/IndexCommandResolver.java index 111f5384c41..2854824e5b7 100644 --- a/config-model/src/main/java/com/yahoo/schema/processing/multifieldresolver/IndexCommandResolver.java +++ b/config-model/src/main/java/com/yahoo/schema/processing/multifieldresolver/IndexCommandResolver.java @@ -5,8 +5,6 @@ import com.yahoo.config.application.api.DeployLogger; import com.yahoo.schema.document.SDField; import com.yahoo.schema.Schema; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.logging.Level; @@ -16,17 +14,10 @@ import java.util.logging.Level; public class IndexCommandResolver extends MultiFieldResolver { /** Commands which don't have to be harmonized between fields */ - private static List<String> ignoredCommands = new ArrayList<>(); + private static final List<String> ignoredCommands = List.of( "complete-boost", "literal-boost", "highlight"); /** Commands which must be harmonized between fields */ - private static List<String> harmonizedCommands = new ArrayList<>(); - - static { - String[] ignore = { "complete-boost", "literal-boost", "highlight" }; - ignoredCommands.addAll(Arrays.asList(ignore)); - String[] harmonize = { "stemming", "normalizing" }; - harmonizedCommands.addAll(Arrays.asList(harmonize)); - } + private static final List<String> harmonizedCommands = List.of("stemming", "normalizing"); public IndexCommandResolver(String indexName, List<SDField> fields, Schema schema, DeployLogger logger) { super(indexName, fields, schema, logger); @@ -53,8 +44,8 @@ public class IndexCommandResolver extends MultiFieldResolver { ", adding to field " + field.getName()); field.addQueryCommand(command); } else { - deployLogger.logApplicationPackage(Level.WARNING, "All fields going to the same index should have the same query-commands. Field \'" + field.getName() + - "\' doesn't contain command \'" + command+"\'"); + deployLogger.logApplicationPackage(Level.WARNING, "All fields going to the same index should have the same query-commands. Field '" + field.getName() + + "' doesn't contain command '" + command+"'"); } } } diff --git a/config-model/src/main/java/com/yahoo/vespa/model/HostPorts.java b/config-model/src/main/java/com/yahoo/vespa/model/HostPorts.java index f1d3b38e8ff..348a5d575eb 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/HostPorts.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/HostPorts.java @@ -4,7 +4,6 @@ package com.yahoo.vespa.model; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.config.provision.NetworkPorts; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -28,7 +27,7 @@ public class HostPorts { private int allocatedPorts = 0; - private PortFinder portFinder = new PortFinder(Collections.emptyList()); + private PortFinder portFinder = new PortFinder(List.of()); private boolean flushed = false; private Optional<NetworkPorts> networkPortsList = Optional.empty(); diff --git a/config-model/src/main/java/com/yahoo/vespa/model/VespaModelFactory.java b/config-model/src/main/java/com/yahoo/vespa/model/VespaModelFactory.java index 1c4b0d31ab2..c876976917b 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/VespaModelFactory.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/VespaModelFactory.java @@ -36,7 +36,6 @@ import java.io.IOException; import java.time.Clock; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.logging.Level; @@ -96,7 +95,7 @@ public class VespaModelFactory implements ModelFactory { } else { this.configModelRegistry = configModelRegistry; } - this.modelImporters = Collections.emptyList(); + this.modelImporters = List.of(); this.additionalValidators = List.of(); this.zone = zone; this.clock = clock; diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java index 78ef6826d26..c19d186df42 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java @@ -10,7 +10,6 @@ import com.yahoo.vespa.model.container.ContainerCluster; import com.yahoo.vespa.model.container.PlatformBundles; import java.nio.file.Path; -import java.util.Collections; import java.util.Optional; import java.util.Set; @@ -22,7 +21,7 @@ import java.util.Set; */ public class ClusterControllerContainerCluster extends ContainerCluster<ClusterControllerContainer> { - private static final Set<Path> UNNECESSARY_BUNDLES = Collections.unmodifiableSet(PlatformBundles.VESPA_SECURITY_BUNDLES); + private static final Set<Path> UNNECESSARY_BUNDLES = Set.copyOf(PlatformBundles.VESPA_SECURITY_BUNDLES); private final ReindexingContext reindexingContext; diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java index 0d85696d503..913ae0e1a00 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java @@ -36,7 +36,6 @@ import com.yahoo.vespa.model.container.component.Handler; import com.yahoo.vespa.model.container.component.SystemBindingPattern; import java.nio.file.Path; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; @@ -198,7 +197,7 @@ public class MetricsProxyContainerCluster extends ContainerCluster<MetricsProxyC private Map<String, MetricsConsumer> getUserMetricsConsumers() { return getAdmin() .map(admin -> admin.getUserMetrics().getConsumers()) - .orElse(Collections.emptyMap()); + .orElse(Map.of()); } private Optional<String> getSystemName() { diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/MetricsConsumer.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/MetricsConsumer.java index aa476b1ae39..0a933e7d5ed 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/MetricsConsumer.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/monitoring/MetricsConsumer.java @@ -7,7 +7,6 @@ import ai.vespa.metrics.set.Vespa9VespaMetricSet; import ai.vespa.metricsproxy.core.VespaMetrics; import ai.vespa.metricsproxy.http.ValuesFetcher; -import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; @@ -71,7 +70,7 @@ public class MetricsConsumer { } public static MetricsConsumer consumer(String id, MetricSet ... metricSets) { - return new MetricsConsumer(id, new MetricSet(id + "-consumer-metrics", List.of(), Arrays.asList(metricSets))); + return new MetricsConsumer(id, new MetricSet(id + "-consumer-metrics", List.of(), List.of(metricSets))); } } diff --git a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/BundleValidator.java b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/BundleValidator.java index 0a23e25e432..4b4cb1530d4 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/BundleValidator.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/BundleValidator.java @@ -5,7 +5,6 @@ import com.yahoo.config.model.deploy.DeployState; import org.w3c.dom.Document; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -35,7 +34,7 @@ public class BundleValidator extends AbstractBundleValidator { for (Map.Entry<Object,Object> entry : attributes.entrySet()) { mfAttributes.add(entry.getKey().toString()); } - List<String> requiredOSGIHeaders = Arrays.asList( + List<String> requiredOSGIHeaders = List.of( "Bundle-ManifestVersion", "Bundle-Name", "Bundle-SymbolicName", "Bundle-Version"); for (String header : requiredOSGIHeaders) { if (!mfAttributes.contains(header)) { diff --git a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/PublicApiBundleValidator.java b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/PublicApiBundleValidator.java index e0a43f0988a..ddffe20f725 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/application/validation/PublicApiBundleValidator.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/application/validation/PublicApiBundleValidator.java @@ -3,7 +3,7 @@ package com.yahoo.vespa.model.application.validation; import org.w3c.dom.Document; -import java.util.Arrays; +import java.util.List; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.logging.Level; @@ -18,7 +18,7 @@ public class PublicApiBundleValidator extends AbstractBundleValidator { String nonPublicApiAttribute = mf.getMainAttributes().getValue("X-JDisc-Non-PublicApi-Import-Package"); if (nonPublicApiAttribute == null) return; - var nonPublicApisUsed = Arrays.asList(nonPublicApiAttribute.split(",")); + var nonPublicApisUsed = List.of(nonPublicApiAttribute.split(",")); if (! nonPublicApisUsed.isEmpty()) { log(context.deployState(), Level.WARNING, "Jar file '%s' uses non-public Vespa APIs: %s", filename(jar), nonPublicApisUsed); } diff --git a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/ComponentsBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/ComponentsBuilder.java index 046980087ed..bde12bb1d5a 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/ComponentsBuilder.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/ComponentsBuilder.java @@ -151,7 +151,7 @@ public class ComponentsBuilder<T extends ChainedComponent<?>> { private Map<String, ComponentType<?>> unmodifiable(Map<String, ComponentType<?>> outerComponentTypeByComponentName) { return (outerComponentTypeByComponentName != null)? Collections.unmodifiableMap(outerComponentTypeByComponentName): - Collections.emptyMap(); + Map.of(); } public Collection<T> getComponentDefinitions() { diff --git a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomGenericTargetBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomGenericTargetBuilder.java index 565cdf3a5f5..b8de223c0cb 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomGenericTargetBuilder.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomGenericTargetBuilder.java @@ -9,7 +9,7 @@ import com.yahoo.vespa.model.container.search.searchchain.GenericTarget; import com.yahoo.vespa.model.container.search.searchchain.Searcher; import org.w3c.dom.Element; -import java.util.Arrays; +import java.util.List; import java.util.Map; /** @@ -20,7 +20,7 @@ import java.util.Map; abstract public class DomGenericTargetBuilder<T extends GenericTarget> extends DomChainBuilderBase<Searcher<?>, T> { DomGenericTargetBuilder(Map<String, ComponentsBuilder.ComponentType<?>> outerSearcherTypeByComponentName) { - super(Arrays.asList(ComponentsBuilder.ComponentType.searcher, ComponentsBuilder.ComponentType.federation), + super(List.of(ComponentsBuilder.ComponentType.searcher, ComponentsBuilder.ComponentType.federation), outerSearcherTypeByComponentName); } diff --git a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearchChainBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearchChainBuilder.java index 2eb1127d75b..4ada9e99e5e 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearchChainBuilder.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearchChainBuilder.java @@ -11,7 +11,7 @@ import com.yahoo.vespa.model.container.search.searchchain.SearchChain; import com.yahoo.vespa.model.container.search.searchchain.Searcher; import org.w3c.dom.Element; -import java.util.Arrays; +import java.util.List; import java.util.Map; /** @@ -21,7 +21,7 @@ import java.util.Map; public class DomSearchChainBuilder extends DomChainBuilderBase<Searcher<?>, SearchChain> { public DomSearchChainBuilder(Map<String, ComponentsBuilder.ComponentType<?>> outerSearcherTypeByComponentName) { - super(Arrays.asList(ComponentsBuilder.ComponentType.searcher, ComponentsBuilder.ComponentType.federation), + super(List.of(ComponentsBuilder.ComponentType.searcher, ComponentsBuilder.ComponentType.federation), outerSearcherTypeByComponentName); } diff --git a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearchChainsBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearchChainsBuilder.java index e05d762d7bc..b48df948358 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearchChainsBuilder.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearchChainsBuilder.java @@ -11,7 +11,6 @@ import com.yahoo.vespa.model.container.search.searchchain.SearchChains; import com.yahoo.vespa.model.container.search.searchchain.Searcher; import org.w3c.dom.Element; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -23,7 +22,7 @@ import java.util.Map; public class DomSearchChainsBuilder extends DomChainsBuilder<Searcher<?>, SearchChain, SearchChains> { public DomSearchChainsBuilder() { - super(Arrays.asList(ComponentType.searcher, ComponentType.federation)); + super(List.of(ComponentType.searcher, ComponentType.federation)); } @Override diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java b/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java index 1400a630e56..e801884a73a 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java @@ -71,7 +71,7 @@ public class PlatformBundles { private static Set<Path> toBundlePaths(String... bundleNames) { return Stream.of(bundleNames) .map(PlatformBundles::absoluteBundlePath) - .collect(Collectors.toSet()); + .collect(Collectors.toUnmodifiableSet()); } public static Path absoluteBundlePath(String fileName) { diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/component/DiscBindingsConfigGenerator.java b/config-model/src/main/java/com/yahoo/vespa/model/container/component/DiscBindingsConfigGenerator.java index ed626f98aa0..dafac2c1af9 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/container/component/DiscBindingsConfigGenerator.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/container/component/DiscBindingsConfigGenerator.java @@ -2,7 +2,6 @@ package com.yahoo.vespa.model.container.component; import java.util.Collection; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; @@ -24,9 +23,9 @@ public class DiscBindingsConfigGenerator { public static <T extends Handler> Map<String, Handlers.Builder> generate(T handler) { if (handler.getServerBindings().isEmpty() && handler.getClientBindings().isEmpty()) - return Collections.emptyMap(); + return Map.of(); - return Collections.singletonMap(handler.model.getComponentId().stringValue(), + return Map.of(handler.model.getComponentId().stringValue(), new Handlers.Builder() .serverBindings(toStrings(handler.getServerBindings())) .clientBindings(toStrings(handler.getClientBindings()))); diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/component/Handler.java b/config-model/src/main/java/com/yahoo/vespa/model/container/component/Handler.java index 099255975b6..0d3d8462376 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/container/component/Handler.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/container/component/Handler.java @@ -8,7 +8,6 @@ import com.yahoo.vespa.model.container.ContainerThreadpool; import org.w3c.dom.Element; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; @@ -51,7 +50,7 @@ public class Handler extends Component<Component<?, ?>, ComponentModel> { } public void addServerBindings(BindingPattern... bindings) { - serverBindings.addAll(Arrays.asList(bindings)); + serverBindings.addAll(List.of(bindings)); } public void addServerBindings(Collection<BindingPattern> bps) { serverBindings.addAll(bps); } @@ -61,7 +60,7 @@ public class Handler extends Component<Component<?, ?>, ComponentModel> { } public void addClientBindings(BindingPattern... bindings) { - clientBindings.addAll(Arrays.asList(bindings)); + clientBindings.addAll(List.of(bindings)); } public final Collection<BindingPattern> getServerBindings() { diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/component/Model.java b/config-model/src/main/java/com/yahoo/vespa/model/container/component/Model.java index 7d6285d00c1..3a8e52c92a8 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/container/component/Model.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/container/component/Model.java @@ -13,6 +13,7 @@ import com.yahoo.vespa.model.container.xml.ModelIdResolver; import org.w3c.dom.Element; import java.net.URI; +import java.net.URISyntaxException; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -51,11 +52,22 @@ class Model { static Model fromXml(DeployState ds, Element model, Set<String> requiredTags) { var modelId = XmlHelper.getOptionalAttribute(model, "model-id").orElse(null); - var url = XmlHelper.getOptionalAttribute(model, "url").map(URI::create).orElse(null); + var url = XmlHelper.getOptionalAttribute(model, "url").map(Model::parseUrl).orElse(null); var path = XmlHelper.getOptionalAttribute(model, "path").map(Path::fromString).orElse(null); return new Model(ds, model.getTagName(), modelId, url, path, requiredTags); } + private static URI parseUrl(String url) { + try { + var uri = new URI(url); + if ( ! uri.isAbsolute()) + throw new IllegalArgumentException("Invalid url '" + url + "': url has no 'scheme' component"); + return uri; + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid url '" + url + "':" + e.getMessage()); + } + } + /** Return tokenizer model from XML if specified, alternatively use model id for ONNX model with suffix '-vocab' appended */ static Model fromXmlOrImplicitlyFromOnnxModel( DeployState ds, Element parent, Model onnxModel, String paramName, Set<String> requiredTags) { diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/http/AccessControl.java b/config-model/src/main/java/com/yahoo/vespa/model/container/http/AccessControl.java index 8c1b868465a..19c45bba2ef 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/container/http/AccessControl.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/container/http/AccessControl.java @@ -48,7 +48,7 @@ public class AccessControl { private final String domain; private ClientAuthentication clientAuthentication = ClientAuthentication.need; private final Set<BindingPattern> excludeBindings = new LinkedHashSet<>(); - private Collection<Handler> handlers = Collections.emptyList(); + private Collection<Handler> handlers = List.of(); public Builder(String domain) { this.domain = domain; } diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/http/xml/FilterChainBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/container/http/xml/FilterChainBuilder.java index bc234546625..82a8a01871e 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/container/http/xml/FilterChainBuilder.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/container/http/xml/FilterChainBuilder.java @@ -11,7 +11,7 @@ import com.yahoo.vespa.model.container.http.HttpFilterChain; import org.w3c.dom.Element; import java.util.Collection; -import java.util.Collections; +import java.util.List; import java.util.Map; import static com.yahoo.vespa.model.builder.xml.dom.chains.ComponentsBuilder.ComponentType; @@ -21,7 +21,7 @@ import static com.yahoo.vespa.model.builder.xml.dom.chains.ComponentsBuilder.Com */ public class FilterChainBuilder extends DomChainBuilderBase<Filter, HttpFilterChain> { - private static final Collection<ComponentType<Filter>> allowedComponentTypes = Collections.singleton(ComponentType.filter); + private static final Collection<ComponentType<Filter>> allowedComponentTypes = List.of(ComponentType.filter); public FilterChainBuilder(Map<String, ComponentType<?>> outerFilterTypeByComponentName) { super(allowedComponentTypes, outerFilterTypeByComponentName); diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/http/xml/FilterChainsBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/container/http/xml/FilterChainsBuilder.java index 878859a01bf..f1cdbfb3b04 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/container/http/xml/FilterChainsBuilder.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/container/http/xml/FilterChainsBuilder.java @@ -15,7 +15,6 @@ import com.yahoo.vespa.model.container.http.HttpFilterChain; import org.w3c.dom.Element; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.Map; @@ -24,7 +23,7 @@ import java.util.Map; */ public class FilterChainsBuilder extends DomChainsBuilder<Filter, HttpFilterChain, FilterChains> { private static final Collection<ComponentType<Filter>> allowedComponentTypes = - Collections.singleton(ComponentType.filter); + List.of(ComponentType.filter); private static final Map<String, Class<? extends DomChainBuilderBase<? extends Filter, ? extends HttpFilterChain>>> chainType2BuilderClass = Map.of( diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/Source.java b/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/Source.java index 29e587c6453..f589884cccd 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/Source.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/container/search/searchchain/Source.java @@ -4,9 +4,8 @@ package com.yahoo.vespa.model.container.search.searchchain; import com.yahoo.component.ComponentId; import com.yahoo.component.chain.model.ChainSpecification; import com.yahoo.search.searchchain.model.federation.FederationOptions; -import com.yahoo.config.model.producer.TreeConfigProducer; -import java.util.Arrays; +import java.util.List; /** @@ -51,7 +50,7 @@ public class Source extends GenericTarget { @Override public ChainSpecification getChainSpecification() { return super.getChainSpecification().addInherits( - Arrays.asList(getParentProvider().getComponentId().toSpecification())); + List.of(getParentProvider().getComponentId().toSpecification())); } public ComponentId getGlobalComponentId() { diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilder.java index 8a15e61495b..7e14eafc2ee 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilder.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilder.java @@ -7,7 +7,6 @@ import com.yahoo.component.ComponentSpecification; import com.yahoo.vespa.model.container.PlatformBundles; import org.w3c.dom.Element; -import java.util.Arrays; import java.util.List; import static com.yahoo.vespa.model.container.component.chain.ProcessingHandler.PROCESSING_HANDLER_CLASS; @@ -39,9 +38,7 @@ public class BundleInstantiationSpecificationBuilder { private static void validate(BundleInstantiationSpecification instSpec) { - List<String> forbiddenClasses = Arrays.asList( - SearchHandler.HANDLER_CLASSNAME, - PROCESSING_HANDLER_CLASS); + List<String> forbiddenClasses = List.of(SearchHandler.HANDLER_CLASSNAME, PROCESSING_HANDLER_CLASS); for (String forbiddenClass: forbiddenClasses) { if (forbiddenClass.equals(instSpec.getClassName())) { diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilder.java index 456ce8fdbc2..360a02256a9 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilder.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilder.java @@ -114,7 +114,6 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -893,7 +892,7 @@ public class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> { private void addStandaloneNode(ApplicationContainerCluster cluster, DeployState deployState) { ApplicationContainer container = new ApplicationContainer(cluster, "standalone", cluster.getContainers().size(), deployState); - cluster.addContainers(Collections.singleton(container)); + cluster.addContainers(List.of(container)); } private static String buildJvmGCOptions(ConfigModelContext context, String jvmGCOptions) { diff --git a/config-model/src/main/java/com/yahoo/vespa/model/content/Content.java b/config-model/src/main/java/com/yahoo/vespa/model/content/Content.java index 9d15eddbef3..6d482a6d4a6 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/content/Content.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/content/Content.java @@ -35,7 +35,6 @@ import org.w3c.dom.Element; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; @@ -195,7 +194,7 @@ public class Content extends ConfigModel { public static class Builder extends ConfigModelBuilder<Content> { - public static final List<ConfigModelId> configModelIds = Collections.singletonList(ConfigModelId.fromName("content")); + public static final List<ConfigModelId> configModelIds = List.of(ConfigModelId.fromName("content")); public Builder() { super(Content.class); diff --git a/config-model/src/main/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidator.java b/config-model/src/main/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidator.java index 53547a1a15b..6dd7278fde8 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidator.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidator.java @@ -3,9 +3,6 @@ package com.yahoo.vespa.model.content; import com.yahoo.documentmodel.NewDocumentType; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -13,9 +10,8 @@ import java.util.stream.Collectors; public class ReservedDocumentTypeNameValidator { - public static final List<String> ORDERED_RESERVED_NAMES = Collections.unmodifiableList( - Arrays.asList("and", "false", "id", "not", "null", "or", "true")); - public static final Set<String> RESERVED_NAMES = Collections.unmodifiableSet(new HashSet<>(ORDERED_RESERVED_NAMES)); + public static final List<String> ORDERED_RESERVED_NAMES = List.of("and", "false", "id", "not", "null", "or", "true"); + public static final Set<String> RESERVED_NAMES = Set.copyOf(ORDERED_RESERVED_NAMES); public void validate(Map<String, NewDocumentType> documentDefinitions) { List<String> conflictingNames = documentDefinitions.keySet().stream() diff --git a/config-model/src/main/java/com/yahoo/vespa/model/content/StorageGroup.java b/config-model/src/main/java/com/yahoo/vespa/model/content/StorageGroup.java index a6f53777c51..a1b9ed67aa7 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/content/StorageGroup.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/content/StorageGroup.java @@ -19,7 +19,6 @@ import com.yahoo.vespa.model.content.engines.PersistenceEngine; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -349,7 +348,7 @@ public class StorageGroup { owner.getStorageCluster().getClusterName(), owner.getRoot().hostSystem(), context) : - Collections.emptyMap(); + Map.of(); Map<Optional<ClusterSpec.Group>, Map<HostResource, ClusterMembership>> hostGroups = collectAllocatedSubgroups(hostMapping); if (hostGroups.size() > 1) { @@ -475,7 +474,7 @@ public class StorageGroup { } private List<XmlNodeBuilder> collectExplicitNodes(Optional<ModelElement> groupOrNodesElement) { - if (groupOrNodesElement.isEmpty()) return Collections.emptyList(); + if (groupOrNodesElement.isEmpty()) return List.of(); List<XmlNodeBuilder> nodes = new ArrayList<>(); for (ModelElement n : groupOrNodesElement.get().subElements("node")) nodes.add(new XmlNodeBuilder(clusterElement, n)); diff --git a/config-model/src/main/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilder.java b/config-model/src/main/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilder.java index c9b6537434b..07dafda164d 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilder.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilder.java @@ -4,7 +4,6 @@ package com.yahoo.vespa.model.content.cluster; import com.yahoo.documentmodel.NewDocumentType; import com.yahoo.vespa.model.builder.xml.dom.ModelElement; -import java.util.Collections; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; @@ -20,19 +19,19 @@ public class GlobalDistributionBuilder { private final Map<String, NewDocumentType> documentDefinitions; public GlobalDistributionBuilder(Map<String, NewDocumentType> documentDefinitions) { - this.documentDefinitions = Collections.unmodifiableMap(documentDefinitions); + this.documentDefinitions = Map.copyOf(documentDefinitions); } public Set<NewDocumentType> build(ModelElement documentsElement) { if (documentsElement == null || documentsElement.subElements("document").isEmpty()) - return Collections.emptySet(); + return Set.of(); return documentsElement.subElements("document") .stream() .filter(GlobalDistributionBuilder::isGloballyDistributed) .map(GlobalDistributionBuilder::getDocumentName) .map(this::getDocumentType) - .collect(Collectors.toCollection(() -> new LinkedHashSet<>())); + .collect(Collectors.toCollection(LinkedHashSet::new)); } private static boolean isGloballyDistributed(ModelElement e) { diff --git a/config-model/src/main/java/com/yahoo/vespa/model/ml/ConvertedModel.java b/config-model/src/main/java/com/yahoo/vespa/model/ml/ConvertedModel.java index 621377e0606..78ed10a583e 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/ml/ConvertedModel.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/ml/ConvertedModel.java @@ -32,7 +32,6 @@ import java.io.StringReader; import java.io.UncheckedIOException; import java.nio.file.Files; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -177,7 +176,7 @@ public class ConvertedModel { if (arguments.output().isEmpty()) { List<Map.Entry<String, ExpressionFunction>> entriesWithTheRightPrefix = expressions.entrySet().stream().filter(entry -> entry.getKey().startsWith(arguments.signature().get() + ".")).toList(); - if (entriesWithTheRightPrefix.size() < 1) + if (entriesWithTheRightPrefix.isEmpty()) throw new IllegalArgumentException("No expressions named '" + arguments.signature().get() + missingExpressionMessageSuffix()); if (entriesWithTheRightPrefix.size() > 1) @@ -191,7 +190,7 @@ public class ConvertedModel { private String missingExpressionMessageSuffix() { return "' in model '" + modelDescription + "'. " + - "Available expressions: " + expressions.keySet().stream().collect(Collectors.joining(", ")); + "Available expressions: " + String.join(", ", expressions.keySet()); } // ----------------------- Static model conversion/storage below here @@ -425,8 +424,7 @@ public class ConvertedModel { } private static void addFunctionNamesIn(ExpressionNode node, Set<String> names, ImportedMlModel model) { - if (node instanceof ReferenceNode) { - ReferenceNode referenceNode = (ReferenceNode)node; + if (node instanceof ReferenceNode referenceNode) { if (referenceNode.getOutput() == null) { // function references cannot specify outputs if (names.add(referenceNode.getName())) { if (model.functions().containsKey(referenceNode.getName())) { @@ -485,7 +483,7 @@ public class ConvertedModel { List<Pair<String, ExpressionFunction>> readExpressions() { List<Pair<String, ExpressionFunction>> expressions = new ArrayList<>(); ApplicationFile expressionPath = application.getFile(modelFiles.expressionsPath()); - if ( ! expressionPath.exists() || ! expressionPath.isDirectory()) return Collections.emptyList(); + if ( ! expressionPath.exists() || ! expressionPath.isDirectory()) return List.of(); for (ApplicationFile expressionFile : expressionPath.listFiles()) { try (BufferedReader reader = new BufferedReader(expressionFile.createReader())) { String name = expressionFile.getPath().getName(); @@ -525,7 +523,7 @@ public class ConvertedModel { List<Pair<String, RankingExpression>> readFunctions() { try { ApplicationFile file = application.getFile(modelFiles.functionsPath()); - if ( ! file.exists()) return Collections.emptyList(); + if ( ! file.exists()) return List.of(); List<Pair<String, RankingExpression>> functions = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(file.createReader())) { @@ -597,7 +595,7 @@ public class ConvertedModel { private List<Pair<String, Tensor>> readSmallConstants() { try { ApplicationFile file = application.getFile(modelFiles.smallConstantsPath()); - if ( ! file.exists()) return Collections.emptyList(); + if ( ! file.exists()) return List.of(); List<Pair<String, Tensor>> constants = new ArrayList<>(); BufferedReader reader = new BufferedReader(file.createReader()); diff --git a/config-model/src/main/java/com/yahoo/vespa/model/ml/OnnxModelInfo.java b/config-model/src/main/java/com/yahoo/vespa/model/ml/OnnxModelInfo.java index 502924ed31a..f47a48b09d7 100644 --- a/config-model/src/main/java/com/yahoo/vespa/model/ml/OnnxModelInfo.java +++ b/config-model/src/main/java/com/yahoo/vespa/model/ml/OnnxModelInfo.java @@ -17,7 +17,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -51,8 +50,8 @@ public class OnnxModelInfo { Map<String, OnnxTypeInfo> outputs, Set<String> initializers, String defaultOutput) { this.app = app; this.modelPath = path; - this.inputs = Collections.unmodifiableMap(inputs); - this.outputs = Collections.unmodifiableMap(outputs); + this.inputs = Map.copyOf(inputs); + this.outputs = Map.copyOf(outputs); this.defaultOutput = defaultOutput; this.initializers = Set.copyOf(initializers); } diff --git a/config-model/src/test/cfg/application/embed/services.xml b/config-model/src/test/cfg/application/embed/services.xml index e92679e3c96..089adbd7517 100644 --- a/config-model/src/test/cfg/application/embed/services.xml +++ b/config-model/src/test/cfg/application/embed/services.xml @@ -40,7 +40,7 @@ <component id="bert-embedder" type="bert-embedder"> <!-- model specifics --> - <transformer-model model-id="minilm-l6-v2" url="application-url"/> + <transformer-model model-id="minilm-l6-v2" url="https://my/url/model.onnx"/> <tokenizer-vocab path="files/vocab.txt"/> <max-tokens>512</max-tokens> <transformer-input-ids>my_input_ids</transformer-input-ids> diff --git a/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java b/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java index cb232c4f812..900799b86a1 100644 --- a/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java @@ -7,7 +7,6 @@ import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.Collection; -import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -47,7 +46,7 @@ public class MapConfigModelRegistryTest { } @Override - public List<ConfigModelId> handlesElements() { return Collections.singletonList(ConfigModelId.fromName("modelB")); } + public List<ConfigModelId> handlesElements() { return List.of(ConfigModelId.fromName("modelB")); } @Override public void doBuild(ModelB model, Element spec, ConfigModelContext modelContext) { } } @@ -57,7 +56,7 @@ public class MapConfigModelRegistryTest { super(ModelB.class); } @Override - public List<ConfigModelId> handlesElements() { return Collections.singletonList(ConfigModelId.fromName("modelB")); } + public List<ConfigModelId> handlesElements() { return List.of(ConfigModelId.fromName("modelB")); } @Override public void doBuild(ModelB model, Element spec, ConfigModelContext modelContext) { } } @@ -73,7 +72,7 @@ public class MapConfigModelRegistryTest { super(ModelA.class); } @Override - public List<ConfigModelId> handlesElements() { return Collections.singletonList(ConfigModelId.fromName("modelA")); } + public List<ConfigModelId> handlesElements() { return List.of(ConfigModelId.fromName("modelA")); } @Override public void doBuild(ModelA model, Element spec, ConfigModelContext modelContext) { } diff --git a/config-model/src/test/java/com/yahoo/config/model/graph/GraphMock.java b/config-model/src/test/java/com/yahoo/config/model/graph/GraphMock.java index 327d48f9276..4c6a5d0e74b 100644 --- a/config-model/src/test/java/com/yahoo/config/model/graph/GraphMock.java +++ b/config-model/src/test/java/com/yahoo/config/model/graph/GraphMock.java @@ -8,7 +8,6 @@ import com.yahoo.config.model.builder.xml.ConfigModelBuilder; import com.yahoo.config.model.builder.xml.ConfigModelId; import org.w3c.dom.Element; -import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -20,7 +19,7 @@ public class GraphMock { public static class BA extends ConfigModelBuilder<A> { public BA() { super(A.class); } - @Override public List<ConfigModelId> handlesElements() { return Arrays.asList(); } + @Override public List<ConfigModelId> handlesElements() { return List.of(); } @Override public void doBuild(A model, Element spec, ConfigModelContext modelContext) { } } public static class A extends ConfigModel { @@ -29,7 +28,7 @@ public class GraphMock { public static class BB extends ConfigModelBuilder<B> { public BB() { super(B.class); } - @Override public List<ConfigModelId> handlesElements() { return Arrays.asList(); } + @Override public List<ConfigModelId> handlesElements() { return List.of(); } @Override public void doBuild(B model, Element spec, ConfigModelContext modelContext) { } } public static class B extends ConfigModel { @@ -40,7 +39,7 @@ public class GraphMock { public static class BC extends ConfigModelBuilder<C> { public BC() { super(C.class); } - @Override public List<ConfigModelId> handlesElements() { return Arrays.asList(); } + @Override public List<ConfigModelId> handlesElements() { return List.of(); } @Override public void doBuild(C model, Element spec, ConfigModelContext modelContext) { } } public static class C extends ConfigModel { @@ -51,7 +50,7 @@ public class GraphMock { public static class BD extends ConfigModelBuilder<D> { public BD() { super(D.class); } - @Override public List<ConfigModelId> handlesElements() { return Arrays.asList(); } + @Override public List<ConfigModelId> handlesElements() { return List.of(); } @Override public void doBuild(D model, Element spec, ConfigModelContext modelContext) { } } public static class D extends ConfigModel { @@ -60,7 +59,7 @@ public class GraphMock { public static class BE extends ConfigModelBuilder<E> { public BE() { super(E.class); } - @Override public List<ConfigModelId> handlesElements() { return Arrays.asList(); } + @Override public List<ConfigModelId> handlesElements() { return List.of(); } @Override public void doBuild(E model, Element spec, ConfigModelContext modelContext) { } } public static class E extends ConfigModel { diff --git a/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java b/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java index 51574432e6d..02ca9effffb 100644 --- a/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java @@ -8,7 +8,6 @@ import org.junit.jupiter.api.Test; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -22,27 +21,29 @@ import static org.junit.jupiter.api.Assertions.*; */ public class HostsXmlProvisionerTest { - private static final String oneHost = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + - "<hosts>\n" + - " <host name=\"test1.yahoo.com\">\n" + - " <alias>node1</alias>\n" + - " <alias>node2</alias>\n" + - " </host>\n" + - "</hosts>"; - - private static final String threeHosts = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + - "<hosts>\n" + - " <host name=\"test1.yahoo.com\">\n" + - " <alias>node1</alias>\n" + - " </host>\n" + - " <host name=\"test2.yahoo.com\">\n" + - " <alias>node2</alias>\n" + - " <alias>node3</alias>\n" + - " </host>\n" + - " <host name=\"test3.yahoo.com\">\n" + - " <alias>node4</alias>\n" + - " </host>\n" + - "</hosts>"; + private static final String oneHost = """ + <?xml version="1.0" encoding="utf-8"?> + <hosts> + <host name="test1.yahoo.com"> + <alias>node1</alias> + <alias>node2</alias> + </host> + </hosts>"""; + + private static final String threeHosts = """ + <?xml version="1.0" encoding="utf-8"?> + <hosts> + <host name="test1.yahoo.com"> + <alias>node1</alias> + </host> + <host name="test2.yahoo.com"> + <alias>node2</alias> + <alias>node3</alias> + </host> + <host name="test3.yahoo.com"> + <alias>node4</alias> + </host> + </hosts>"""; @Test void require_basic_works() { @@ -57,7 +58,7 @@ public class HostsXmlProvisionerTest { assertTrue(map.keySet().containsAll(aliases)); // 5 services, 3 host aliases, mapping to 2 host. - aliases = createAliases(Collections.singletonList("node3")); + aliases = createAliases(List.of("node3")); map = allocate(hostProvisioner, aliases); assertCorrectNumberOfHosts(map, 2); @@ -65,7 +66,7 @@ public class HostsXmlProvisionerTest { assertTrue(map.keySet().containsAll(aliases)); // 5 services, 3 host aliases, mapping to 3 host. - aliases = createAliases(Collections.singletonList("node4")); + aliases = createAliases(List.of("node4")); map = allocate(hostProvisioner, aliases); assertEquals(3, map.size()); assertCorrectNumberOfHosts(map, 3); diff --git a/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java b/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java index e5dca4e5adf..b4f586e3f2f 100644 --- a/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java @@ -12,7 +12,6 @@ import org.xml.sax.SAXException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -40,7 +39,7 @@ public class SingleNodeProvisionerTest { assertTrue(map.keySet().containsAll(aliases)); // 5 services, 3 host aliases, mapping to 2 host. - aliases = createAliases(Collections.singletonList("node3")); + aliases = createAliases(List.of("node3")); map = allocate(hostProvisioner, aliases); assertCorrectNumberOfHost(map, 1); @@ -48,7 +47,7 @@ public class SingleNodeProvisionerTest { assertTrue(map.keySet().containsAll(aliases)); // 5 services, 3 host aliases, mapping to 3 host. - aliases = createAliases(Collections.singletonList("node4")); + aliases = createAliases(List.of("node4")); map = allocate(hostProvisioner, aliases); assertThat(map.size(), is(3)); assertCorrectNumberOfHost(map, 1); diff --git a/config-model/src/test/java/com/yahoo/schema/AttributeUtils.java b/config-model/src/test/java/com/yahoo/schema/AttributeUtils.java index 69e7e14b3be..9ae24d6bfd4 100644 --- a/config-model/src/test/java/com/yahoo/schema/AttributeUtils.java +++ b/config-model/src/test/java/com/yahoo/schema/AttributeUtils.java @@ -8,8 +8,8 @@ import com.yahoo.schema.document.SDField; */ public class AttributeUtils { - public static void addAttributeAspect(SDField field) { - field.parseIndexingScript("{ attribute }"); + public static void addAttributeAspect(String schemaName, SDField field) { + field.parseIndexingScript(schemaName, "{ attribute }"); } } diff --git a/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java b/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java index defc7e59080..88761fc5d3f 100644 --- a/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java @@ -9,7 +9,6 @@ import com.yahoo.schema.document.TemporarySDField; import org.junit.jupiter.api.Test; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -142,14 +141,13 @@ public class DocumentGraphValidatorTest { Schema campaignSchema = new Schema(name, MockApplicationPackage.createEmpty()); SDDocumentType document = new SDDocumentType(name); campaignSchema.addDocument(document); - document.setDocumentReferences(new DocumentReferences(Collections.emptyMap())); + document.setDocumentReferences(new DocumentReferences(Map.of())); Arrays.stream(parents) .map(Schema::getDocument) .forEach(document::inherit); return campaignSchema; } - @SuppressWarnings("deprecation") private static void createDocumentReference(Schema from, Schema to, String refFieldName) { SDDocumentType fromDocument = from.getDocument(); SDField refField = new TemporarySDField(fromDocument, refFieldName, NewDocumentReferenceDataType.forDocumentName(to.getName())); diff --git a/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java b/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java index 76006ad28d7..99946406344 100644 --- a/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java +++ b/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java @@ -8,10 +8,9 @@ import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import org.junit.jupiter.api.Test; +import java.util.List; import java.util.Map; -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.*; /** @@ -34,13 +33,13 @@ public class DocumentReferenceResolverTest { SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema); SDField fooRefToBarField = new SDField (fooDocument, "bar_ref", new NewDocumentReferenceDataType(barDocument.getDocumentType())); - AttributeUtils.addAttributeAspect(fooRefToBarField); + AttributeUtils.addAttributeAspect(fooSchema.getName(), fooRefToBarField); SDField irrelevantField = new SDField(fooDocument, "irrelevant_stuff", DataType.INT); fooDocument.addField(fooRefToBarField); fooDocument.addField(irrelevantField); fooSchema.addDocument(fooDocument); - DocumentReferenceResolver resolver = new DocumentReferenceResolver(asList(fooSchema, barSchema)); + DocumentReferenceResolver resolver = new DocumentReferenceResolver(List.of(fooSchema, barSchema)); resolver.resolveReferences(fooDocument); assertTrue(fooDocument.getDocumentReferences().isPresent()); @@ -50,7 +49,6 @@ public class DocumentReferenceResolverTest { assertSame(fooRefToBarField, fooReferenceMap.get("bar_ref").referenceField()); } - @SuppressWarnings("deprecation") @Test void throws_user_friendly_exception_if_referenced_document_does_not_exist() { Throwable exception = assertThrows(IllegalArgumentException.class, () -> { @@ -60,11 +58,11 @@ public class DocumentReferenceResolverTest { SDField fooRefToBarField = new SDField( fooDocument, "bar_ref", NewDocumentReferenceDataType.forDocumentName("bar")); - AttributeUtils.addAttributeAspect(fooRefToBarField); + AttributeUtils.addAttributeAspect(fooSchema.getName(), fooRefToBarField); fooDocument.addField(fooRefToBarField); fooSchema.addDocument(fooDocument); - DocumentReferenceResolver resolver = new DocumentReferenceResolver(singletonList(fooSchema)); + DocumentReferenceResolver resolver = new DocumentReferenceResolver(List.of(fooSchema)); resolver.resolveReferences(fooDocument); }); assertTrue(exception.getMessage().contains("Invalid document reference 'bar_ref': Could not find document type 'bar'")); @@ -86,7 +84,7 @@ public class DocumentReferenceResolverTest { fooDocument.addField(fooRefToBarField); fooSchema.addDocument(fooDocument); - DocumentReferenceResolver resolver = new DocumentReferenceResolver(asList(fooSchema, barSchema)); + DocumentReferenceResolver resolver = new DocumentReferenceResolver(List.of(fooSchema, barSchema)); resolver.resolveReferences(fooDocument); }); assertTrue(exception.getMessage().contains("The field 'bar_ref' is an invalid document reference. The field must be an attribute.")); diff --git a/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java b/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java index 8c0b8c32d81..b96a43e9b53 100644 --- a/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java +++ b/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java @@ -22,7 +22,7 @@ public class ImportedFieldsEnumeratorTest { Schema parentSchema = new Schema(PARENT, MockApplicationPackage.createEmpty()); SDDocumentType parentDocument = new SDDocumentType(PARENT, parentSchema); var parentField = new SDField(parentDocument, "their_field", DataType.INT); - AttributeUtils.addAttributeAspect(parentField); + AttributeUtils.addAttributeAspect(parentSchema.getName(), parentField); parentDocument.addField(parentField); parentSchema.addDocument(parentDocument); diff --git a/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java index 0cfb9474365..f21999df94c 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java @@ -14,6 +14,7 @@ import java.util.Iterator; import static com.yahoo.config.model.test.TestUtil.joinLines; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * Tests attribute deriving @@ -126,4 +127,38 @@ public class AttributeListTestCase extends AbstractSchemaTestCase { assertFalse(attributes.hasNext()); } + @Test + void bad_map_attribute() throws ParseException { + run_bad_struct_or_map_attribute("map<string,string>"); + } + + @Test + void bad_array_of_struct_attribute() throws ParseException { + run_bad_struct_or_map_attribute("array<s>"); + } + + private void run_bad_struct_or_map_attribute(String type) throws ParseException { + run_bad_struct_or_map_attribute(type, false, true); + run_bad_struct_or_map_attribute(type, true, false); + run_bad_struct_or_map_attribute(type, true, true); + } + + private void run_bad_struct_or_map_attribute(String type, boolean fs, boolean ilscript) throws ParseException { + var exception = assertThrows(IllegalArgumentException.class, () -> ApplicationBuilder.createFromString( + joinLines("search test {", + " document test {", + " struct s {", + " field a type string { }", + " }", + " field metadata type " + type + " {", + " indexing: summary" + (ilscript ? "| attribute" : ""), + " " + (fs ? "attribute: fast-search" : ""), + " }", + " }", + "}")).getSchema()); + assertEquals("For schema 'test': Field 'metadata' of type '" + type + "' cannot be an attribute." + + " Instead specify the struct fields to be searchable as attribute", + exception.getMessage()); + } + } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java index 188017e0af1..60adf7cbaf0 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java @@ -30,7 +30,7 @@ public class IdTestCase extends AbstractExportingTestCase { SDDocumentType document = new SDDocumentType("test"); schema.addDocument(document); SDField uri = new SDField(document, "URI", DataType.URI); - uri.parseIndexingScript("{ summary | index }"); + uri.parseIndexingScript(schema.getName(), "{ summary | index }"); document.addField(uri); new Processing().process(schema, new BaseDeployLogger(), new RankProfileRegistry(), new QueryProfiles(), diff --git a/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java index 766c19bd01c..596ea99c36d 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java @@ -6,7 +6,6 @@ import com.yahoo.document.Field; import com.yahoo.document.StructDataType; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -194,7 +193,7 @@ public class IndexSchemaTestCase { private static void assertFlat(Field fieldToFlatten, Field... expectedFields) { List<Field> actual = new LinkedList<>(IndexSchema.flattenField(fieldToFlatten)); - List<Field> expected = new LinkedList<>(Arrays.asList(expectedFields)); + List<Field> expected = new LinkedList<>(List.of(expectedFields)); Collections.sort(actual); Collections.sort(expected); for (Field field : actual) { diff --git a/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java index 472fa58230e..b1dc2e66bee 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java @@ -65,7 +65,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase { derive("inheritdiamond", builder, builder.getSchema("child")); assertCorrectConfigFiles("inheritdiamond"); } - List<String> files = Arrays.asList("grandparent.sd", "mother.sd", "father.sd", "child.sd"); + List<String> files = List.of("grandparent.sd", "mother.sd", "father.sd", "child.sd"); File outDir = newFolder(tmpDir, "out"); for (int startIdx = 0; startIdx < files.size(); ++startIdx) { var builder = new ApplicationBuilder(new TestProperties()); @@ -159,7 +159,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase { Schema parentSchema = new Schema("parent", MockApplicationPackage.createEmpty()); parentSchema.addDocument(parent); SDField prefixed = parent.addField("prefixed", DataType.STRING); - prefixed.parseIndexingScript("{ index }"); + prefixed.parseIndexingScript(parentSchema.getName(), "{ index }"); prefixed.addIndex(new Index("prefixed", true)); SDDocumentType child = new SDDocumentType("child"); @@ -175,7 +175,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase { @Test void testInheritStructDiamondNew() throws IOException, ParseException { String dir = "src/test/derived/declstruct/"; - List<String> files = Arrays.asList("common.sd", "foo.sd", "bar.sd", "foobar.sd"); + List<String> files = List.of("common.sd", "foo.sd", "bar.sd", "foobar.sd"); var builder = new ApplicationBuilder(new TestProperties()); for (String fileName : files) { builder.addSchemaFile(dir + fileName); diff --git a/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java index 97a3f06ac64..505960256b8 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java @@ -15,7 +15,7 @@ import com.yahoo.schema.processing.Processing; import com.yahoo.vespa.model.container.search.QueryProfiles; import org.junit.jupiter.api.Test; -import java.util.Arrays; +import java.util.List; import java.util.Set; import static com.yahoo.schema.processing.AssertIndexingScript.assertIndexing; @@ -36,7 +36,7 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { SDDocumentType document = new SDDocumentType("literalboost"); schema.addDocument(document); SDField field1 = document.addField("a", DataType.STRING); - field1.parseIndexingScript("{ index }"); + field1.parseIndexingScript(schema.getName(), "{ index }"); field1.setLiteralBoost(20); RankProfile other = new RankProfile("other", schema, rankProfileRegistry); rankProfileRegistry.add(other); @@ -50,7 +50,7 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { derived.getAttributeFields(); // TODO: assert content // Check il script addition - assertIndexing(Arrays.asList("clear_state | guard { input a | tokenize normalize stem:\"BEST\" | index a; }", + assertIndexing(List.of("clear_state | guard { input a | tokenize normalize stem:\"BEST\" | index a; }", "clear_state | guard { input a | tokenize | index a_literal; }"), schema); @@ -69,7 +69,7 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { SDDocumentType document = new SDDocumentType("literalboost"); schema.addDocument(document); SDField field1 = document.addField("a", DataType.STRING); - field1.parseIndexingScript("{ index }"); + field1.parseIndexingScript(schema.getName(), "{ index }"); RankProfile other = new RankProfile("other", schema, rankProfileRegistry); rankProfileRegistry.add(other); other.addRankSetting(new RankProfile.RankSetting("a", RankProfile.RankSetting.Type.LITERALBOOST, 333)); @@ -78,7 +78,7 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { DerivedConfiguration derived = new DerivedConfiguration(schema, rankProfileRegistry); // Check il script addition - assertIndexing(Arrays.asList("clear_state | guard { input a | tokenize normalize stem:\"BEST\" | index a; }", + assertIndexing(List.of("clear_state | guard { input a | tokenize normalize stem:\"BEST\" | index a; }", "clear_state | guard { input a | tokenize | index a_literal; }"), schema); @@ -95,15 +95,15 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { SDDocumentType document = new SDDocumentType("msb"); schema.addDocument(document); SDField field1 = document.addField("title", DataType.STRING); - field1.parseIndexingScript("{ summary | index }"); + field1.parseIndexingScript(schema.getName(), "{ summary | index }"); field1.setLiteralBoost(20); SDField field2 = document.addField("body", DataType.STRING); - field2.parseIndexingScript("{ summary | index }"); + field2.parseIndexingScript(schema.getName(), "{ summary | index }"); field2.setLiteralBoost(20); schema = ApplicationBuilder.buildFromRawSchema(schema, rankProfileRegistry, new QueryProfileRegistry()); new DerivedConfiguration(schema, rankProfileRegistry); - assertIndexing(Arrays.asList("clear_state | guard { input title | tokenize normalize stem:\"BEST\" | summary title | index title; }", + assertIndexing(List.of("clear_state | guard { input title | tokenize normalize stem:\"BEST\" | summary title | index title; }", "clear_state | guard { input body | tokenize normalize stem:\"BEST\" | summary body | index body; }", "clear_state | guard { input title | tokenize | index title_literal; }", "clear_state | guard { input body | tokenize | index body_literal; }"), diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java index 593f26eb074..8ae6ada7a63 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java @@ -12,13 +12,11 @@ import com.yahoo.schema.document.SDField; import com.yahoo.schema.document.TemporarySDField; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; -import static java.util.Collections.emptyMap; import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -63,7 +61,7 @@ public class SchemaOrdererTestCase extends AbstractSchemaTestCase { private static Schema createSchema(String name, Map<String, Schema> schemas) { Schema schema = new Schema(name, MockApplicationPackage.createEmpty()); SDDocumentType document = new SDDocumentType(name); - document.setDocumentReferences(new DocumentReferences(emptyMap())); + document.setDocumentReferences(new DocumentReferences(Map.of())); schema.addDocument(document); schemas.put(schema.getName(), schema); return schema; @@ -74,9 +72,8 @@ public class SchemaOrdererTestCase extends AbstractSchemaTestCase { } private static void assertOrder(List<String> expectedSearchOrder, List<String> inputNames) { - inputNames.sort((a, b) -> a.compareTo(b)); Map<String, Schema> schemas = createSchemas(); - List<Schema> inputSchemas = inputNames.stream() + List<Schema> inputSchemas = inputNames.stream().sorted() .map(schemas::get) .map(Objects::requireNonNull) .toList(); @@ -88,7 +85,6 @@ public class SchemaOrdererTestCase extends AbstractSchemaTestCase { assertEquals(expectedSearchOrder, actualSearchOrder); } - @SuppressWarnings("deprecation") private static void createDocumentReference(Schema from, Schema to, String refFieldName) { SDDocumentType fromDocument = from.getDocument(); SDField refField = new TemporarySDField(fromDocument, refFieldName, NewDocumentReferenceDataType.forDocumentName(to.getName())); @@ -102,44 +98,44 @@ public class SchemaOrdererTestCase extends AbstractSchemaTestCase { @Test void testPerfectOrderingIsKept() { - assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("grandParent", "mother", "father", "daughter", "son", "product", "pc", "alone")); + assertOrder(List.of("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), + List.of("grandParent", "mother", "father", "daughter", "son", "product", "pc", "alone")); } @Test void testOneLevelReordering() { - assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("grandParent", "daughter", "son", "mother", "father", "pc", "product", "alone")); + assertOrder(List.of("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), + List.of("grandParent", "daughter", "son", "mother", "father", "pc", "product", "alone")); } @Test void testMultiLevelReordering() { - assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("daughter", "son", "mother", "father", "grandParent", "pc", "product", "alone")); + assertOrder(List.of("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), + List.of("daughter", "son", "mother", "father", "grandParent", "pc", "product", "alone")); } @Test void testAloneIsKeptInPlaceWithMultiLevelReordering() { - assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("alone", "daughter", "son", "mother", "father", "grandParent", "pc", "product")); + assertOrder(List.of("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), + List.of("alone", "daughter", "son", "mother", "father", "grandParent", "pc", "product")); } @Test void testPartialMultiLevelReordering() { - assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("daughter", "grandParent", "mother", "son", "father", "product", "pc", "alone")); + assertOrder(List.of("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), + List.of("daughter", "grandParent", "mother", "son", "father", "product", "pc", "alone")); } @Test void testMultilevelReorderingAccrossHierarchies() { - assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone")); + assertOrder(List.of("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), + List.of("daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone")); } @Test void referees_are_ordered_before_referrer() { - assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "accessory-pc", "son"), - Arrays.asList("accessory-pc", "daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone")); + assertOrder(List.of("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "accessory-pc", "son"), + List.of("accessory-pc", "daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone")); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java index a27bc824b45..63510785ca5 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java @@ -172,7 +172,7 @@ public class SummaryTestCase extends AbstractSchemaTestCase { schema.addDocument(document); String fieldName = "location"; SDField field = document.addField(fieldName, PositionDataType.INSTANCE); - field.parseIndexingScript("{ attribute | summary }"); + field.parseIndexingScript(schema.getName(), "{ attribute | summary }"); new Processing().process(schema, new BaseDeployLogger(), new RankProfileRegistry(), new QueryProfiles(), true, false, Set.of()); diff --git a/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java index d2b3acc9a1e..cdfe376416b 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java @@ -32,7 +32,7 @@ public class TypeConversionTestCase extends AbstractSchemaTestCase { SDDocumentType document = new SDDocumentType("test"); schema.addDocument(document); SDField a = new SDField(document, "a", DataType.STRING); - a.parseIndexingScript("{ index }"); + a.parseIndexingScript(schema.getName(), "{ index }"); document.addField(a); new Processing().process(schema, new BaseDeployLogger(), rankProfileRegistry, new QueryProfiles(), diff --git a/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java index 852f567ccfa..a90b4fa8d9f 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java @@ -46,7 +46,7 @@ public class VsmFieldsTestCase { void reference_type_field_is_unsearchable() { Schema schema = createSchema(); SDField field = new TemporarySDField(schema.getDocument(), "ref_field", NewDocumentReferenceDataType.forDocumentName("parent_type")); - field.parseIndexingScript("{ summary }"); + field.parseIndexingScript(schema.getName(), "{ summary }"); schema.getDocument().addField(field); VsmfieldsConfig cfg = vsmfieldsConfig(schema); @@ -59,7 +59,7 @@ public class VsmFieldsTestCase { private void testIndexMatching(Matching matching, VsmfieldsConfig.Fieldspec.Normalize.Enum normalize, String arg1) { Schema schema = createSchema(); SDField field = new TemporarySDField(schema.getDocument(), "f", DataType.STRING); - field.parseIndexingScript("{ index }"); + field.parseIndexingScript(schema.getName(), "{ index }"); field.setMatching(matching); schema.getDocument().addField(field); VsmfieldsConfig cfg = vsmfieldsConfig(schema); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AddDataTypeAndTransformToSummaryOfImportedFieldsTest.java b/config-model/src/test/java/com/yahoo/schema/processing/AddDataTypeAndTransformToSummaryOfImportedFieldsTest.java index f09a95b89a0..3da6f250853 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/AddDataTypeAndTransformToSummaryOfImportedFieldsTest.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/AddDataTypeAndTransformToSummaryOfImportedFieldsTest.java @@ -19,7 +19,7 @@ import com.yahoo.vespa.documentmodel.SummaryField; import com.yahoo.vespa.documentmodel.SummaryTransform; import org.junit.jupiter.api.Test; -import java.util.Collections; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -63,7 +63,7 @@ public class AddDataTypeAndTransformToSummaryOfImportedFieldsTest { SDField targetField = new SDField(doc, "target_field", DataType.INT); DocumentReference documentReference = new DocumentReference(new Field("reference_field"), targetSchema); ImportedField importedField = new ImportedSimpleField(fieldName, documentReference, targetField); - return new ImportedFields(Collections.singletonMap(fieldName, importedField)); + return new ImportedFields(Map.of(fieldName, importedField)); } private static DocumentSummary createDocumentSummary(String fieldName, Schema schema) { diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java index c2cc28ea6b3..310706cb0d1 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java @@ -18,7 +18,7 @@ import com.yahoo.vespa.indexinglanguage.expressions.ScriptExpression; import com.yahoo.vespa.model.container.search.QueryProfiles; import org.junit.jupiter.api.Test; -import java.util.Arrays; +import java.util.List; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; @@ -105,7 +105,7 @@ public class IndexingScriptRewriterTestCase extends AbstractSchemaTestCase { @Test void testDerivingFromSimple() throws Exception { - assertIndexing(Arrays.asList("clear_state | guard { input access | attribute access; }", + assertIndexing(List.of("clear_state | guard { input access | attribute access; }", "clear_state | guard { input category | split \";\" | attribute category_arr; }", "clear_state | guard { input category | tokenize | index category; }", "clear_state | guard { input categories_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categories; }", @@ -127,8 +127,7 @@ public class IndexingScriptRewriterTestCase extends AbstractSchemaTestCase { @Test void testIndexRewrite() throws Exception { assertIndexing( - Arrays.asList("clear_state | guard { input title_src | lowercase | normalize | " + - " tokenize | index title; }", + List.of("clear_state | guard { input title_src | lowercase | normalize | tokenize | index title; }", "clear_state | guard { input title_src | summary title_s; }"), ApplicationBuilder.buildFromFile("src/test/examples/indexrewrite.sd")); } @@ -151,7 +150,7 @@ public class IndexingScriptRewriterTestCase extends AbstractSchemaTestCase { void requireThatMaxTermOccurrencesIsPropagated() { var field = new SDField("test", DataType.STRING); field.getMatching().maxTermOccurrences(10); - field.parseIndexingScript("{ summary | index }"); + field.parseIndexingScript("test", "{ summary | index }"); assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" max-occurrences:10 | summary test | index test; }", field); } @@ -173,14 +172,14 @@ public class IndexingScriptRewriterTestCase extends AbstractSchemaTestCase { private static SDField createField(String name, DataType type, String script) { SDField field = new SDField(null, name, type); - field.parseIndexingScript(script); + field.parseIndexingScript("test", script); return field; } private static SDField createPredicateField( String name, DataType type, String script, int arity, OptionalLong lower_bound, OptionalLong upper_bound) { SDField field = new SDField(null, name, type); - field.parseIndexingScript(script); + field.parseIndexingScript("test", script); Index index = new Index("foo"); index.setBooleanIndexDefiniton(new BooleanIndexDefinition( OptionalInt.of(arity), lower_bound, upper_bound, OptionalDouble.empty())); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java index 71c91533f54..4053834784f 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java @@ -8,7 +8,7 @@ import com.yahoo.yolean.Exceptions; import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.Arrays; +import java.util.List; import static com.yahoo.schema.processing.AssertIndexingScript.assertIndexing; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -154,7 +154,7 @@ public class IndexingValidationTestCase extends AbstractExportingTestCase { @Test void testExtraField() throws IOException, ParseException { assertIndexing( - Arrays.asList("clear_state | guard { input my_index | tokenize normalize stem:\"BEST\" | index my_index | summary my_index }", + List.of("clear_state | guard { input my_index | tokenize normalize stem:\"BEST\" | index my_index | summary my_index }", "clear_state | guard { input my_input | tokenize normalize stem:\"BEST\" | index my_extra | summary my_extra }"), ApplicationBuilder.buildFromFile("src/test/examples/indexing_extra.sd")); } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ParentChildSearchModel.java b/config-model/src/test/java/com/yahoo/schema/processing/ParentChildSearchModel.java index af275feffed..129d65584ba 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ParentChildSearchModel.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ParentChildSearchModel.java @@ -36,8 +36,11 @@ public class ParentChildSearchModel { } protected static TemporarySDField createField(SDDocumentType repo, String name, DataType dataType, String indexingScript) { + return createField(repo, repo.getName(), name, dataType, indexingScript); + } + protected static TemporarySDField createField(SDDocumentType repo, String schemaName, String name, DataType dataType, String indexingScript) { TemporarySDField result = new TemporarySDField(repo, name, dataType); - result.parseIndexingScript(indexingScript); + result.parseIndexingScript(schemaName, indexingScript); return result; } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java index 007006bf6d3..87a66046fe5 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java @@ -13,8 +13,8 @@ import com.yahoo.vespa.documentmodel.SummaryTransform; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Iterator; +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -27,7 +27,7 @@ public class PositionTestCase { @Test void inherited_position_zcurve_field_is_not_added_to_document_fieldset() throws Exception { - ApplicationBuilder sb = ApplicationBuilder.createFromFiles(Arrays.asList( + ApplicationBuilder sb = ApplicationBuilder.createFromFiles(List.of( "src/test/examples/position_base.sd", "src/test/examples/position_inherited.sd")); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java index 9213f97fd9f..6cbd8faf3b0 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java @@ -19,7 +19,7 @@ import com.yahoo.searchlib.rankingexpression.evaluation.TensorValue; import com.yahoo.tensor.Tensor; import org.junit.jupiter.api.Test; -import java.util.Collections; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -94,16 +94,17 @@ public class RankingExpressionWithTransformerTokensTestCase { MockApplicationPackage application = (MockApplicationPackage) MockApplicationPackage.createEmpty(); RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); QueryProfileRegistry queryProfileRegistry = application.getQueryProfiles(); - String sdContent = "search test {\n" + - " document test {}\n" + - " rank-profile my_profile inherits default {}\n" + - "}"; + String sdContent = """ + search test { + document test {} + rank-profile my_profile inherits default {} + }"""; ApplicationBuilder schemaBuilder = new ApplicationBuilder(application, new MockFileRegistry(), new BaseDeployLogger(), new TestProperties(), rankProfileRegistry, queryProfileRegistry); schemaBuilder.addSchema(sdContent); schemaBuilder.build(true); Schema schema = schemaBuilder.getSchema(); RankProfile rp = rankProfileRegistry.get(schema, "my_profile"); - return new RankProfileTransformContext(rp, queryProfileRegistry, Collections.emptyMap(), null, Collections.emptyMap(), Collections.emptyMap()); + return new RankProfileTransformContext(rp, queryProfileRegistry, Map.of(), null, Map.of(), Map.of()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java index 0f16330ce11..a602503a71c 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java @@ -21,7 +21,6 @@ import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels; import org.junit.jupiter.api.Test; import java.io.IOException; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -102,12 +101,12 @@ public class RankingExpressionsTestCase extends AbstractSchemaTestCase { { AttributeFields attributes = new AttributeFields(schema); - verifyProfile(rankProfileRegistry.get(schema, "base"), Arrays.asList("large_f", "large_m"), - Arrays.asList(new Pair<>("rankingExpression(large_f).expressionName", "base.large_f"), new Pair<>("rankingExpression(large_m).expressionName", "base.large_m")), + verifyProfile(rankProfileRegistry.get(schema, "base"), List.of("large_f", "large_m"), + List.of(new Pair<>("rankingExpression(large_f).expressionName", "base.large_f"), new Pair<>("rankingExpression(large_m).expressionName", "base.large_m")), largeExpressions, queryProfiles, models, attributes, properties); - for (String child : Arrays.asList("child_a", "child_b")) { - verifyProfile(rankProfileRegistry.get(schema, child), Arrays.asList("large_f", "large_m", "large_local_f", "large_local_m"), - Arrays.asList(new Pair<>("rankingExpression(large_f).expressionName", child + ".large_f"), new Pair<>("rankingExpression(large_m).expressionName", child + ".large_m"), + for (String child : List.of("child_a", "child_b")) { + verifyProfile(rankProfileRegistry.get(schema, child), List.of("large_f", "large_m", "large_local_f", "large_local_m"), + List.of(new Pair<>("rankingExpression(large_f).expressionName", child + ".large_f"), new Pair<>("rankingExpression(large_m).expressionName", child + ".large_m"), new Pair<>("rankingExpression(large_local_f).expressionName", child + ".large_local_f"), new Pair<>("rankingExpression(large_local_m).expressionName", child + ".large_local_m"), new Pair<>("vespa.rank.firstphase", "rankingExpression(firstphase)"), new Pair<>("rankingExpression(firstphase).expressionName", child + ".firstphase")), largeExpressions, queryProfiles, models, attributes, properties); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java b/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java index be72d2b12fa..8585a206d77 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java @@ -18,7 +18,7 @@ import com.yahoo.vespa.documentmodel.DocumentSummary; import com.yahoo.vespa.documentmodel.SummaryField; import org.junit.jupiter.api.Test; -import java.util.Collections; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -65,7 +65,7 @@ public class ValidateFieldTypesTest { SDField targetField = new SDField(targetSchema.getDocument(), "target_field", dataType); DocumentReference documentReference = new DocumentReference(new Field("reference_field"), targetSchema); ImportedField importedField = new ImportedSimpleField(fieldName, documentReference, targetField); - return new ImportedFields(Collections.singletonMap(fieldName, importedField)); + return new ImportedFields(Map.of(fieldName, importedField)); } private static DocumentSummary createDocumentSummary(String fieldName, DataType dataType, Schema schema) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java index 88e1ba7a1a6..94dd0f367a3 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java @@ -8,6 +8,8 @@ import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.admin.monitoring.MetricsConsumer; import org.junit.jupiter.api.Test; +import java.util.List; + import static ai.vespa.metrics.set.DefaultMetrics.defaultMetricSet; import static ai.vespa.metrics.set.DefaultVespaMetrics.defaultVespaMetricSet; import static ai.vespa.metrics.set.NetworkMetrics.networkMetricSet; @@ -21,7 +23,6 @@ import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.c import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getCustomConsumer; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getModel; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.servicesWithAdminOnly; -import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -72,7 +73,7 @@ public class MetricsConsumersTest { void vespa_consumer_can_be_amended_via_admin_object() { VespaModel model = getModel(servicesWithAdminOnly(), hosted); var additionalMetric = new Metric("additional-metric"); - model.getAdmin().setAdditionalDefaultMetrics(new MetricSet("amender-metrics", singleton(additionalMetric))); + model.getAdmin().setAdditionalDefaultMetrics(new MetricSet("amender-metrics", List.of(additionalMetric))); ConsumersConfig config = consumersConfigFromModel(model); assertEquals(numMetricsForVespaConsumer + 1, config.consumer(0).metric().size()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java index b2291099b44..ae1db366c9f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java @@ -18,6 +18,7 @@ import java.util.List; import java.util.logging.Level; import static com.yahoo.config.model.test.TestUtil.joinLines; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -67,7 +68,9 @@ public class ComplexFieldsValidatorTestCase { "}", "}")); }); - assertTrue(exception.getMessage().contains(getExpectedMessage("docTopics (docTopics.topics, docTopics.topics.id, docTopics.topics.label)"))); + assertEquals("For schema 'test': Field 'docTopics.topics' of type 'array<topic>' cannot be an attribute." + + " Instead specify the struct fields to be searchable as attribute", + exception.getMessage()); } @Test diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/PublicApiBundleValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/PublicApiBundleValidatorTest.java index 19be886d3e5..c5ef2238f9b 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/PublicApiBundleValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/PublicApiBundleValidatorTest.java @@ -8,7 +8,6 @@ import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; -import java.util.Arrays; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; @@ -42,7 +41,7 @@ public class PublicApiBundleValidatorTest { assertThat(output, containsString("uses non-public Vespa APIs: [")); // List of packages should be sorted - List<String> packages = Arrays.asList(output.substring(output.indexOf("[") + 1, output.indexOf("]")).split(", ")); + List<String> packages = List.of(output.substring(output.indexOf("[") + 1, output.indexOf("]")).split(", ")); assertThat(packages, hasSize(2)); assertThat(packages, contains("ai.vespa.lib.non_public", "com.yahoo.lib.non_public")); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java index e4b9b45489d..829bd6148a6 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java @@ -54,7 +54,7 @@ public class StartupCommandChangeValidatorTest { private static MockRoot createRootWithChildren(TreeConfigProducer<?>... children) { MockRoot root = new MockRoot(); - Arrays.asList(children).forEach(root::addChild); + List.of(children).forEach(root::addChild); root.freezeModelTopology(); return root; } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java index 91ba97817d6..8778f0c26c0 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java @@ -9,7 +9,6 @@ import com.yahoo.vespa.model.content.utils.ContentClusterUtils; import com.yahoo.vespa.model.content.utils.SchemaBuilder; import com.yahoo.vespa.model.search.DocumentDatabase; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -32,15 +31,15 @@ public abstract class ContentClusterFixture { public ContentClusterFixture(String entireSd) throws Exception { currentCluster = new ContentClusterBuilder().build( - ContentClusterUtils.createMockRoot(Arrays.asList(entireSd))); + ContentClusterUtils.createMockRoot(List.of(entireSd))); nextCluster = new ContentClusterBuilder().build( - ContentClusterUtils.createMockRoot(Arrays.asList(entireSd))); + ContentClusterUtils.createMockRoot(List.of(entireSd))); } private static ContentCluster createCluster(String sdContent) throws Exception { return new ContentClusterBuilder().build( ContentClusterUtils.createMockRoot( - Arrays.asList(new SchemaBuilder().content(sdContent).build()))); + List.of(new SchemaBuilder().content(sdContent).build()))); } protected DocumentDatabase currentDb() { @@ -65,7 +64,7 @@ public abstract class ContentClusterFixture { } public void assertValidation(VespaConfigChangeAction exp) { - assertValidation(Arrays.asList(exp)); + assertValidation(List.of(exp)); } public void assertValidation(List<VespaConfigChangeAction> exp) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java index 684bd619ba1..129649ae1fb 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java @@ -8,7 +8,6 @@ import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeActi import org.junit.jupiter.api.Test; import java.time.Instant; -import java.util.Arrays; import java.util.List; import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.newRefeedAction; @@ -50,7 +49,7 @@ public class DocumentDatabaseChangeValidatorTest { "field f3 type string { indexing: summary } " + "field f4 type array<s> { struct-field s1 { indexing: attribute } }"); Instant.now(); - f.assertValidation(Arrays.asList( + f.assertValidation(List.of( newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1' changed: add attribute aspect"), newRestartAction(ClusterSpec.Id.from("test"), diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java index 44743c4fa3e..26a4f532362 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java @@ -14,10 +14,9 @@ import com.yahoo.vespa.model.application.validation.change.VespaRefeedAction; import org.junit.jupiter.api.Test; import java.time.Instant; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.Set; import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.newRefeedAction; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -108,7 +107,7 @@ public class DocumentTypeChangeValidatorTest { "field f2 type string { indexing: summary } field f1 type int { indexing: summary }"); Instant.now(); Instant.now(); - f.assertValidation(Arrays.asList(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'string' -> 'int'"), + f.assertValidation(List.of(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'string' -> 'int'"), newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f2' changed: data type: 'int' -> 'string'"))); } @@ -210,8 +209,8 @@ public class DocumentTypeChangeValidatorTest { new NewDocumentType.Name("mydoc"), headerfields, new FieldSets(Optional.empty()), - Collections.emptySet(), - Collections.emptySet()); + Set.of(), + Set.of()); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java index 6b58cac3f6c..cd54a20523f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java @@ -12,7 +12,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.List; public class IndexingScriptChangeValidatorTest { @@ -126,7 +125,7 @@ public class IndexingScriptChangeValidatorTest { void requireThatMultipleChangesRequireReindexing() throws Exception { new Fixture(FIELD + " { indexing: index } " + FIELD_F2 + " { indexing: index }", FIELD + " { indexing: index \n stemming: none } " + FIELD_F2 + " { indexing: index \n normalizing: none }"). - assertValidation(Arrays.asList(expectedReindexingAction("f1", "stemming: 'best' -> 'none'", + assertValidation(List.of(expectedReindexingAction("f1", "stemming: 'best' -> 'none'", "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }", "{ input f1 | tokenize normalize | index f1; }"), expectedReindexingAction("f2", "normalizing: 'ACCENT' -> 'NONE'", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java index fac82f3e675..924419daeae 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java @@ -26,7 +26,6 @@ import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.List; import java.util.Set; @@ -876,8 +875,8 @@ public class ContentBuilderTest extends DomBuilderTest { VespaModel m = new VespaModelCreatorWithMockPkg(new MockApplicationPackage.Builder() .withHosts(getHosts()) .withServices(combined) - .withSchemas(Arrays.asList(MockApplicationPackage.MUSIC_SCHEMA, - MockApplicationPackage.BOOK_SCHEMA)) + .withSchemas(List.of(MockApplicationPackage.MUSIC_SCHEMA, + MockApplicationPackage.BOOK_SCHEMA)) .build()) .create(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java index 853cfdd9429..0e616661191 100755 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java @@ -18,7 +18,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -112,7 +111,7 @@ public class DomAdminV2BuilderTest extends DomBuilderTest { @Test void multitenant() { - List<ConfigServerSpec> configServerSpecs = Arrays.asList( + List<ConfigServerSpec> configServerSpecs = List.of( new TestProperties.Spec("test1", 19070, 2181), new TestProperties.Spec("test2", 19070, 2181), new TestProperties.Spec("test3", 19070, 2181)); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java index 764e31fe13a..c7525dec6a3 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java @@ -8,7 +8,7 @@ import com.yahoo.vespa.model.search.Tuning; import org.junit.jupiter.api.Test; import org.w3c.dom.Element; -import java.util.Arrays; +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -22,7 +22,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { private static Element parseXml(String... xmlLines) { return parse("<tuning>", "<searchnode>", - CollectionUtil.mkString(Arrays.asList(xmlLines), "\n"), + CollectionUtil.mkString(List.of(xmlLines), "\n"), "</searchnode>", "</tuning>"); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java index 6b384269910..56f492f3fca 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java @@ -20,7 +20,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.w3c.dom.Element; -import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -98,7 +97,7 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest { @Test void ensureSearchChainsExists() { - for (String id : Arrays.asList("provider:1", "source:1@provider:1", "default")) { + for (String id : List.of("provider:1", "source:1@provider:1", "default")) { assertNotNull(getSearchChain(id), "Missing search chain " + id); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/component/ModelTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/component/ModelTest.java new file mode 100644 index 00000000000..7660ae45c3a --- /dev/null +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/component/ModelTest.java @@ -0,0 +1,33 @@ +// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. +package com.yahoo.vespa.model.container.component; + +import com.yahoo.config.model.deploy.DeployState; +import com.yahoo.text.XML; +import org.junit.jupiter.api.Test; + +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * @author hmusum + */ +public class ModelTest { + + @Test + void invalid_url(){ + var xml = """ + <component id="bert-embedder" type="bert-embedder"> + <transformer-model url="models/e5-base-v2.onnx" /> + <tokenizer-vocab path="models/vocab.txt"/> + </component> + """; + + var state = new DeployState.Builder().build(); + var element = XML.getDocument(xml).getDocumentElement(); +var exception = assertThrows(IllegalArgumentException.class, + () -> Model.fromXml(state, element, "transformer-model", Set.of())); +org.junit.jupiter.api.Assertions.assertEquals("Invalid url 'models/e5-base-v2.onnx': url has no 'scheme' component", exception.getMessage()); + } + +} diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java index b933d86655e..4e14fbcd671 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java @@ -21,12 +21,9 @@ import com.yahoo.vespa.model.container.configserver.option.CloudConfigOptions; import com.yahoo.vespa.model.container.xml.ConfigServerContainerModelBuilder; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Function; -import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; @@ -46,7 +43,7 @@ public class ConfigserverClusterTest { @Test void zookeeperConfig_only_config_servers_set_hosted() { - TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Collections.emptyList()); + TestOptions testOptions = createTestOptions(List.of("cfg1", "localhost", "cfg3"), List.of()); ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::hostname, "cfg1", "localhost", "cfg3"); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::id, 0, 1, 2); @@ -57,7 +54,7 @@ public class ConfigserverClusterTest { @Test void zookeeperConfig_with_config_servers_and_zk_ids_hosted() { - TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(4, 2, 3)); + TestOptions testOptions = createTestOptions(List.of("cfg1", "localhost", "cfg3"), List.of(4, 2, 3)); ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::hostname, "cfg1", "localhost", "cfg3"); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::id, 4, 2, 3); @@ -68,7 +65,7 @@ public class ConfigserverClusterTest { @Test void zookeeperConfig_self_hosted() { final boolean hostedVespa = false; - TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(4, 2, 3), hostedVespa); + TestOptions testOptions = createTestOptions(List.of("cfg1", "localhost", "cfg3"), List.of(4, 2, 3), hostedVespa); ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::hostname, "cfg1", "localhost", "cfg3"); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::id, 4, 2, 3); @@ -80,7 +77,7 @@ public class ConfigserverClusterTest { @Test void zookeeperConfig_uneven_number_of_config_servers_and_zk_ids() { assertThrows(IllegalArgumentException.class, () -> { - TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Collections.singletonList(1)); + TestOptions testOptions = createTestOptions(List.of("cfg1", "localhost", "cfg3"), List.of(1)); getConfig(ZookeeperServerConfig.class, testOptions); }); } @@ -88,7 +85,7 @@ public class ConfigserverClusterTest { @Test void zookeeperConfig_negative_zk_id() { assertThrows(IllegalArgumentException.class, () -> { - TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(1, 2, -1)); + TestOptions testOptions = createTestOptions(List.of("cfg1", "localhost", "cfg3"), List.of(1, 2, -1)); getConfig(ZookeeperServerConfig.class, testOptions); }); } @@ -137,7 +134,7 @@ public class ConfigserverClusterTest { private static <T> void assertZookeeperServerProperty( List<ZookeeperServerConfig.Server> zkServers, Function<ZookeeperServerConfig.Server, T> propertyMapper, T... expectedProperties) { List<T> actualPropertyValues = zkServers.stream().map(propertyMapper).toList(); - List<T> expectedPropertyValues = Arrays.asList(expectedProperties); + List<T> expectedPropertyValues = List.of(expectedProperties); assertEquals(expectedPropertyValues, actualPropertyValues); } @@ -169,7 +166,7 @@ public class ConfigserverClusterTest { } private static <CONFIGTYPE extends ConfigInstance> CONFIGTYPE getConfig(Class<CONFIGTYPE> clazz) { - return getConfig(clazz, createTestOptions(Collections.emptyList(), Collections.emptyList())); + return getConfig(clazz, createTestOptions(List.of(), List.of())); } private static <CONFIGTYPE extends ConfigInstance> CONFIGTYPE getConfig(Class<CONFIGTYPE> clazz, TestOptions testOptions) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java index 73c4075a182..3345f935e1d 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java @@ -7,7 +7,6 @@ import com.yahoo.config.model.api.ContainerEndpoint; import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; import java.util.Set; @@ -29,7 +28,7 @@ public class BlockFeedGlobalEndpointsFilterTest { @Test void does_not_setup_blocking_rule_when_endpoints_empty() { - var filter = new BlockFeedGlobalEndpointsFilter(Collections.emptySet(), true); + var filter = new BlockFeedGlobalEndpointsFilter(Set.of(), true); var config = getConfig(filter); assertEquals(0, config.rule().size()); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java index a066308b426..a832c54021f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java @@ -19,8 +19,8 @@ import org.junit.jupiter.api.BeforeEach; import org.w3c.dom.Element; import java.util.ArrayList; -import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.logging.Level; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -88,7 +88,7 @@ public abstract class ContainerModelBuilderTestBase { private static void generateDefaultSearchChains(ContainerCluster<?> cluster) { ContainerSearch search = cluster.getSearch(); if (search != null) - search.initializeSearchChains(Collections.emptyMap()); + search.initializeSearchChains(Map.of()); } protected ComponentsConfig componentsConfig() { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java index 4efffc8310a..fb1e176f707 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java @@ -158,7 +158,7 @@ public class EmbedderTestCase { var model = loadModel(Path.fromString("src/test/cfg/application/embed/"), false); var cluster = model.getContainerClusters().get("container"); var embedderCfg = assertBertEmbedderComponentPresent(cluster); - assertEquals("application-url", modelReference(embedderCfg, "transformerModel").url().orElseThrow().value()); + assertEquals("https://my/url/model.onnx", modelReference(embedderCfg, "transformerModel").url().orElseThrow().value()); assertEquals("files/vocab.txt", modelReference(embedderCfg, "tokenizerVocab").path().orElseThrow().value()); assertEquals("", embedderCfg.transformerTokenTypeIds()); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java index 10adca12f91..46097da434e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java @@ -19,13 +19,12 @@ import org.w3c.dom.Element; import org.xml.sax.SAXException; import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.logging.Level; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -218,18 +217,17 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase { } private String verifyLogMessage(TestLogger logger, String... invalidOptions) { - List<String> strings = Arrays.asList(invalidOptions.clone()); + List<String> strings = List.of(invalidOptions); // Verify that nothing is logged if there are no invalid options if (strings.isEmpty()) { - assertEquals(0, logger.msgs.size(), logger.msgs.size() > 0 ? logger.msgs.get(0).getSecond() : ""); + assertEquals(0, logger.msgs.size(), !logger.msgs.isEmpty() ? logger.msgs.get(0).getSecond() : ""); return null; } - assertTrue(logger.msgs.size() > 0, "Expected 1 or more log messages for invalid JM options, got none"); + assertFalse(logger.msgs.isEmpty(), "Expected 1 or more log messages for invalid JM options, got none"); Pair<Level, String> firstOption = logger.msgs.get(0); assertEquals(Level.WARNING, firstOption.getFirst()); - Collections.sort(strings); return firstOption.getSecond(); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java index 1ba5bebea7e..96e1f2edf76 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java @@ -22,7 +22,6 @@ import com.yahoo.vespa.config.content.AllClustersBucketSpacesConfig; import com.yahoo.vespa.config.content.DistributionConfig; import com.yahoo.vespa.config.content.FleetcontrollerConfig; import com.yahoo.vespa.config.content.StorDistributionConfig; -import com.yahoo.vespa.config.content.StorFilestorConfig; import com.yahoo.vespa.config.content.core.StorDistributormanagerConfig; import com.yahoo.vespa.config.content.core.StorServerConfig; import com.yahoo.vespa.config.search.DispatchConfig; @@ -43,8 +42,6 @@ import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; import com.yahoo.yolean.Exceptions; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; @@ -72,7 +69,7 @@ public class ContentClusterTest extends ContentBaseTest { @Test void testHierarchicRedundancy() { - ContentCluster cc = parse("" + + ContentCluster cc = parse( "<content version=\"1.0\" id=\"storage\">\n" + " <documents/>" + " <engine>" + @@ -947,8 +944,8 @@ public class ContentClusterTest extends ContentBaseTest { .properties(props); MockRoot root = flavor.isPresent() ? ContentClusterUtils.createMockRoot(new SingleNodeProvisioner(flavor.get()), - Collections.emptyList(), deployStateBuilder) : - ContentClusterUtils.createMockRoot(Collections.emptyList(), deployStateBuilder); + List.of(), deployStateBuilder) : + ContentClusterUtils.createMockRoot(List.of(), deployStateBuilder); ContentCluster cluster = ContentClusterUtils.createCluster(clusterXml, root); root.freezeModelTopology(); cluster.validate(); @@ -1104,8 +1101,8 @@ public class ContentClusterTest extends ContentBaseTest { assertEquals(2, config.cluster().size()); - assertClusterHasBucketSpaceMappings(config, "foo_c", Arrays.asList("bunnies", "hares"), Collections.emptyList()); - assertClusterHasBucketSpaceMappings(config, "bar_c", Collections.emptyList(), Collections.singletonList("rabbits")); + assertClusterHasBucketSpaceMappings(config, "foo_c", List.of("bunnies", "hares"), List.of()); + assertClusterHasBucketSpaceMappings(config, "bar_c", List.of(), List.of("rabbits")); } @Test diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java index 55ec9f4efe2..8c08b9054a4 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java @@ -12,7 +12,6 @@ import com.yahoo.vespa.model.content.utils.DocType; import com.yahoo.vespa.model.content.utils.SchemaBuilder; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import static com.yahoo.config.model.test.TestUtil.joinLines; @@ -60,12 +59,12 @@ public class ContentSchemaClusterTest { private static ContentClusterBuilder createClusterBuilderWithGlobalType() { return new ContentClusterBuilder() - .docTypes(Arrays.asList(DocType.indexGlobal("global"), DocType.index("regular"))); + .docTypes(List.of(DocType.indexGlobal("global"), DocType.index("regular"))); } private static ContentClusterBuilder createClusterBuilderWithOnlyDefaultTypes() { return new ContentClusterBuilder() - .docTypes(Arrays.asList(DocType.index("marve"), DocType.index("fleksnes"))); + .docTypes(List.of(DocType.index("marve"), DocType.index("fleksnes"))); } private static ProtonConfig getProtonConfig(ContentCluster cluster) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java index 6066a27cff5..e671a47b36c 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java @@ -11,8 +11,6 @@ import java.util.Map; import java.util.Set; import java.util.stream.Stream; -import static java.util.Collections.emptyMap; -import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; @@ -25,7 +23,7 @@ public class GlobalDistributionValidatorTest { @Test void validation_succeeds_on_no_documents() { new GlobalDistributionValidator() - .validate(emptyMap(), emptySet()); + .validate(Map.of(), Set.of()); } @Test diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java index b41d92bd63f..901c307723e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java @@ -21,7 +21,6 @@ import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -489,7 +488,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { private DocprocClusterSpec(String name, DocprocChainSpec ... chains) { this.name = name; - this.chains.addAll(Arrays.asList(chains)); + this.chains.addAll(List.of(chains)); } } @@ -500,7 +499,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { private DocprocChainSpec(String name, String ... inherits) { this.name = name; - this.inherits.addAll(Arrays.asList(inherits)); + this.inherits.addAll(List.of(inherits)); } } @@ -542,7 +541,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { } public static List<String> generateSchemas(String ... sdNames) { - return generateSchemas(Arrays.asList(sdNames)); + return generateSchemas(List.of(sdNames)); } public static List<String> generateSchemas(List<String> sdNames) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java index a6fa0334668..2fb9a67a9ae 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java @@ -4,8 +4,6 @@ package com.yahoo.vespa.model.content; import com.yahoo.documentmodel.NewDocumentType; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -40,13 +38,13 @@ public class ReservedDocumentTypeNameValidatorTest { @Test void exception_is_not_thrown_on_unreserved_name() { ReservedDocumentTypeNameValidator validator = new ReservedDocumentTypeNameValidator(); - validator.validate(asDocTypeMapping(Collections.singletonList("foo"))); + validator.validate(asDocTypeMapping(List.of("foo"))); } @Test void validation_is_case_insensitive() { ReservedDocumentTypeNameValidator validator = new ReservedDocumentTypeNameValidator(); - Map<String, NewDocumentType> orderedDocTypes = new TreeMap<>(asDocTypeMapping(Arrays.asList("NULL", "True", "anD"))); + Map<String, NewDocumentType> orderedDocTypes = new TreeMap<>(asDocTypeMapping(List.of("NULL", "True", "anD"))); try { validator.validate(orderedDocTypes); fail(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java index c5a645bd863..06794a3c1f3 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java @@ -5,8 +5,6 @@ import com.yahoo.documentmodel.NewDocumentType; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -20,24 +18,24 @@ public class TopologicalDocumentTypeSorterTest { @Test void require_that_types_without_references_are_returned_in_input_order() { - assertOrder(Arrays.asList("a"), new DocumentTypesBuilder().add("a")); - assertOrder(Arrays.asList("a", "c", "b"), + assertOrder(List.of("a"), new DocumentTypesBuilder().add("a")); + assertOrder(List.of("a", "c", "b"), new DocumentTypesBuilder().add("a").add("c").add("b")); } @Test void require_that_types_with_references_are_sorted_in_topological_order() { - assertOrder(Arrays.asList("b", "a"), new DocumentTypesBuilder() - .add("a", Arrays.asList("b")) + assertOrder(List.of("b", "a"), new DocumentTypesBuilder() + .add("a", List.of("b")) .add("b")); - assertOrder(Arrays.asList("c", "b", "a"), new DocumentTypesBuilder() - .add("a", Arrays.asList("b", "c")) - .add("b", Arrays.asList("c")) + assertOrder(List.of("c", "b", "a"), new DocumentTypesBuilder() + .add("a", List.of("b", "c")) + .add("b", List.of("c")) .add("c")); - assertOrder(Arrays.asList("b", "a", "d", "c"), new DocumentTypesBuilder() - .add("a", Arrays.asList("b")) + assertOrder(List.of("b", "a", "d", "c"), new DocumentTypesBuilder() + .add("a", List.of("b")) .add("b") - .add("c", Arrays.asList("d")) + .add("c", List.of("d")) .add("d")); } @@ -52,7 +50,7 @@ public class TopologicalDocumentTypeSorterTest { private final List<NewDocumentType> result = new ArrayList<>(); public DocumentTypesBuilder add(String docTypeName) { - return add(docTypeName, Collections.emptyList()); + return add(docTypeName, List.of()); } public DocumentTypesBuilder add(String docTypeName, List<String> docTypeNameReferences) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java index 3bd7b7a4c1a..1043ddd2c0b 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java @@ -6,9 +6,7 @@ import com.yahoo.text.XML; import com.yahoo.vespa.model.builder.xml.dom.ModelElement; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -35,7 +33,7 @@ public class GlobalDistributionBuilderTest { " <document type=\"" + GLOBAL_2.getName() + "\" global=\"true\"/>" + "</documents>"; - Set<NewDocumentType> expectedResult = new HashSet<>(Arrays.asList(GLOBAL_1, GLOBAL_2)); + Set<NewDocumentType> expectedResult = Set.of(GLOBAL_1, GLOBAL_2); Set<NewDocumentType> actualResult = builder.build(new ModelElement(XML.getDocument(documentsElement).getDocumentElement())); assertEquals(expectedResult, actualResult); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/utils/ContentClusterBuilder.java b/config-model/src/test/java/com/yahoo/vespa/model/content/utils/ContentClusterBuilder.java index 61ce5172ceb..277b07023e6 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/utils/ContentClusterBuilder.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/utils/ContentClusterBuilder.java @@ -7,7 +7,6 @@ import com.yahoo.vespa.model.content.cluster.ContentCluster; import java.util.Arrays; import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; import static com.yahoo.config.model.test.TestUtil.joinLines; @@ -21,7 +20,7 @@ public class ContentClusterBuilder { private String name = "mycluster"; private int redundancy = 1; private int searchableCopies = 1; - private List<DocType> docTypes = Arrays.asList(DocType.index("test")); + private List<DocType> docTypes = List.of(DocType.index("test")); private String groupXml = getSimpleGroupXml(); private Optional<String> dispatchXml = Optional.empty(); private Optional<Double> protonDiskLimit = Optional.empty(); @@ -54,8 +53,8 @@ public class ContentClusterBuilder { } public ContentClusterBuilder docTypes(String ... docTypes) { - this.docTypes = Arrays.asList(docTypes).stream(). - map(type -> DocType.index(type)). + this.docTypes = Arrays.stream(docTypes). + map(DocType::index). toList(); return this; } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/utils/ContentClusterUtils.java b/config-model/src/test/java/com/yahoo/vespa/model/content/utils/ContentClusterUtils.java index a8c67ebf0a3..360ad19b710 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/utils/ContentClusterUtils.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/utils/ContentClusterUtils.java @@ -16,7 +16,6 @@ import com.yahoo.vespa.model.admin.monitoring.builder.Metrics; import com.yahoo.vespa.model.content.cluster.ContentCluster; import org.w3c.dom.Document; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -67,7 +66,7 @@ public class ContentClusterUtils { ConfigModelContext context = ConfigModelContext.create(applicationType, root.getDeployState(), null,null, root, null); - return new ContentCluster.Builder(admin).build(Collections.emptyList(), context, doc.getDocumentElement()); + return new ContentCluster.Builder(admin).build(List.of(), context, doc.getDocumentElement()); } public static ContentCluster createCluster(String clusterXml, List<String> schemas, DeployState.Builder deployStateBuilder) throws Exception { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/utils/DocType.java b/config-model/src/test/java/com/yahoo/vespa/model/content/utils/DocType.java index 3ffb33a47c8..ce05fa27e2e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/utils/DocType.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/utils/DocType.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.content.utils; -import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -46,7 +45,7 @@ public class DocType { } public static String listToXml(DocType... docTypes) { - return listToXml(Arrays.asList(docTypes)); + return listToXml(List.of(docTypes)); } public static String listToXml(List<DocType> docTypes) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/utils/SchemaBuilder.java b/config-model/src/test/java/com/yahoo/vespa/model/content/utils/SchemaBuilder.java index 304f3dc426f..55ad9149a17 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/utils/SchemaBuilder.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/utils/SchemaBuilder.java @@ -38,8 +38,7 @@ public class SchemaBuilder { } public static List<String> createSchemas(String ... docTypes) { - return Arrays.asList(docTypes) - .stream() + return Arrays.stream(docTypes) .map(type -> new SchemaBuilder().name(type).build()) .toList(); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java index f9999a30869..7809a97f85c 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java @@ -41,8 +41,8 @@ public class SchemaClusterTest { SDDocumentType sdt1 = new SDDocumentType("s1"); Schema schema1 = new Schema("s1", MockApplicationPackage.createEmpty()); SDField f1 = new SDField(sdt1, "f1", DataType.STRING); - f1.addAttribute(new Attribute("f1", DataType.STRING)); - f1.setIndexingScript(new ScriptExpression(new StatementExpression(new AttributeExpression("f1")))); + f1.addAttribute(new Attribute(schema1.getName(), f1.getName(), "f1", DataType.STRING)); + f1.setIndexingScript("s1", new ScriptExpression(new StatementExpression(new AttributeExpression("f1")))); sdt1.addField(f1); schema1.addDocument(sdt1); @@ -50,8 +50,8 @@ public class SchemaClusterTest { SDDocumentType sdt2 = new SDDocumentType("s2"); Schema schema2 = new Schema("s2", MockApplicationPackage.createEmpty()); SDField f2 = new SDField(sdt2, "f2", DataType.STRING); - f2.addAttribute(new Attribute("f2", DataType.STRING)); - f2.setIndexingScript(new ScriptExpression(new StatementExpression(new AttributeExpression("f2")))); + f2.addAttribute(new Attribute(schema2.getName(), f2.getName(), "f2", DataType.STRING)); + f2.setIndexingScript("s2", new ScriptExpression(new StatementExpression(new AttributeExpression("f2")))); sdt2.addField(f2); schema2.addDocument(sdt2); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java index 8502bfa92f4..672bba83e87 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java @@ -102,7 +102,7 @@ public class SchemaInfoTestCase { var schemaInfoTester = new SchemaInfoTester(); var schema = schemaInfoTester.createSchema("test"); var field = (SDField)schema.getDocument().addField(new SDField("f1", DataType.STRING)); - var attribute = field.addAttribute(new Attribute("f1Attribute", field.getDataType())); + var attribute = field.addAttribute(new Attribute(schema.getName(), field.getName(), "f1Attribute", field.getDataType())); attribute.getAliases().add("a1"); attribute.getAliases().add("a2"); assertEquals(""" diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java index 7efacd6b5ad..e17db551798 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java @@ -12,7 +12,6 @@ import com.yahoo.vespa.model.search.SearchCluster; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -181,7 +180,7 @@ public class SchemaTester { } public static List<String> generateSchemas(String schemaContent, String rankProfile, String ... schemaNames) { - return generateSchemas(schemaContent, rankProfile, Arrays.asList(schemaNames)); + return generateSchemas(schemaContent, rankProfile, List.of(schemaNames)); } public static List<String> generateSchemas(String schemaContent, String rankProfile, List<String> schemaNames) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/ApiConfigModel.java b/config-model/src/test/java/com/yahoo/vespa/model/test/ApiConfigModel.java index 41003f03c0d..b9be56d8d69 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/test/ApiConfigModel.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/test/ApiConfigModel.java @@ -10,7 +10,6 @@ import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -50,7 +49,7 @@ public class ApiConfigModel extends ConfigModel { @Override public List<ConfigModelId> handlesElements() { - return Arrays.asList(ConfigModelId.fromName("api")); + return List.of(ConfigModelId.fromName("api")); } @Override diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/SimpleConfigModel.java b/config-model/src/test/java/com/yahoo/vespa/model/test/SimpleConfigModel.java index 61bd3d885f5..d9be865bc7d 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/test/SimpleConfigModel.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/test/SimpleConfigModel.java @@ -10,7 +10,6 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -20,8 +19,8 @@ import java.util.List; */ public class SimpleConfigModel extends ConfigModel implements TestApi { - private List<SimpleService> simpleServices = new ArrayList<>(); - private List<ParentService> parentServices = new ArrayList<>(); + private final List<SimpleService> simpleServices = new ArrayList<>(); + private final List<ParentService> parentServices = new ArrayList<>(); public SimpleConfigModel(ConfigModelContext modelContext) { super(modelContext); @@ -43,7 +42,7 @@ public class SimpleConfigModel extends ConfigModel implements TestApi { @Override public List<ConfigModelId> handlesElements() { - return Arrays.asList(ConfigModelId.fromName("simple")); + return List.of(ConfigModelId.fromName("simple")); } @Override @@ -54,11 +53,10 @@ public class SimpleConfigModel extends ConfigModel implements TestApi { NodeList childNodes = spec.getChildNodes(); for (int i=0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); - if (! (child instanceof Element)) { + if (! (child instanceof Element e)) { // skip #text and #comment nodes continue; } - Element e = (Element)child; String service = e.getTagName(); if (service.equals("simpleservice")) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/utils/ApplicationPackageUtils.java b/config-model/src/test/java/com/yahoo/vespa/model/test/utils/ApplicationPackageUtils.java index b9bc34688b7..ce373e558ef 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/test/utils/ApplicationPackageUtils.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/test/utils/ApplicationPackageUtils.java @@ -2,7 +2,6 @@ package com.yahoo.vespa.model.test.utils; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -50,7 +49,7 @@ public class ApplicationPackageUtils { } public static List<String> generateSchemas(String ... sdNames) { - return generateSchemas(Arrays.asList(sdNames)); + return generateSchemas(List.of(sdNames)); } public static List<String> generateSchemas(List<String> sdNames) { diff --git a/config-provisioning/src/main/java/com/yahoo/config/provision/HostFilter.java b/config-provisioning/src/main/java/com/yahoo/config/provision/HostFilter.java index 4fe6f8453de..f79fee08bc4 100644 --- a/config-provisioning/src/main/java/com/yahoo/config/provision/HostFilter.java +++ b/config-provisioning/src/main/java/com/yahoo/config/provision/HostFilter.java @@ -4,7 +4,6 @@ package com.yahoo.config.provision; import com.yahoo.text.StringUtilities; import java.util.Collection; -import java.util.Collections; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -44,27 +43,27 @@ public class HostFilter { /** Returns a filter which matches all hosts */ public static HostFilter all() { - return new HostFilter(Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet()); + return new HostFilter(Set.of(), Set.of(), Set.of(), Set.of()); } /** Returns a filter which matches a given host only */ public static HostFilter hostname(String hostname) { - return new HostFilter(Collections.singleton(hostname), Collections.emptySet(), Collections.emptySet(), Collections.emptySet()); + return new HostFilter(Set.of(hostname), Set.of(), Set.of(), Set.of()); } /** Returns a filter which matches a given flavor only */ public static HostFilter flavor(String flavor) { - return new HostFilter(Collections.emptySet(), Collections.singleton(flavor), Collections.emptySet(), Collections.emptySet()); + return new HostFilter(Set.of(), Set.of(flavor), Set.of(), Set.of()); } /** Returns a filter which matches a given cluster type only */ public static HostFilter clusterType(ClusterSpec.Type clusterType) { - return new HostFilter(Collections.emptySet(), Collections.emptySet(), Collections.singleton(clusterType), Collections.emptySet()); + return new HostFilter(Set.of(), Set.of(), Set.of(clusterType), Set.of()); } /** Returns a filter which matches a given cluster id only */ public static HostFilter clusterId(ClusterSpec.Id clusterId) { - return new HostFilter(Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.singleton(clusterId)); + return new HostFilter(Set.of(), Set.of(), Set.of(), Set.of(clusterId)); } /** Returns a host filter from three optional conditions */ diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java index 87165c0afef..93995bace63 100644 --- a/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java +++ b/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java @@ -4,7 +4,7 @@ package com.yahoo.config.provision; import com.yahoo.component.Vtag; import org.junit.jupiter.api.Test; -import java.util.Collections; +import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -45,10 +45,10 @@ public class HostFilterTest { @Test void testMultiConditionFilter() { - HostFilter typeAndId = HostFilter.from(Collections.emptyList(), - Collections.emptyList(), - Collections.singletonList(ClusterSpec.Type.content), - Collections.singletonList(ClusterSpec.Id.from("type1"))); + HostFilter typeAndId = HostFilter.from(List.of(), + List.of(), + List.of(ClusterSpec.Type.content), + List.of(ClusterSpec.Id.from("type1"))); assertFalse(typeAndId.matches("anyhost", "flavor", membership("content/anyType/0/0/stateful"))); assertFalse(typeAndId.matches("anyhost", "flavor", membership("container/type1/0/0"))); diff --git a/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServer.java b/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServer.java index 2034a537b7c..3ec968e545a 100644 --- a/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServer.java +++ b/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServer.java @@ -21,6 +21,7 @@ import com.yahoo.vespa.config.protocol.JRTServerConfigRequestV3; import java.util.Arrays; import java.util.Iterator; +import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -180,7 +181,7 @@ public class ConfigProxyRpcServer implements Runnable, TargetWatcher { String ret; System.out.println(proxyServer.getMode()); if (proxyServer.getMode().requiresConfigSource()) { - proxyServer.updateSourceConnections(Arrays.asList(sources.split(","))); + proxyServer.updateSourceConnections(List.of(sources.split(","))); ret = "Updated config sources to: " + sources; } else { ret = "Cannot update sources when in '" + proxyServer.getMode().name() + "' mode"; diff --git a/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClient.java b/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClient.java index e69d76ec124..a34ad69d22c 100644 --- a/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClient.java +++ b/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClient.java @@ -6,7 +6,6 @@ import com.yahoo.vespa.config.ConfigKey; import com.yahoo.vespa.config.RawConfig; import com.yahoo.vespa.config.protocol.JRTServerConfigRequest; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.logging.Level; @@ -56,7 +55,7 @@ class MemoryCacheConfigClient implements ConfigSourceClient { @Override public List<String> getSourceConnections() { - return Collections.singletonList("N/A"); + return List.of("N/A"); } @Override diff --git a/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/filedistribution/UrlDownloadRpcServer.java b/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/filedistribution/UrlDownloadRpcServer.java index 8074c1bd702..bf84e02ec9d 100644 --- a/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/filedistribution/UrlDownloadRpcServer.java +++ b/config-proxy/src/main/java/com/yahoo/vespa/config/proxy/filedistribution/UrlDownloadRpcServer.java @@ -16,6 +16,7 @@ import net.jpountz.xxhash.XXHashFactory; import java.io.File; import java.nio.ByteBuffer; import java.nio.file.Files; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; @@ -94,6 +95,7 @@ class UrlDownloadRpcServer { } private static Downloader downloader(String url) { + Objects.requireNonNull(url, "url cannot be null"); URI uri = new URI(url); return switch (uri.getScheme()) { case "http", "https" -> new UrlDownloader(); diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigTester.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigTester.java index aa063b1ea54..656187ea8e5 100644 --- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigTester.java +++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigTester.java @@ -17,7 +17,6 @@ import com.yahoo.vespa.config.protocol.Payload; import com.yahoo.vespa.config.protocol.Trace; import com.yahoo.vespa.config.util.ConfigUtils; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -30,7 +29,7 @@ import static com.yahoo.vespa.config.PayloadChecksum.Type.XXHASH64; public class ConfigTester { private static final long defaultTimeout = 10000; - private static final List<String> defContent = Collections.singletonList("bar string"); + private static final List<String> defContent = List.of("bar string"); static RawConfig fooConfig; static RawConfig barConfig; diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MockConfigSourceClient.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MockConfigSourceClient.java index baafe2ae2dd..69f6e0e8dae 100644 --- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MockConfigSourceClient.java +++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MockConfigSourceClient.java @@ -5,7 +5,6 @@ import com.yahoo.vespa.config.ConfigKey; import com.yahoo.vespa.config.RawConfig; import com.yahoo.vespa.config.protocol.JRTServerConfigRequest; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -51,7 +50,7 @@ public class MockConfigSourceClient implements ConfigSourceClient{ @Override public List<String> getSourceConnections() { - return Collections.singletonList("N/A"); + return List.of("N/A"); } @Override diff --git a/config/src/main/java/com/yahoo/config/subscription/ConfigSourceSet.java b/config/src/main/java/com/yahoo/config/subscription/ConfigSourceSet.java index 65737d116c5..3d42967802f 100755..100644 --- a/config/src/main/java/com/yahoo/config/subscription/ConfigSourceSet.java +++ b/config/src/main/java/com/yahoo/config/subscription/ConfigSourceSet.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.subscription; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; @@ -49,7 +48,7 @@ public class ConfigSourceSet implements ConfigSource { * @param addresses Connection endpoints on the format "tcp/host:port". */ public ConfigSourceSet(String[] addresses) { - this(Arrays.asList(addresses)); + this(List.of(addresses)); } /** diff --git a/config/src/main/java/com/yahoo/config/subscription/impl/JarConfigSubscription.java b/config/src/main/java/com/yahoo/config/subscription/impl/JarConfigSubscription.java index d33e1b422e0..03f791e5536 100644 --- a/config/src/main/java/com/yahoo/config/subscription/impl/JarConfigSubscription.java +++ b/config/src/main/java/com/yahoo/config/subscription/impl/JarConfigSubscription.java @@ -14,7 +14,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; -import java.util.Arrays; +import java.util.List; import java.util.jar.JarFile; import java.util.zip.ZipEntry; @@ -56,7 +56,7 @@ public class JarConfigSubscription<T extends ConfigInstance> extends ConfigSubsc throw new IllegalArgumentException("Config '" + key.getName() + "' not found in '" + jarName + "!/" + path + "'."); T config; try { - ConfigPayload payload = new CfgConfigPayloadBuilder().deserialize(Arrays.asList(IOUtils.readAll(new InputStreamReader(jarFile.getInputStream(zipEntry), StandardCharsets.UTF_8)).split("\n"))); + ConfigPayload payload = new CfgConfigPayloadBuilder().deserialize(List.of(IOUtils.readAll(new InputStreamReader(jarFile.getInputStream(zipEntry), StandardCharsets.UTF_8)).split("\n"))); config = payload.toInstance(configClass, key.getConfigId()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); diff --git a/config/src/main/java/com/yahoo/config/subscription/impl/RawConfigSubscription.java b/config/src/main/java/com/yahoo/config/subscription/impl/RawConfigSubscription.java index dd08c1fe29c..d4e4e075e23 100644 --- a/config/src/main/java/com/yahoo/config/subscription/impl/RawConfigSubscription.java +++ b/config/src/main/java/com/yahoo/config/subscription/impl/RawConfigSubscription.java @@ -8,7 +8,8 @@ import com.yahoo.vespa.config.ConfigKey; import com.yahoo.vespa.config.ConfigPayload; import com.yahoo.vespa.config.PayloadChecksums; -import java.util.Arrays; +import java.util.List; + /** * Subscription used when config id is raw:... @@ -34,7 +35,7 @@ public class RawConfigSubscription<T extends ConfigInstance> extends ConfigSubsc } if (payload == null) { payload = inputPayload; - ConfigPayload configPayload = new CfgConfigPayloadBuilder().deserialize(Arrays.asList(payload.split("\n"))); + ConfigPayload configPayload = new CfgConfigPayloadBuilder().deserialize(List.of(payload.split("\n"))); setConfig(0L, false, configPayload.toInstance(configClass, key.getConfigId()), PayloadChecksums.empty()); return true; } diff --git a/config/src/main/java/com/yahoo/vespa/config/ConfigDefinition.java b/config/src/main/java/com/yahoo/vespa/config/ConfigDefinition.java index f640f5c1294..2545b82b3dd 100644 --- a/config/src/main/java/com/yahoo/vespa/config/ConfigDefinition.java +++ b/config/src/main/java/com/yahoo/vespa/config/ConfigDefinition.java @@ -4,7 +4,6 @@ package com.yahoo.vespa.config; import com.yahoo.yolean.Exceptions; import java.util.ArrayList; -import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -567,7 +566,7 @@ public class ConfigDefinition { public void addEnumDef(String id, String valsCommaSep, String defVal) { String[] valArr = valsCommaSep.split(","); - addEnumDef(id, Arrays.asList(valArr), defVal); + addEnumDef(id, List.of(valArr), defVal); } public void addStringDef(String id, String defVal) { diff --git a/config/src/main/java/com/yahoo/vespa/config/ConfigDefinitionBuilder.java b/config/src/main/java/com/yahoo/vespa/config/ConfigDefinitionBuilder.java index c8e86c97661..8e8a48580d8 100644 --- a/config/src/main/java/com/yahoo/vespa/config/ConfigDefinitionBuilder.java +++ b/config/src/main/java/com/yahoo/vespa/config/ConfigDefinitionBuilder.java @@ -4,7 +4,8 @@ package com.yahoo.vespa.config; import com.yahoo.config.codegen.CNode; import com.yahoo.config.codegen.LeafCNode; -import java.util.Arrays; +import java.util.List; + /** * Builds a ConfigDefinition from a tree of CNodes. @@ -183,9 +184,9 @@ public class ConfigDefinitionBuilder { private static void addNode(ConfigDefinition def, LeafCNode.EnumLeaf leaf) { if (leaf.getDefaultValue() != null) { - def.addEnumDef(leaf.getName(), Arrays.asList(leaf.getLegalValues()), leaf.getDefaultValue().getValue()); + def.addEnumDef(leaf.getName(), List.of(leaf.getLegalValues()), leaf.getDefaultValue().getValue()); } else { - def.addEnumDef(leaf.getName(), Arrays.asList(leaf.getLegalValues()), null); + def.addEnumDef(leaf.getName(), List.of(leaf.getLegalValues()), null); } } diff --git a/config/src/main/java/com/yahoo/vespa/config/RawConfig.java b/config/src/main/java/com/yahoo/vespa/config/RawConfig.java index 9964e63bfd6..3f7d9c15fa7 100755..100644 --- a/config/src/main/java/com/yahoo/vespa/config/RawConfig.java +++ b/config/src/main/java/com/yahoo/vespa/config/RawConfig.java @@ -11,7 +11,6 @@ import com.yahoo.vespa.config.protocol.Payload; import com.yahoo.vespa.config.protocol.VespaVersion; import com.yahoo.vespa.config.util.ConfigUtils; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -40,7 +39,7 @@ public class RawConfig extends ConfigInstance { * @param defMd5 The md5 sum of the .def-file. */ public RawConfig(ConfigKey<?> key, String defMd5) { - this(key, defMd5, null, PayloadChecksums.empty(), 0L, false, 0, Collections.emptyList(), Optional.empty()); + this(key, defMd5, null, PayloadChecksums.empty(), 0L, false, 0, List.of(), Optional.empty()); } public RawConfig(ConfigKey<?> key, String defMd5, Payload payload, PayloadChecksums payloadChecksums, long generation, diff --git a/config/src/main/java/com/yahoo/vespa/config/benchmark/LoadTester.java b/config/src/main/java/com/yahoo/vespa/config/benchmark/LoadTester.java index 6a0f8ea1cdc..4c61c995491 100644 --- a/config/src/main/java/com/yahoo/vespa/config/benchmark/LoadTester.java +++ b/config/src/main/java/com/yahoo/vespa/config/benchmark/LoadTester.java @@ -28,7 +28,6 @@ import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -139,7 +138,7 @@ public class LoadTester { if (!name.endsWith(".def")) continue; String contents = IOUtils.readFile(f); ConfigDefinitionKey key = ConfigUtils.createConfigDefinitionKeyFromDefFile(f); - ret.put(key, new Tuple2<>(ConfigUtils.getDefMd5(Arrays.asList(contents.split("\n"))), contents.split("\n"))); + ret.put(key, new Tuple2<>(ConfigUtils.getDefMd5(List.of(contents.split("\n"))), contents.split("\n"))); } System.out.println("# Read " + ret.size() + " def files from " + defDir.getPath()); return ret; diff --git a/config/src/main/java/com/yahoo/vespa/config/protocol/DefContent.java b/config/src/main/java/com/yahoo/vespa/config/protocol/DefContent.java index 6b3c1f0040d..a4c4dfde8f0 100644 --- a/config/src/main/java/com/yahoo/vespa/config/protocol/DefContent.java +++ b/config/src/main/java/com/yahoo/vespa/config/protocol/DefContent.java @@ -7,7 +7,6 @@ import com.yahoo.slime.*; import java.lang.reflect.Field; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -47,7 +46,7 @@ public class DefContent { } public static DefContent fromArray(String[] schema) { - return fromList(Arrays.asList(schema)); + return fromList(List.of(schema)); } /** diff --git a/config/src/test/java/com/yahoo/config/subscription/CfgConfigPayloadBuilderTest.java b/config/src/test/java/com/yahoo/config/subscription/CfgConfigPayloadBuilderTest.java index 851ef28155d..29582fedc44 100644 --- a/config/src/test/java/com/yahoo/config/subscription/CfgConfigPayloadBuilderTest.java +++ b/config/src/test/java/com/yahoo/config/subscription/CfgConfigPayloadBuilderTest.java @@ -8,7 +8,6 @@ import com.yahoo.foo.SimpletypesConfig; import com.yahoo.vespa.config.ConfigPayload; import org.junit.Test; -import java.util.Arrays; import java.util.List; import static com.yahoo.test.json.JsonTestHelper.assertJsonEquals; @@ -216,7 +215,7 @@ public class CfgConfigPayloadBuilderTest { @Test public void test_config_with_comments() { CfgConfigPayloadBuilderTest.assertDeserializedConfigEqualsJson( - Arrays.asList( + List.of( "fielda b\n", "#fielda c\n", "#fieldb c\n", @@ -230,7 +229,7 @@ public class CfgConfigPayloadBuilderTest { @Test public void testConvertingMaps() { - List<String> payload = Arrays.asList( + List<String> payload = List.of( "intmap{\"foo\"} 1337", "complexmap{\"key\"}.foo 1337", "nestedmap{\"key1\"}.foo{\"key2\"}.bar 1337" diff --git a/config/src/test/java/com/yahoo/config/subscription/ConfigInstancePayloadTest.java b/config/src/test/java/com/yahoo/config/subscription/ConfigInstancePayloadTest.java index d737a2d5930..3327e94c32b 100644 --- a/config/src/test/java/com/yahoo/config/subscription/ConfigInstancePayloadTest.java +++ b/config/src/test/java/com/yahoo/config/subscription/ConfigInstancePayloadTest.java @@ -11,7 +11,6 @@ import com.yahoo.vespa.config.ConfigTransformer; import org.junit.Test; import java.io.File; -import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -55,7 +54,7 @@ public class ConfigInstancePayloadTest { doublearr(123.0). stringarr("bar"). enumarr(Enumarr.VALUES). - refarr(Arrays.asList(":parent:", ":parent", "parent:")). // test collection based setter + refarr(List.of(":parent:", ":parent", "parent:")). // test collection based setter fileArr("bin"). pathArr(FileReference.mockFileReferenceForUnitTesting(new File("pom.xml"))). intMap("one", 1). diff --git a/config/src/test/java/com/yahoo/config/subscription/ConfigInstanceTest.java b/config/src/test/java/com/yahoo/config/subscription/ConfigInstanceTest.java index 1c6ca46eb04..bbd4ae7e797 100644 --- a/config/src/test/java/com/yahoo/config/subscription/ConfigInstanceTest.java +++ b/config/src/test/java/com/yahoo/config/subscription/ConfigInstanceTest.java @@ -49,15 +49,15 @@ public class ConfigInstanceTest { @Ignore public void testRetainOldValuesOnConfigUpdates() { AppConfig config = new AppConfig(new AppConfig.Builder()); - //config.setConfig(Arrays.asList("message \"one\"", "times 333"), "", 0L); + //config.setConfig(List.of("message \"one\"", "times 333"), "", 0L); assertEquals("one", config.message()); assertEquals(333, config.times()); - //config.setConfig(Arrays.asList("message \"two\""), "", 0L); + //config.setConfig(List.of("message \"two\""), "", 0L); assertEquals("two", config.message()); assertEquals("config.times retains previously set value", 333, config.times()); - //config.setConfig(Arrays.asList("times 666"), "", 0L); + //config.setConfig(List.of("times 666"), "", 0L); assertEquals("config.message retains previously set value", "two", config.message()); assertEquals(666, config.times()); } diff --git a/config/src/test/java/com/yahoo/config/subscription/ConfigInstanceUtilTest.java b/config/src/test/java/com/yahoo/config/subscription/ConfigInstanceUtilTest.java index 58c8a740bdb..6b392db5906 100644 --- a/config/src/test/java/com/yahoo/config/subscription/ConfigInstanceUtilTest.java +++ b/config/src/test/java/com/yahoo/config/subscription/ConfigInstanceUtilTest.java @@ -11,7 +11,7 @@ import com.yahoo.vespa.config.ConfigPayloadBuilder; import org.junit.Test; import java.io.File; -import java.util.Arrays; +import java.util.List; import static org.junit.Assert.assertEquals; import static com.yahoo.foo.FunctionTestConfig.*; @@ -97,7 +97,7 @@ public class ConfigInstanceUtilTest { doublearr(123.0). stringarr("bar"). enumarr(Enumarr.VALUES). - refarr(Arrays.asList(":parent:", ":parent", "parent:")). // test collection based setter + refarr(List.of(":parent:", ":parent", "parent:")). // test collection based setter fileArr("bin"). basicStruct(b -> b. diff --git a/config/src/test/java/com/yahoo/config/subscription/ConfigSubscriptionTest.java b/config/src/test/java/com/yahoo/config/subscription/ConfigSubscriptionTest.java index 69ec2ff2d7b..c347880f239 100644 --- a/config/src/test/java/com/yahoo/config/subscription/ConfigSubscriptionTest.java +++ b/config/src/test/java/com/yahoo/config/subscription/ConfigSubscriptionTest.java @@ -11,7 +11,6 @@ import com.yahoo.vespa.config.ConfigKey; import com.yahoo.vespa.config.TimingValues; import org.junit.Test; -import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; @@ -78,7 +77,7 @@ public class ConfigSubscriptionTest { @Test public void testSubscribeWithException() { TestConfigSubscriber sub = new TestConfigSubscriber(); - ConfigSourceSet configSourceSet = new ConfigSourceSet(Collections.singletonList("tcp/localhost:99999")); + ConfigSourceSet configSourceSet = new ConfigSourceSet(List.of("tcp/localhost:99999")); try { sub.subscribe(SimpletypesConfig.class, "configid", configSourceSet, new TimingValues().setSubscribeTimeout(100)); fail(); diff --git a/config/src/test/java/com/yahoo/vespa/config/ConfigBuilderMergeTest.java b/config/src/test/java/com/yahoo/vespa/config/ConfigBuilderMergeTest.java index ff2b2bbaf5f..021178d88b1 100644 --- a/config/src/test/java/com/yahoo/vespa/config/ConfigBuilderMergeTest.java +++ b/config/src/test/java/com/yahoo/vespa/config/ConfigBuilderMergeTest.java @@ -8,7 +8,8 @@ import com.yahoo.foo.StructtypesConfig; import com.yahoo.foo.MaptypesConfig; import org.junit.Test; -import java.util.Arrays; + +import java.util.List; import static com.yahoo.foo.MaptypesConfig.Innermap; import static org.hamcrest.CoreMatchers.is; @@ -44,7 +45,7 @@ public class ConfigBuilderMergeTest { StructtypesConfig.Simple.Builder simpleBuilder = new StructtypesConfig.Simple.Builder(); simpleBuilder.name(name); simpleBuilder.gender(StructtypesConfig.Simple.Gender.Enum.valueOf(gender)); - simpleBuilder.emails(Arrays.asList(emails)); + simpleBuilder.emails(List.of(emails)); builder.simple(simpleBuilder); return builder; } diff --git a/config/src/test/java/com/yahoo/vespa/config/RawConfigTest.java b/config/src/test/java/com/yahoo/vespa/config/RawConfigTest.java index 9223c39055b..06e3297d2fe 100644 --- a/config/src/test/java/com/yahoo/vespa/config/RawConfigTest.java +++ b/config/src/test/java/com/yahoo/vespa/config/RawConfigTest.java @@ -8,7 +8,6 @@ import com.yahoo.vespa.config.protocol.VespaVersion; import com.yahoo.vespa.config.util.ConfigUtils; import org.junit.Test; -import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -29,7 +28,7 @@ import static org.junit.Assert.assertNull; public class RawConfigTest { private static final ConfigKey<?> key = new ConfigKey<>("foo", "id", "bar"); - private static final List<String> defContent = Arrays.asList("version=1", "anInt int"); + private static final List<String> defContent = List.of("version=1", "anInt int"); private static final String defMd5 = ConfigUtils.getDefMd5FromRequest("", defContent); private static final PayloadChecksums payloadChecksums = PayloadChecksums.from("012345", ""); private static final Payload payload = Payload.from(new Utf8String("anInt 1"), CompressionInfo.uncompressed()); diff --git a/configdefinitions/src/vespa/stor-filestor.def b/configdefinitions/src/vespa/stor-filestor.def index de67d4336e9..a5d86cc91ba 100644 --- a/configdefinitions/src/vespa/stor-filestor.def +++ b/configdefinitions/src/vespa/stor-filestor.def @@ -29,7 +29,7 @@ response_sequencer_type enum {LATENCY, THROUGHPUT, ADAPTIVE} default=ADAPTIVE re ## Should follow stor-distributormanager:splitsize (16MB). bucket_merge_chunk_size int default=16772216 restart -## Whether or not to use async message handling when scheduling storage messages from FileStorManager. +## Whether to use async message handling when scheduling storage messages from FileStorManager. ## ## When turned on, the calling thread (e.g. FNET network thread when using Storage API RPC) ## gets the next async message to handle (if any) as part of scheduling a storage message. @@ -61,3 +61,10 @@ async_operation_throttler.window_size_backoff double default=0.95 async_operation_throttler.min_window_size int default=20 async_operation_throttler.max_window_size int default=-1 # < 0 implies INT_MAX async_operation_throttler.resize_rate double default=3.0 + +## Maximum number of enqueued put/remove/update operations towards a given bucket +## that can be dispatched asynchronously as a batch under the same write lock. +## This prevents pipeline stalls when many write operations are in-flight to the +## same bucket, as each operation would otherwise have to wait for the completion +## of all prior writes to the bucket. +max_feed_op_batch_size int default=1 diff --git a/configgen/src/main/java/com/yahoo/config/codegen/BuilderGenerator.java b/configgen/src/main/java/com/yahoo/config/codegen/BuilderGenerator.java index a3a5727e30c..fe6e328020f 100644 --- a/configgen/src/main/java/com/yahoo/config/codegen/BuilderGenerator.java +++ b/configgen/src/main/java/com/yahoo/config/codegen/BuilderGenerator.java @@ -99,7 +99,7 @@ public class BuilderGenerator { } String uninitializedList = (scalarsWithoutDefault.size() > 0) - ? "Arrays.asList(\n" + indentCode(INDENTATION, String.join(",\n", scalarsWithoutDefault) + "\n)") + ? "List.of(\n" + indentCode(INDENTATION, String.join(",\n", scalarsWithoutDefault) + "\n)") : ""; return "private Set<String> " + INTERNAL_PREFIX + "uninitialized = new HashSet<String>(" + uninitializedList + ");"; diff --git a/configgen/src/test/resources/allfeatures.reference b/configgen/src/test/resources/allfeatures.reference index b17655e317d..d068853b167 100644 --- a/configgen/src/test/resources/allfeatures.reference +++ b/configgen/src/test/resources/allfeatures.reference @@ -101,7 +101,7 @@ public final class AllfeaturesConfig extends ConfigInstance { } public static final class Builder implements ConfigInstance.Builder { - private Set<String> __uninitialized = new HashSet<String>(Arrays.asList( + private Set<String> __uninitialized = new HashSet<String>(List.of( "boolVal", "intVal", "longVal", @@ -1730,7 +1730,7 @@ public final class AllfeaturesConfig extends ConfigInstance { public final static class MyArray extends InnerNode { public static final class Builder implements ConfigBuilder { - private Set<String> __uninitialized = new HashSet<String>(Arrays.asList( + private Set<String> __uninitialized = new HashSet<String>(List.of( "refVal" )); @@ -2040,7 +2040,7 @@ public final class AllfeaturesConfig extends ConfigInstance { public final static class MyMap extends InnerNode { public static final class Builder implements ConfigBuilder { - private Set<String> __uninitialized = new HashSet<String>(Arrays.asList( + private Set<String> __uninitialized = new HashSet<String>(List.of( "refVal" )); diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/StaticConfigDefinitionRepo.java b/configserver/src/main/java/com/yahoo/vespa/config/server/StaticConfigDefinitionRepo.java index 51918b4902a..bfad5af504c 100644 --- a/configserver/src/main/java/com/yahoo/vespa/config/server/StaticConfigDefinitionRepo.java +++ b/configserver/src/main/java/com/yahoo/vespa/config/server/StaticConfigDefinitionRepo.java @@ -6,7 +6,6 @@ import com.yahoo.config.model.api.ConfigDefinitionRepo; import com.yahoo.vespa.config.ConfigDefinitionKey; import com.yahoo.vespa.config.buildergen.ConfigDefinition; -import java.util.Collections; import java.util.Map; /** @@ -24,7 +23,7 @@ public class StaticConfigDefinitionRepo implements ConfigDefinitionRepo { this.repo = new ConfigDefinitionRepo() { @Override public Map<ConfigDefinitionKey, ConfigDefinition> getConfigDefinitions() { - return Collections.emptyMap(); + return Map.of(); } @Override diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/application/FileDistributionStatus.java b/configserver/src/main/java/com/yahoo/vespa/config/server/application/FileDistributionStatus.java index 3de35a20008..57ecd175435 100644 --- a/configserver/src/main/java/com/yahoo/vespa/config/server/application/FileDistributionStatus.java +++ b/configserver/src/main/java/com/yahoo/vespa/config/server/application/FileDistributionStatus.java @@ -16,7 +16,6 @@ import com.yahoo.vespa.config.server.http.JSONResponse; import java.time.Duration; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -75,7 +74,7 @@ public class FileDistributionStatus extends AbstractComponent { if (request.isError()) { return new HostStatus(hostname, Status.UNKNOWN, - Collections.emptyMap(), + Map.of(), "error: " + request.errorMessage() + "(" + request.errorCode() + ")"); } else { Map<String, Double> fileReferenceStatuses = new HashMap<>(); diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/deploy/ZooKeeperDeployer.java b/configserver/src/main/java/com/yahoo/vespa/config/server/deploy/ZooKeeperDeployer.java index f0228f40ad2..a634519dd0a 100644 --- a/configserver/src/main/java/com/yahoo/vespa/config/server/deploy/ZooKeeperDeployer.java +++ b/configserver/src/main/java/com/yahoo/vespa/config/server/deploy/ZooKeeperDeployer.java @@ -24,7 +24,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; @@ -109,7 +108,7 @@ public class ZooKeeperDeployer { void initialize() { curator.create(sessionPath); - for (String subPath : Arrays.asList(DEFCONFIGS_ZK_SUBPATH, + for (String subPath : List.of(DEFCONFIGS_ZK_SUBPATH, USER_DEFCONFIGS_ZK_SUBPATH, USERAPP_ZK_SUBPATH, ZKApplicationPackage.fileRegistryNode)) { diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/http/HttpConfigRequest.java b/configserver/src/main/java/com/yahoo/vespa/config/server/http/HttpConfigRequest.java index 06e5ded4cdb..c80d034a2f9 100644 --- a/configserver/src/main/java/com/yahoo/vespa/config/server/http/HttpConfigRequest.java +++ b/configserver/src/main/java/com/yahoo/vespa/config/server/http/HttpConfigRequest.java @@ -19,7 +19,7 @@ import com.yahoo.vespa.config.server.http.v2.request.HttpConfigRequests; import com.yahoo.vespa.config.server.http.v2.request.TenantRequest; import com.yahoo.vespa.config.util.ConfigUtils; -import java.util.Collections; +import java.util.List; import java.util.Optional; import java.util.Set; @@ -190,7 +190,7 @@ public class HttpConfigRequest implements GetConfigRequest, TenantRequest { @Override public DefContent getDefContent() { - return DefContent.fromList(Collections.emptyList()); + return DefContent.fromList(List.of()); } @Override diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/RpcServer.java b/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/RpcServer.java index b0ecedd4853..6d671377e63 100644 --- a/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/RpcServer.java +++ b/configserver/src/main/java/com/yahoo/vespa/config/server/rpc/RpcServer.java @@ -48,7 +48,6 @@ import com.yahoo.vespa.filedistribution.FileReferenceDownload; import java.nio.ByteBuffer; import java.time.Duration; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -131,7 +130,7 @@ public class RpcServer implements Runnable, ConfigActivationListener, TenantList this.superModelRequestHandler = superModelRequestHandler; metricUpdaterFactory = metrics; supervisor.setMaxOutputBufferSize(config.maxoutputbuffersize()); - this.metrics = metrics.getOrCreateMetricUpdater(Collections.emptyMap()); + this.metrics = metrics.getOrCreateMetricUpdater(Map.of()); BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(config.maxgetconfigclients()); int rpcWorkerThreads = (config.numRpcThreads() == 0) ? threadsToUse() : config.numRpcThreads(); executorService = new ThreadPoolExecutor(rpcWorkerThreads, rpcWorkerThreads, diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java b/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java index 546277c4aba..ac483ea20c9 100644 --- a/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java +++ b/configserver/src/main/java/com/yahoo/vespa/config/server/session/SessionRepository.java @@ -64,7 +64,6 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -851,7 +850,7 @@ public class SessionRepository { File[] sdFiles = sdDir.listFiles(); if (sdFiles != null) { Files.createDirectories(schemasDir.toPath()); - Arrays.asList(sdFiles).forEach(file -> Exceptions.uncheck( + List.of(sdFiles).forEach(file -> Exceptions.uncheck( () -> Files.move(file.toPath(), schemasDir.toPath().resolve(file.toPath().getFileName()), StandardCopyOption.REPLACE_EXISTING))); diff --git a/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/TenantRepository.java b/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/TenantRepository.java index 8c4445f897c..f9f477c9693 100644 --- a/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/TenantRepository.java +++ b/configserver/src/main/java/com/yahoo/vespa/config/server/tenant/TenantRepository.java @@ -194,7 +194,7 @@ public class TenantRepository { this.configserverConfig = configserverConfig; this.curator = curator; this.metrics = metrics; - metricUpdater = metrics.getOrCreateMetricUpdater(Collections.emptyMap()); + metricUpdater = metrics.getOrCreateMetricUpdater(Map.of()); this.zkCacheExecutor = zkCacheExecutor; this.zkApplicationWatcherExecutor = zkApplicationWatcherExecutor; this.zkSessionWatcherExecutor = zkSessionWatcherExecutor; @@ -312,7 +312,7 @@ public class TenantRepository { } } - if (failed.size() > 0) + if (!failed.isEmpty()) throw new RuntimeException("Could not create all tenants when bootstrapping, failed to create: " + failed); metricUpdater.setTenants(tenants.size()); diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/ConfigServerBootstrapTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/ConfigServerBootstrapTest.java index 801f599c2d8..34900f61463 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/ConfigServerBootstrapTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/ConfigServerBootstrapTest.java @@ -35,7 +35,6 @@ import java.io.IOException; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.BooleanSupplier; @@ -311,7 +310,7 @@ public class ConfigServerBootstrapTest { } private Host createHost(String hostname, String version) { - return new Host(hostname, Collections.emptyList(), Optional.empty(), Optional.of(com.yahoo.component.Version.fromString(version))); + return new Host(hostname, List.of(), Optional.empty(), Optional.of(com.yahoo.component.Version.fromString(version))); } private VipStatus createVipStatus(StateMonitor stateMonitor) { diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/ModelFactoryRegistryTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/ModelFactoryRegistryTest.java index 4d23c4c6ffa..64417536f8b 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/ModelFactoryRegistryTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/ModelFactoryRegistryTest.java @@ -56,7 +56,7 @@ public class ModelFactoryRegistryTest { TestFactory b = new TestFactory(new Version(5, 58, 1)); TestFactory c = new TestFactory(new Version(5, 48, 44)); TestFactory d = new TestFactory(new Version(5, 18, 44)); - ModelFactoryRegistry registry = new ModelFactoryRegistry(Arrays.asList(a, b, c, d)); + ModelFactoryRegistry registry = new ModelFactoryRegistry(List.of(a, b, c, d)); assertEquals(4, registry.getFactories().size()); assertTrue(registry.getFactories().contains(a)); assertTrue(registry.getFactories().contains(b)); @@ -70,23 +70,9 @@ public class ModelFactoryRegistryTest { registry.getFactory(new Version(3, 2, 1)); } - private static class TestFactory implements ModelFactory { + private record TestFactory(Version version) implements ModelFactory { - private final Version version; - - TestFactory(Version version) { - this.version = version; - } - - @Override - public Version version() { - return version; - } - - @Override - public Model createModel(ModelContext modelContext) { - return null; - } + @Override public Model createModel(ModelContext modelContext) { return null; } @Override public ModelCreateResult createAndValidateModel(ModelContext modelContext, ValidationParameters validationParameters) { diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelControllerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelControllerTest.java index af86463bb81..39f1cb70112 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelControllerTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelControllerTest.java @@ -30,8 +30,8 @@ import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; -import java.util.Collections; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -73,7 +73,7 @@ public class SuperModelControllerTest { public void test_unknown_config_definition() { PayloadChecksums payloadChecksums = PayloadChecksums.empty(); Request request = createWithParams(new ConfigKey<>("foo", "id", "bar", null), - DefContent.fromList(Collections.emptyList()), "fromHost", + DefContent.fromList(List.of()), "fromHost", payloadChecksums, 1, 1, Trace.createDummy(), CompressionType.UNCOMPRESSED, Optional.empty()) .getRequest(); diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelRequestHandlerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelRequestHandlerTest.java index 28c95ba33c8..74b08b83791 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelRequestHandlerTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelRequestHandlerTest.java @@ -21,7 +21,6 @@ import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -88,7 +87,7 @@ public class SuperModelRequestHandlerTest { assertTrue(controller.getHandler().getSuperModel().applicationModels().keySet().containsAll(List.of(foo, bar, baz))); controller.removeApplication(bar); assertEquals(2, controller.getHandler().getSuperModel().applicationModels().size()); - assertEquals(Arrays.asList(foo, baz), new ArrayList<>(controller.getHandler().getSuperModel().applicationModels().keySet())); + assertEquals(List.of(foo, baz), new ArrayList<>(controller.getHandler().getSuperModel().applicationModels().keySet())); assertEquals(gen + 5, controller.getHandler().getGeneration()); } diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/application/ApplicationMapperTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/application/ApplicationMapperTest.java index ddcee892594..28090b42e75 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/application/ApplicationMapperTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/application/ApplicationMapperTest.java @@ -3,7 +3,6 @@ package com.yahoo.vespa.config.server.application; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -52,7 +51,7 @@ public class ApplicationMapperTest { @Test (expected = VersionDoesNotExistException.class) public void testGetForVersionThrows() { - applicationMapper.register(appId, ApplicationVersions.fromList(Arrays.asList(applications.get(0), applications.get(2)))); + applicationMapper.register(appId, ApplicationVersions.fromList(List.of(applications.get(0), applications.get(2)))); applicationMapper.getForVersion(appId, Optional.of(vespaVersions.get(1)), Instant.now()); } diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/application/ApplicationVersionsTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/application/ApplicationVersionsTest.java index 9345b45bab4..23a425b99e2 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/application/ApplicationVersionsTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/application/ApplicationVersionsTest.java @@ -3,7 +3,6 @@ package com.yahoo.vespa.config.server.application; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -46,7 +45,7 @@ public class ApplicationVersionsTest { @Test (expected = VersionDoesNotExistException.class) public void testGetForVersionOrLatestThrows() { - applicationVersions = ApplicationVersions.fromList(Arrays.asList(applications.get(0), applications.get(2))); + applicationVersions = ApplicationVersions.fromList(List.of(applications.get(0), applications.get(2))); applicationVersions.getForVersionOrLatest(Optional.of(vespaVersions.get(1)), Instant.now()); } diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/application/CompressedApplicationInputStreamTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/application/CompressedApplicationInputStreamTest.java index 93c41f1b087..b735c69f247 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/application/CompressedApplicationInputStreamTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/application/CompressedApplicationInputStreamTest.java @@ -18,7 +18,6 @@ import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.zip.GZIPOutputStream; @@ -104,7 +103,7 @@ public class CompressedApplicationInputStreamTest { try (CompressedApplicationInputStream unpacked = streamFromTarGz(gzFile)) { outApp = unpacked.decompress(); } - List<File> files = Arrays.asList(Objects.requireNonNull(outApp.listFiles())); + List<File> files = List.of(Objects.requireNonNull(outApp.listFiles())); assertEquals(5, files.size()); assertTrue(files.contains(new File(outApp, "services.xml"))); assertTrue(files.contains(new File(outApp, "hosts.xml"))); @@ -121,13 +120,13 @@ public class CompressedApplicationInputStreamTest { assertEquals(1, ext.listFiles().length); assertEquals(new File(ext, "foo").getAbsolutePath(), ext.listFiles()[0].getAbsolutePath()); - files = Arrays.asList(ext.listFiles()); + files = List.of(ext.listFiles()); File foo = files.get(files.indexOf(new File(ext, "foo"))); assertTrue(foo.isDirectory()); assertEquals(1, foo.listFiles().length); assertEquals(new File(foo, "bar").getAbsolutePath(), foo.listFiles()[0].getAbsolutePath()); - files = Arrays.asList(foo.listFiles()); + files = List.of(foo.listFiles()); File bar = files.get(files.indexOf(new File(foo, "bar"))); assertTrue(bar.isDirectory()); assertEquals(1, bar.listFiles().length); diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/application/ConfigConvergenceCheckerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/application/ConfigConvergenceCheckerTest.java index 0fe39fd0224..a5ce29b6494 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/application/ConfigConvergenceCheckerTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/application/ConfigConvergenceCheckerTest.java @@ -17,7 +17,6 @@ import org.junit.rules.TemporaryFolder; import java.net.URI; import java.time.Duration; -import java.util.Arrays; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; @@ -101,7 +100,7 @@ public class ConfigConvergenceCheckerTest { } { // Model with two hosts on different generations - MockModel model = new MockModel(Arrays.asList( + MockModel model = new MockModel(List.of( MockModel.createContainerHost(service.getHost(), service.getPort()), MockModel.createContainerHost(service2.getHost(), service2.getPort())) ); diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/application/FileDistributionStatusTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/application/FileDistributionStatusTest.java index 4a2f422252b..30e1373b7f6 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/application/FileDistributionStatusTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/application/FileDistributionStatusTest.java @@ -17,7 +17,6 @@ import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.time.Duration; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -119,7 +118,7 @@ public class FileDistributionStatusTest { fileReferenceStatuses2.put("1234", 1.0); HostStatus localhost2 = statusFinished("localhost2", Status.FINISHED, fileReferenceStatuses2); - FileDistributionStatus status = new MockStatus(new HashSet<>(Arrays.asList(localhost, localhost2))); + FileDistributionStatus status = new MockStatus(new HashSet<>(List.of(localhost, localhost2))); application = createApplication("localhost", "localhost2"); HttpResponse response = getStatus(status, application); assertResponse(200, @@ -156,7 +155,7 @@ public class FileDistributionStatusTest { } private Application createApplication(String... hostname) { - return createApplication(Arrays.asList(hostname)); + return createApplication(List.of(hostname)); } private Application createApplication(List<String> hostnames) { diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/application/HttpProxyTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/application/HttpProxyTest.java index 1a6669e93b2..f57148dd8d0 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/application/HttpProxyTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/application/HttpProxyTest.java @@ -21,8 +21,9 @@ import org.mockito.ArgumentCaptor; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; -import java.util.Arrays; import java.util.Collections; +import java.util.List; +import java.util.Set; import static com.yahoo.config.model.api.container.ContainerServiceType.CLUSTERCONTROLLER_CONTAINER; import static com.yahoo.vespa.config.server.application.MockModel.createServiceInfo; @@ -119,9 +120,9 @@ public class HttpProxyTest { "state http external query"); ServiceInfo serviceNoStatePort = createServiceInfo(hostname, "storagenode", "storagenode", ClusterSpec.Type.content, 1234, "rpc"); - HostInfo hostInfo = new HostInfo(hostname, Arrays.asList(container, serviceNoStatePort)); + HostInfo hostInfo = new HostInfo(hostname, List.of(container, serviceNoStatePort)); - return new MockModel(Collections.singleton(hostInfo)); + return new MockModel(Set.of(hostInfo)); } } diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/application/MockModel.java b/configserver/src/test/java/com/yahoo/vespa/config/server/application/MockModel.java index c18dad1ea67..4ba507bf5d9 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/application/MockModel.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/application/MockModel.java @@ -40,7 +40,7 @@ public class MockModel implements Model { ClusterSpec.Type.container, statePort, "state"); ServiceInfo serviceNoStatePort = createServiceInfo(hostname, "logserver", "logserver", ClusterSpec.Type.admin, 1234, "logtp"); - return new HostInfo(hostname, Arrays.asList(container, serviceNoStatePort)); + return new HostInfo(hostname, List.of(container, serviceNoStatePort)); } static MockModel createConfigProxies(List<String> hostnames, int rpcPort) { @@ -48,7 +48,7 @@ public class MockModel implements Model { hostnames.forEach(hostname -> { ServiceInfo configProxy = createServiceInfo(hostname, "configproxy", "configproxy", ClusterSpec.Type.admin, rpcPort, "rpc"); - hostInfos.add(new HostInfo(hostname, Collections.singletonList(configProxy))); + hostInfos.add(new HostInfo(hostname, List.of(configProxy))); }); return new MockModel(hostInfos); } diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/application/TenantApplicationsTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/application/TenantApplicationsTest.java index 14d49f9d9d6..a613dc91211 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/application/TenantApplicationsTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/application/TenantApplicationsTest.java @@ -42,7 +42,6 @@ import java.io.File; import java.io.IOException; import java.time.Clock; import java.time.Duration; -import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; @@ -306,7 +305,7 @@ public class TenantApplicationsTest { } private ModelFactoryRegistry createRegistry() { - return new ModelFactoryRegistry(Arrays.asList(new TestModelFactory(vespaVersion), + return new ModelFactoryRegistry(List.of(new TestModelFactory(vespaVersion), new TestModelFactory(new Version(3, 2, 1)))); } diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/DeployTester.java b/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/DeployTester.java index 67a1a335067..68add64ddd9 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/DeployTester.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/DeployTester.java @@ -53,7 +53,6 @@ import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -219,7 +218,7 @@ public class DeployTester { public ModelCreateResult createAndValidateModel(ModelContext modelContext, ValidationParameters validationParameters) { if ( ! validationParameters.ignoreValidationErrors()) throw new IllegalArgumentException("Model building fails"); - return new ModelCreateResult(createModel(modelContext), Collections.emptyList()); + return new ModelCreateResult(createModel(modelContext), List.of()); } } diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/HostedDeployTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/HostedDeployTest.java index 838b1b6b209..512f4dff6b7 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/HostedDeployTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/deploy/HostedDeployTest.java @@ -47,7 +47,6 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -581,7 +580,7 @@ public class HostedDeployTest { } private Host createHost(String hostname, String version) { - return new Host(hostname, Collections.emptyList(), Optional.empty(), Optional.ofNullable(version).map(Version::fromString)); + return new Host(hostname, List.of(), Optional.empty(), Optional.ofNullable(version).map(Version::fromString)); } private DeployTester createTester(List<Host> hosts, List<ModelFactory> modelFactories, Zone zone) { diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/http/ContentHandlerTestBase.java b/configserver/src/test/java/com/yahoo/vespa/config/server/http/ContentHandlerTestBase.java index 13192499603..ee694c984fb 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/http/ContentHandlerTestBase.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/http/ContentHandlerTestBase.java @@ -8,8 +8,8 @@ import com.yahoo.jdisc.http.HttpRequest; import org.junit.Test; import java.io.IOException; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import static com.yahoo.jdisc.Response.Status.BAD_REQUEST; import static com.yahoo.jdisc.Response.Status.NOT_FOUND; @@ -92,11 +92,7 @@ public abstract class ContentHandlerTestBase extends SessionHandlerTest { protected abstract HttpResponse doRequest(HttpRequest.Method method, String path); private String generateResultArray(String... files) { - Collection<String> output = Collections2.transform(Arrays.asList(files), input -> "\"" + baseUrl + input + "\""); - StringBuilder sb = new StringBuilder(); - sb.append("["); - sb.append(Joiner.on(",").join(output)); - sb.append("]"); - return sb.toString(); + Collection<String> output = Collections2.transform(List.of(files), input -> "\"" + baseUrl + input + "\""); + return "[" + Joiner.on(",").join(output) + "]"; } } diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/http/HttpGetConfigHandlerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/http/HttpGetConfigHandlerTest.java index 34045cf3804..452ee53c439 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/http/HttpGetConfigHandlerTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/http/HttpGetConfigHandlerTest.java @@ -17,7 +17,7 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; -import java.util.Collections; +import java.util.Map; import static com.yahoo.jdisc.http.HttpRequest.Method.GET; import static com.yahoo.jdisc.http.HttpResponse.Status.BAD_REQUEST; @@ -90,7 +90,7 @@ public class HttpGetConfigHandlerTest { @Test public void require_that_nocache_property_works() throws IOException { - HttpRequest request = HttpRequest.createTestRequest(configUri, GET, null, Collections.singletonMap("nocache", "true")); + HttpRequest request = HttpRequest.createTestRequest(configUri, GET, null, Map.of("nocache", "true")); HttpResponse response = handler.handle(request); String renderedString = SessionHandlerTest.getRenderedString(response); assertTrue(renderedString, renderedString.startsWith(expected)); diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/http/HttpHandlerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/http/HttpHandlerTest.java index a7f86133fce..b58bca074b8 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/http/HttpHandlerTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/http/HttpHandlerTest.java @@ -11,7 +11,7 @@ import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.time.Duration; -import java.util.Collections; +import java.util.Map; import static org.junit.Assert.assertEquals; @@ -39,7 +39,7 @@ public class HttpHandlerTest { HttpRequest.createTestRequest("foo", com.yahoo.jdisc.http.HttpRequest.Method.GET, null, - Collections.singletonMap("timeout", "1.5")), Duration.ofSeconds(5)).toMillis()); + Map.of("timeout", "1.5")), Duration.ofSeconds(5)).toMillis()); } private static class HttpTestHandler extends HttpHandler { diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/http/v2/HttpGetConfigHandlerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/http/v2/HttpGetConfigHandlerTest.java index 6f2c7366b62..4c140159e12 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/http/v2/HttpGetConfigHandlerTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/http/v2/HttpGetConfigHandlerTest.java @@ -24,7 +24,6 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; -import java.util.Collections; import java.util.Map; import static com.yahoo.jdisc.Response.Status.BAD_REQUEST; @@ -126,7 +125,7 @@ public class HttpGetConfigHandlerTest { @Test public void require_that_nocache_property_works() throws IOException { - HttpRequest request = HttpRequest.createTestRequest(configUri, GET, null, Collections.singletonMap("nocache", "true")); + HttpRequest request = HttpRequest.createTestRequest(configUri, GET, null, Map.of("nocache", "true")); HttpResponse response = handler.handle(request); String renderedString = SessionHandlerTest.getRenderedString(response); assertTrue(renderedString, renderedString.startsWith(expected)); diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/http/v2/SessionCreateHandlerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/http/v2/SessionCreateHandlerTest.java index b8c9a2f8fb8..4fb514bde17 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/http/v2/SessionCreateHandlerTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/http/v2/SessionCreateHandlerTest.java @@ -30,7 +30,6 @@ import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -93,7 +92,7 @@ public class SessionCreateHandlerTest extends SessionHandlerTest { @Ignore @Test public void require_that_from_parameter_cannot_be_set_if_data_in_request() throws IOException { - HttpRequest request = post(Collections.singletonMap("from", "active")); + HttpRequest request = post(Map.of("from", "active")); HttpResponse response = createHandler().handle(request); assertHttpStatusCodeErrorCodeAndMessage(response, BAD_REQUEST, HttpErrorResponse.ErrorCode.BAD_REQUEST, "Parameter 'from' is illegal for POST"); } @@ -114,14 +113,14 @@ public class SessionCreateHandlerTest extends SessionHandlerTest { private void assertIllegalFromParameter(String fromValue) throws IOException { File outFile = CompressedApplicationInputStreamTest.createTarFile(temporaryFolder.getRoot().toPath()); - HttpRequest request = post(outFile, postHeaders, Collections.singletonMap("from", fromValue)); + HttpRequest request = post(outFile, postHeaders, Map.of("from", fromValue)); assertHttpStatusCodeErrorCodeAndMessage(createHandler().handle(request), BAD_REQUEST, HttpErrorResponse.ErrorCode.BAD_REQUEST, "Parameter 'from' has illegal value '" + fromValue + "'"); } @Test public void require_that_prepare_url_is_returned_on_success() throws IOException { File outFile = CompressedApplicationInputStreamTest.createTarFile(temporaryFolder.getRoot().toPath()); - Map<String, String> parameters = Collections.singletonMap("name", "foo"); + Map<String, String> parameters = Map.of("name", "foo"); HttpResponse response = createHandler().handle(post(outFile, postHeaders, parameters)); assertNotNull(response); assertEquals(OK, response.getStatus()); @@ -160,7 +159,7 @@ public class SessionCreateHandlerTest extends SessionHandlerTest { @Test public void require_that_application_urls_can_be_given_as_from_parameter() throws Exception { ApplicationId applicationId = ApplicationId.from(tenant.value(), "foo", "quux"); - HttpRequest request = post(Collections.singletonMap( + HttpRequest request = post(Map.of( "from", "http://myhost:40555/application/v2/tenant/" + tenant + "/application/foo/environment/test/region/baz/instance/quux")); assertEquals(applicationId, SessionCreateHandler.getFromApplicationId(request)); @@ -180,7 +179,7 @@ public class SessionCreateHandlerTest extends SessionHandlerTest { public void require_that_content_type_is_parsed_correctly() throws FileNotFoundException { HttpRequest request = post(new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8)), Map.of("Content-Type", "multipart/form-data; charset=ISO-8859-1; boundary=g5gJAzUWl_t6"), - Collections.emptyMap()); + Map.of()); // Valid header should validate ok SessionCreateHandler.validateDataAndHeader(request, List.of(ContentType.MULTIPART_FORM_DATA.getMimeType())); diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/DelayedConfigResponseTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/DelayedConfigResponseTest.java index 2ca0155ac6f..0773ace0051 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/DelayedConfigResponseTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/rpc/DelayedConfigResponseTest.java @@ -17,7 +17,6 @@ import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.time.Duration; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -80,7 +79,7 @@ public class DelayedConfigResponseTest { private JRTServerConfigRequest createRequest(String configName, String configId, long generation, long timeout, String namespace) { Request request = createWithParams(new ConfigKey<>(configName, configId, namespace, null), - DefContent.fromList(Collections.emptyList()), "fromHost", + DefContent.fromList(List.of()), "fromHost", PayloadChecksums.empty(), generation, timeout, Trace.createDummy(), CompressionType.UNCOMPRESSED, Optional.empty()) .getRequest(); diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/session/SessionPreparerTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/session/SessionPreparerTest.java index f736eab0576..0ec651468cd 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/session/SessionPreparerTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/session/SessionPreparerTest.java @@ -61,7 +61,6 @@ import java.security.KeyPair; import java.security.cert.X509Certificate; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -192,7 +191,7 @@ public class SessionPreparerTest { public void require_exception_for_overlapping_host() throws IOException { FilesApplicationPackage app = getApplicationPackage(testApp); HostRegistry hostValidator = new HostRegistry(); - hostValidator.update(applicationId("foo"), Collections.singletonList("mytesthost")); + hostValidator.update(applicationId("foo"), List.of("mytesthost")); preparer.prepare(hostValidator, new BaseDeployLogger(), new PrepareParams.Builder().applicationId(applicationId("default")).build(), Optional.empty(), Instant.now(), app.getAppDir(), app, createSessionZooKeeperClient()); } @@ -206,7 +205,7 @@ public class SessionPreparerTest { FilesApplicationPackage app = getApplicationPackage(testApp); HostRegistry hostValidator = new HostRegistry(); ApplicationId applicationId = applicationId(); - hostValidator.update(applicationId, Collections.singletonList("mytesthost")); + hostValidator.update(applicationId, List.of("mytesthost")); preparer.prepare(hostValidator, logger, new PrepareParams.Builder().applicationId(applicationId).build(), Optional.empty(), Instant.now(), app.getAppDir(), app, createSessionZooKeeperClient()); diff --git a/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TenantRepositoryTest.java b/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TenantRepositoryTest.java index 515ecf0005e..9ef1f42f247 100644 --- a/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TenantRepositoryTest.java +++ b/configserver/src/test/java/com/yahoo/vespa/config/server/tenant/TenantRepositoryTest.java @@ -46,7 +46,6 @@ import org.mockito.Mock; import org.xml.sax.SAXException; import java.io.IOException; import java.time.Clock; -import java.util.Arrays; import java.util.List; import java.util.Set; @@ -174,7 +173,7 @@ public class TenantRepositoryTest { @Test public void testTenantWatching() throws Exception { TenantName newTenant = TenantName.from("newTenant"); - List<TenantName> expectedTenants = Arrays.asList(TenantName.defaultName(), newTenant); + List<TenantName> expectedTenants = List.of(TenantName.defaultName(), newTenant); try { tenantRepository.addTenant(newTenant); // Poll for the watcher to pick up the tenant from zk, and add it diff --git a/container-core/src/main/java/com/yahoo/component/chain/ChainedComponent.java b/container-core/src/main/java/com/yahoo/component/chain/ChainedComponent.java index 12a833881f7..2c2ee5226a6 100644 --- a/container-core/src/main/java/com/yahoo/component/chain/ChainedComponent.java +++ b/container-core/src/main/java/com/yahoo/component/chain/ChainedComponent.java @@ -11,9 +11,7 @@ import com.yahoo.component.chain.dependencies.Provides; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.List; /** @@ -70,7 +68,7 @@ public abstract class ChainedComponent extends AbstractComponent { // TODO: move to vespajlib. private static List<String> allOf(List<String> symbols, String... otherSymbols) { List<String> result = new ArrayList<>(symbols); - result.addAll(Arrays.asList(otherSymbols)); + result.addAll(List.of(otherSymbols)); return result; } @@ -88,9 +86,9 @@ public abstract class ChainedComponent extends AbstractComponent { Annotation annotation = component.getClass().getAnnotation(annotationClass); if (annotation != null) { Object values = annotationClass.getMethod("value").invoke(annotation); - return Arrays.asList((String[])values); + return List.of((String[])values); } - return Collections.emptyList(); + return List.of(); } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new RuntimeException(e); diff --git a/container-core/src/main/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilder.java b/container-core/src/main/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilder.java index fef23f3cc27..c0bc01be27c 100644 --- a/container-core/src/main/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilder.java +++ b/container-core/src/main/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilder.java @@ -3,7 +3,6 @@ package com.yahoo.component.chain.dependencies.ordering; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; @@ -50,7 +49,7 @@ public class ChainBuilder<T extends ChainedComponent> { } private Set<String> set(String... s) { - return new HashSet<>(Arrays.asList(s)); + return new HashSet<>(List.of(s)); } public PhaseNameProvider addPhase(Phase phase) { diff --git a/container-core/src/main/java/com/yahoo/container/bundle/MockBundle.java b/container-core/src/main/java/com/yahoo/container/bundle/MockBundle.java index da5b040e296..b00455b1e2a 100644 --- a/container-core/src/main/java/com/yahoo/container/bundle/MockBundle.java +++ b/container-core/src/main/java/com/yahoo/container/bundle/MockBundle.java @@ -157,7 +157,7 @@ public class MockBundle implements Bundle, BundleWiring { @Override public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) { - return Collections.emptyMap(); + return Map.of(); } @SuppressWarnings("unchecked") @@ -239,7 +239,7 @@ public class MockBundle implements Bundle, BundleWiring { @Override public Collection<String> listResources(String p1, String p2, int p3) { - return Collections.emptyList(); + return List.of(); } @Override diff --git a/container-core/src/main/java/com/yahoo/container/di/ConfigRetriever.java b/container-core/src/main/java/com/yahoo/container/di/ConfigRetriever.java index fcccc02d143..5a04bd8eae1 100644 --- a/container-core/src/main/java/com/yahoo/container/di/ConfigRetriever.java +++ b/container-core/src/main/java/com/yahoo/container/di/ConfigRetriever.java @@ -8,7 +8,6 @@ import com.yahoo.container.di.config.Subscriber; import com.yahoo.container.di.config.SubscriberFactory; import com.yahoo.vespa.config.ConfigKey; -import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Optional; @@ -135,7 +134,7 @@ public final class ConfigRetriever { private void resetComponentSubscriberIfBootstrap(ConfigSnapshot configSnapshot) { if (configSnapshot instanceof BootstrapConfigs) { - setupComponentSubscriber(Collections.emptySet()); + setupComponentSubscriber(Set.of()); } } diff --git a/container-core/src/main/java/com/yahoo/container/di/Osgi.java b/container-core/src/main/java/com/yahoo/container/di/Osgi.java index 0ff640031fc..7bab8605a3e 100644 --- a/container-core/src/main/java/com/yahoo/container/di/Osgi.java +++ b/container-core/src/main/java/com/yahoo/container/di/Osgi.java @@ -10,8 +10,6 @@ import org.osgi.framework.Bundle; import java.util.Collection; import java.util.Set; -import static java.util.Collections.emptySet; - /** * This interface has default implementations of all methods, to allow using it * for testing, instead of mocking or a test implementation. @@ -49,7 +47,7 @@ public interface Osgi { * @return The set of bundles that are no longer needed by the new or latest good generation. */ default Set<Bundle> completeBundleGeneration(GenerationStatus status) { - return emptySet(); + return Set.of(); } default Class<?> resolveClass(BundleInstantiationSpecification spec) { diff --git a/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentGraph.java b/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentGraph.java index 98b4d0f4d63..5db57250bdf 100644 --- a/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentGraph.java +++ b/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentGraph.java @@ -23,7 +23,6 @@ import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -369,7 +368,7 @@ public class ComponentGraph { public static boolean isBindingAnnotation(Annotation annotation) { LinkedList<Class<?>> queue = new LinkedList<>(); queue.add(annotation.getClass()); - queue.addAll(Arrays.asList(annotation.getClass().getInterfaces())); + queue.addAll(List.of(annotation.getClass().getInterfaces())); while (!queue.isEmpty()) { Class<?> clazz = queue.removeFirst(); diff --git a/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentNode.java b/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentNode.java index 4500a5636f4..dcc024ef2b1 100644 --- a/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentNode.java +++ b/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentNode.java @@ -199,7 +199,7 @@ public class ComponentNode extends Node { @Override public boolean equals(Object other) { if (other instanceof ComponentNode that) { - return super.equals(that) && equalEdges(Arrays.asList(this.arguments), Arrays.asList(that.arguments)) && this.usedConfigs().equals(that.usedConfigs()); + return super.equals(that) && equalEdges(List.of(this.arguments), List.of(that.arguments)) && this.usedConfigs().equals(that.usedConfigs()); } else { return false; } @@ -225,7 +225,7 @@ public class ComponentNode extends Node { List<Pair<Type, List<Annotation>>> ret = new ArrayList<>(); for (int i = 0; i < types.length; i++) { - ret.add(new Pair<>(types[i], Arrays.asList(annotations[i]))); + ret.add(new Pair<>(types[i], List.of(annotations[i]))); } return ret; } diff --git a/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentRegistryNode.java b/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentRegistryNode.java index ca10072c6c9..8b5fb128e2b 100644 --- a/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentRegistryNode.java +++ b/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/ComponentRegistryNode.java @@ -8,10 +8,8 @@ import com.yahoo.component.provider.ComponentRegistry; import com.yahoo.config.ConfigInstance; import com.yahoo.vespa.config.ConfigKey; -import java.util.Collections; import java.util.List; import java.util.Set; -import java.util.stream.Collectors; /** * @author Tony Vaagenes @@ -20,7 +18,7 @@ import java.util.stream.Collectors; */ public class ComponentRegistryNode extends Node { - private static ComponentId componentRegistryNamespace = ComponentId.fromString("ComponentRegistry"); + private static final ComponentId componentRegistryNamespace = ComponentId.fromString("ComponentRegistry"); private final Class<?> componentClass; @@ -63,7 +61,7 @@ public class ComponentRegistryNode extends Node { @Override public Set<ConfigKey<ConfigInstance>> configKeys() { - return Collections.emptySet(); + return Set.of(); } @Override @@ -76,8 +74,7 @@ public class ComponentRegistryNode extends Node { @Override public boolean equals(Object other) { - if (other instanceof ComponentRegistryNode) { - ComponentRegistryNode that = (ComponentRegistryNode) other; + if (other instanceof ComponentRegistryNode that) { return this.componentId().equals(that.componentId()) && this.instanceType().equals(that.instanceType()) && equalNodeEdges(this.usedComponents(), that.usedComponents()); } else { diff --git a/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/GuiceNode.java b/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/GuiceNode.java index 936eadb0b3c..8e6a39a4921 100644 --- a/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/GuiceNode.java +++ b/container-core/src/main/java/com/yahoo/container/di/componentgraph/core/GuiceNode.java @@ -7,7 +7,6 @@ import com.yahoo.config.ConfigInstance; import com.yahoo.vespa.config.ConfigKey; import java.lang.annotation.Annotation; -import java.util.Collections; import java.util.List; import java.util.Set; @@ -24,8 +23,7 @@ public final class GuiceNode extends Node { private final Object myInstance; private final Annotation annotation; - public GuiceNode(Object myInstance, - Annotation annotation) { + public GuiceNode(Object myInstance, Annotation annotation) { super(componentId(myInstance)); this.myInstance = myInstance; this.annotation = annotation; @@ -33,7 +31,7 @@ public final class GuiceNode extends Node { @Override public Set<ConfigKey<ConfigInstance>> configKeys() { - return Collections.emptySet(); + return Set.of(); } @Override @@ -54,7 +52,7 @@ public final class GuiceNode extends Node { @Override public List<Node> usedComponents() { - return Collections.emptyList(); + return List.of(); } @Override diff --git a/container-core/src/main/java/com/yahoo/container/di/componentgraph/cycle/CycleFinder.java b/container-core/src/main/java/com/yahoo/container/di/componentgraph/cycle/CycleFinder.java index f8fa0756cb3..6364eab6d42 100644 --- a/container-core/src/main/java/com/yahoo/container/di/componentgraph/cycle/CycleFinder.java +++ b/container-core/src/main/java/com/yahoo/container/di/componentgraph/cycle/CycleFinder.java @@ -6,13 +6,11 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; -import java.util.stream.Collectors; import static com.yahoo.container.di.componentgraph.cycle.CycleFinder.State.BLACK; import static com.yahoo.container.di.componentgraph.cycle.CycleFinder.State.GRAY; import static com.yahoo.container.di.componentgraph.cycle.CycleFinder.State.WHITE; import static java.util.logging.Level.FINE; -import static java.util.Collections.singletonList; /** @@ -55,7 +53,7 @@ public class CycleFinder<T> { resetState(); for (T vertex : graph.getVertices()) { if (colors.get(vertex) == WHITE) { - if (visitDepthFirst(vertex, new ArrayList<>(singletonList(vertex)))) { + if (visitDepthFirst(vertex, new ArrayList<>(List.of(vertex)))) { if (cycle == null) throw new IllegalStateException("Null cycle - this should never happen"); if (cycle.isEmpty()) throw new IllegalStateException("Empty cycle - this should never happen"); log.log(FINE, () -> "Cycle detected: " + cycle); diff --git a/container-core/src/main/java/com/yahoo/container/http/filter/FilterChainRepository.java b/container-core/src/main/java/com/yahoo/container/http/filter/FilterChainRepository.java index 020022dc9fd..10f8400fa37 100644 --- a/container-core/src/main/java/com/yahoo/container/http/filter/FilterChainRepository.java +++ b/container-core/src/main/java/com/yahoo/container/http/filter/FilterChainRepository.java @@ -22,12 +22,11 @@ import com.yahoo.jdisc.http.filter.chain.ResponseFilterChain; import com.yahoo.processing.execution.chain.ChainRegistry; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.logging.Logger; -import static java.util.Collections.emptyList; +import static java.util.List.of; import static java.util.stream.Collectors.toSet; /** @@ -158,7 +157,7 @@ public class FilterChainRepository extends AbstractComponent { } private static Object wrapIfSecurityFilter(Object filter) { - if (isSecurityFilter(filter)) return createSecurityChain(Collections.singletonList(filter)); + if (isSecurityFilter(filter)) return createSecurityChain(List.of(filter)); return filter; } diff --git a/container-core/src/main/java/com/yahoo/container/jdisc/HttpRequest.java b/container-core/src/main/java/com/yahoo/container/jdisc/HttpRequest.java index 1c325654f2e..71449d6edae 100644 --- a/container-core/src/main/java/com/yahoo/container/jdisc/HttpRequest.java +++ b/container-core/src/main/java/com/yahoo/container/jdisc/HttpRequest.java @@ -412,7 +412,7 @@ public class HttpRequest { Map<String, String> mask; Map<String, String> view; - mask = Objects.requireNonNullElse(parameterMask, Collections.emptyMap()); + mask = Objects.requireNonNullElse(parameterMask, Map.of()); view = new HashMap<>(parameters.size() + mask.size()); for (Map.Entry<String, List<String>> parameter : parameters.entrySet()) { if (existsAsOriginalParameter(parameter.getValue())) { diff --git a/container-core/src/main/java/com/yahoo/container/jdisc/state/MetricsPacketsHandler.java b/container-core/src/main/java/com/yahoo/container/jdisc/state/MetricsPacketsHandler.java index 165330662a9..894a231f9be 100644 --- a/container-core/src/main/java/com/yahoo/container/jdisc/state/MetricsPacketsHandler.java +++ b/container-core/src/main/java/com/yahoo/container/jdisc/state/MetricsPacketsHandler.java @@ -25,7 +25,6 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -91,7 +90,7 @@ public class MetricsPacketsHandler extends AbstractRequestHandler { @Override protected Iterable<ByteBuffer> responseContent() { - return Collections.singleton(ByteBuffer.wrap(buildMetricOutput(request.getUri().getQuery()))); + return Set.of(ByteBuffer.wrap(buildMetricOutput(request.getUri().getQuery()))); } }.dispatch(handler); @@ -160,7 +159,7 @@ public class MetricsPacketsHandler extends AbstractRequestHandler { } private List<JsonNode> getPacketsForSnapshot(MetricSnapshot metricSnapshot, String application, long timestamp) { - if (metricSnapshot == null) return Collections.emptyList(); + if (metricSnapshot == null) return List.of(); List<JsonNode> packets = new ArrayList<>(); @@ -178,9 +177,9 @@ public class MetricsPacketsHandler extends AbstractRequestHandler { } private List<JsonNode> getPacketsForSnapshot(MetricSnapshot metricSnapshot, String metricSetId, String application, long timestamp) { - if (metricSnapshot == null) return Collections.emptyList(); + if (metricSnapshot == null) return List.of(); if (metricSetId == null) return getPacketsForSnapshot(metricSnapshot, application, timestamp); - Set<String> configuredMetrics = metricSets.getOrDefault(metricSetId, Collections.emptySet()); + Set<String> configuredMetrics = metricSets.getOrDefault(metricSetId, Set.of()); List<JsonNode> packets = new ArrayList<>(); for (Map.Entry<MetricDimensions, MetricSet> snapshotEntry : metricSnapshot) { diff --git a/container-core/src/main/java/com/yahoo/container/jdisc/state/StateHandler.java b/container-core/src/main/java/com/yahoo/container/jdisc/state/StateHandler.java index ebd5c38e3a3..81ec0919441 100644 --- a/container-core/src/main/java/com/yahoo/container/jdisc/state/StateHandler.java +++ b/container-core/src/main/java/com/yahoo/container/jdisc/state/StateHandler.java @@ -31,7 +31,6 @@ import java.io.PrintStream; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -373,7 +372,7 @@ public class StateHandler extends AbstractRequestHandler implements CapabilityRe private boolean isPrometheusRequest(String query) { if (query == null) return false; - return Arrays.asList(query.split("&")).contains("format=prometheus"); + return List.of(query.split("&")).contains("format=prometheus"); } private String prometheusSanitizedName(String name) { diff --git a/container-core/src/main/java/com/yahoo/container/jdisc/state/StateMetricContext.java b/container-core/src/main/java/com/yahoo/container/jdisc/state/StateMetricContext.java index 4cb19653848..6d6635ecc94 100644 --- a/container-core/src/main/java/com/yahoo/container/jdisc/state/StateMetricContext.java +++ b/container-core/src/main/java/com/yahoo/container/jdisc/state/StateMetricContext.java @@ -3,10 +3,11 @@ package com.yahoo.container.jdisc.state; import com.yahoo.jdisc.Metric; -import java.util.Collections; -import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.Objects; + +import static java.util.stream.Collectors.toUnmodifiableMap; /** * A context implementation whose identity is the key and values such that this can be used as @@ -41,16 +42,10 @@ public final class StateMetricContext implements MetricDimensions, Metric.Contex } public static StateMetricContext newInstance(Map<String, ?> properties) { - Map<String, String> data; - if (properties != null) { - data = new HashMap<>(properties.size()); - for (Map.Entry<String, ?> entry : properties.entrySet()) { - data.put(entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : null); - } - data = Collections.unmodifiableMap(data); - } else { - data = Collections.emptyMap(); - } + Map<String, String> data = (properties != null) + ? properties.entrySet().stream().collect( + toUnmodifiableMap(Map.Entry::getKey, e -> Objects.requireNonNullElse(e.getValue(), "").toString())) + : Map.of(); return new StateMetricContext(data); } diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/CookieHelper.java b/container-core/src/main/java/com/yahoo/jdisc/http/CookieHelper.java index e3c2d20ba51..1c9e6572d63 100644 --- a/container-core/src/main/java/com/yahoo/jdisc/http/CookieHelper.java +++ b/container-core/src/main/java/com/yahoo/jdisc/http/CookieHelper.java @@ -3,8 +3,6 @@ package com.yahoo.jdisc.http; import com.yahoo.jdisc.HeaderFields; -import java.util.Arrays; -import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -20,7 +18,7 @@ public class CookieHelper { public static List<Cookie> decodeSetCookieHeader(HeaderFields headers) { List<String> cookies = headers.get(HttpHeaders.Names.SET_COOKIE); if (cookies == null) { - return Collections.emptyList(); + return List.of(); } List<Cookie> ret = new LinkedList<>(); for (String cookie : cookies) { @@ -32,7 +30,7 @@ public class CookieHelper { public static void encodeSetCookieHeader(HeaderFields headers, List<Cookie> cookies) { headers.remove(HttpHeaders.Names.SET_COOKIE); for (Cookie cookie : cookies) { - headers.add(HttpHeaders.Names.SET_COOKIE, Cookie.toSetCookieHeaders(Arrays.asList(cookie))); + headers.add(HttpHeaders.Names.SET_COOKIE, Cookie.toSetCookieHeaders(List.of(cookie))); } } } diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/HttpRequest.java b/container-core/src/main/java/com/yahoo/jdisc/http/HttpRequest.java index 4f1a0bf0d03..e801873e2cd 100644 --- a/container-core/src/main/java/com/yahoo/jdisc/http/HttpRequest.java +++ b/container-core/src/main/java/com/yahoo/jdisc/http/HttpRequest.java @@ -16,7 +16,6 @@ import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.security.Principal; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -226,7 +225,7 @@ public class HttpRequest extends Request { public List<Cookie> decodeCookieHeader() { List<String> cookies = headers().get(HttpHeaders.Names.COOKIE); if (cookies == null) { - return Collections.emptyList(); + return List.of(); } List<Cookie> ret = new LinkedList<>(); for (String cookie : cookies) { diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/filter/DiscFilterRequest.java b/container-core/src/main/java/com/yahoo/jdisc/http/filter/DiscFilterRequest.java index a1ea14d80a3..c22e4afec1c 100644 --- a/container-core/src/main/java/com/yahoo/jdisc/http/filter/DiscFilterRequest.java +++ b/container-core/src/main/java/com/yahoo/jdisc/http/filter/DiscFilterRequest.java @@ -242,7 +242,7 @@ public class DiscFilterRequest { public List<String> getHeadersAsList(String name) { List<String> values = parent.headers().get(name); if(values == null) { - return Collections.emptyList(); + return List.of(); } return parent.headers().get(name); } @@ -401,7 +401,7 @@ public class DiscFilterRequest { return Optional.ofNullable(parent.context().get(RequestUtils.JDISC_REQUEST_X509CERT)) .map(X509Certificate[].class::cast) .map(Arrays::asList) - .orElse(Collections.emptyList()); + .orElse(List.of()); } public void setUserRoles(String[] roles) { diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/filter/DiscFilterResponse.java b/container-core/src/main/java/com/yahoo/jdisc/http/filter/DiscFilterResponse.java index f96bb8b30ae..5070ef75c4d 100644 --- a/container-core/src/main/java/com/yahoo/jdisc/http/filter/DiscFilterResponse.java +++ b/container-core/src/main/java/com/yahoo/jdisc/http/filter/DiscFilterResponse.java @@ -9,7 +9,6 @@ import com.yahoo.jdisc.http.HttpResponse; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.List; @@ -158,7 +157,7 @@ public class DiscFilterResponse { public void setCookie(String name, String value) { Cookie cookie = new Cookie(name, value); - setCookies(Arrays.asList(cookie)); + setCookies(List.of(cookie)); } } diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChain.java b/container-core/src/main/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChain.java index 22874d2f987..dc8eb7daa7a 100644 --- a/container-core/src/main/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChain.java +++ b/container-core/src/main/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChain.java @@ -9,7 +9,6 @@ import com.yahoo.jdisc.handler.ResponseHandler; import com.yahoo.jdisc.http.HttpRequest; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -42,7 +41,7 @@ public final class SecurityRequestFilterChain extends AbstractResource implement } public static RequestFilter newInstance(SecurityRequestFilter... filters) { - return newInstance(Arrays.asList(filters)); + return newInstance(List.of(filters)); } public static RequestFilter newInstance(List<? extends SecurityRequestFilter> filters) { diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChain.java b/container-core/src/main/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChain.java index e6d5e67bc57..16565cb5010 100644 --- a/container-core/src/main/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChain.java +++ b/container-core/src/main/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChain.java @@ -8,8 +8,6 @@ import com.yahoo.jdisc.http.HttpRequest; import java.net.URI; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -20,12 +18,14 @@ import java.util.Optional; */ public class SecurityResponseFilterChain extends AbstractResource implements ResponseFilter { - private final List<SecurityResponseFilter> filters = new ArrayList<>(); + private final List<SecurityResponseFilter> filters; private SecurityResponseFilterChain(Iterable<? extends SecurityResponseFilter> filters) { + List<SecurityResponseFilter> builder = new ArrayList<>(); for (SecurityResponseFilter filter : filters) { - this.filters.add(filter); + builder.add(filter); } + this.filters = List.copyOf(builder); } @Override @@ -42,7 +42,7 @@ public class SecurityResponseFilterChain extends AbstractResource implements Res } public static ResponseFilter newInstance(SecurityResponseFilter... filters) { - return newInstance(Arrays.asList(filters)); + return newInstance(List.of(filters)); } public static ResponseFilter newInstance(List<? extends SecurityResponseFilter> filters) { @@ -51,7 +51,7 @@ public class SecurityResponseFilterChain extends AbstractResource implements Res /** Returns an unmodifiable view of the filters in this */ public List<SecurityResponseFilter> getFilters() { - return Collections.unmodifiableList(filters); + return filters; } static class RequestViewImpl implements RequestView { @@ -74,7 +74,7 @@ public class SecurityResponseFilterChain extends AbstractResource implements Res @Override public List<String> getHeaders(String name) { List<String> headers = request.headers().get(name); - return headers == null ? Collections.emptyList() : Collections.unmodifiableList(headers); + return headers == null ? List.of() : List.copyOf(headers); } @Override diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/filter/chain/RequestFilterChain.java b/container-core/src/main/java/com/yahoo/jdisc/http/filter/chain/RequestFilterChain.java index 2f50b5e319b..d6666060dbc 100644 --- a/container-core/src/main/java/com/yahoo/jdisc/http/filter/chain/RequestFilterChain.java +++ b/container-core/src/main/java/com/yahoo/jdisc/http/filter/chain/RequestFilterChain.java @@ -8,7 +8,6 @@ import com.yahoo.jdisc.http.HttpRequest; import com.yahoo.jdisc.http.filter.RequestFilter; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -40,7 +39,7 @@ public final class RequestFilterChain extends AbstractResource implements Reques } public static RequestFilter newInstance(RequestFilter... filters) { - return newInstance(Arrays.asList(filters)); + return newInstance(List.of(filters)); } public static RequestFilter newInstance(List<? extends RequestFilter> filters) { diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/filter/chain/ResponseFilterChain.java b/container-core/src/main/java/com/yahoo/jdisc/http/filter/chain/ResponseFilterChain.java index 02d94a7529e..5145c7210f1 100644 --- a/container-core/src/main/java/com/yahoo/jdisc/http/filter/chain/ResponseFilterChain.java +++ b/container-core/src/main/java/com/yahoo/jdisc/http/filter/chain/ResponseFilterChain.java @@ -8,7 +8,6 @@ import com.yahoo.jdisc.application.ResourcePool; import com.yahoo.jdisc.http.filter.ResponseFilter; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -39,7 +38,7 @@ public final class ResponseFilterChain extends AbstractResource implements Respo } public static ResponseFilter newInstance(ResponseFilter... filters) { - return newInstance(Arrays.asList(filters)); + return newInstance(List.of(filters)); } public static ResponseFilter newInstance(List<? extends ResponseFilter> filters) { diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/CompletionHandlers.java b/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/CompletionHandlers.java index caa942b6a5c..23efec5f98d 100644 --- a/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/CompletionHandlers.java +++ b/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/CompletionHandlers.java @@ -3,7 +3,8 @@ package com.yahoo.jdisc.http.server.jetty; import com.yahoo.jdisc.handler.CompletionHandler; -import java.util.Arrays; +import java.util.List; + /** * @author Simon Thoresen Hult @@ -33,7 +34,7 @@ public class CompletionHandlers { } public static CompletionHandler wrap(CompletionHandler... handlers) { - return wrap(Arrays.asList(handlers)); + return wrap(List.of(handlers)); } public static CompletionHandler wrap(final Iterable<CompletionHandler> handlers) { diff --git a/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/FormPostRequestHandler.java b/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/FormPostRequestHandler.java index b43281c524a..7e6b9b822ac 100644 --- a/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/FormPostRequestHandler.java +++ b/container-core/src/main/java/com/yahoo/jdisc/http/server/jetty/FormPostRequestHandler.java @@ -20,7 +20,6 @@ import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -134,7 +133,7 @@ class FormPostRequestHandler extends AbstractRequestHandler implements ContentCh */ private static Map<String, List<String>> parseFormParameters(String formContent) { if (formContent.isEmpty()) { - return Collections.emptyMap(); + return Map.of(); } Map<String, List<String>> parameterMap = new HashMap<>(); diff --git a/container-core/src/main/java/com/yahoo/metrics/simple/Point.java b/container-core/src/main/java/com/yahoo/metrics/simple/Point.java index 5c7abe03596..4a1ae80fc69 100644 --- a/container-core/src/main/java/com/yahoo/metrics/simple/Point.java +++ b/container-core/src/main/java/com/yahoo/metrics/simple/Point.java @@ -74,13 +74,11 @@ public final class Point implements Context { @Override public String toString() { final int maxLen = 3; - StringBuilder builder = new StringBuilder(); - builder.append("Point [location=") - .append(Arrays.asList(location).subList(0, Math.min(location.length, maxLen))) - .append(", dimensions=") - .append(Arrays.asList(dimensions).subList(0, Math.min(dimensions.length, maxLen))) - .append("]"); - return builder.toString(); + return "Point [location=" + + List.of(location).subList(0, Math.min(location.length, maxLen)) + + ", dimensions=" + + List.of(dimensions).subList(0, Math.min(dimensions.length, maxLen)) + + "]"; } /** diff --git a/container-core/src/main/java/com/yahoo/osgi/MockOsgi.java b/container-core/src/main/java/com/yahoo/osgi/MockOsgi.java index e8a92211afb..decf7a557be 100644 --- a/container-core/src/main/java/com/yahoo/osgi/MockOsgi.java +++ b/container-core/src/main/java/com/yahoo/osgi/MockOsgi.java @@ -7,7 +7,6 @@ import com.yahoo.jdisc.test.NonWorkingOsgiFramework; import org.osgi.framework.Bundle; import org.osgi.framework.ServiceReference; -import java.util.Collections; import java.util.List; /** @@ -23,7 +22,7 @@ public class MockOsgi extends NonWorkingOsgiFramework implements Osgi { @Override public List<Bundle> getCurrentBundles() { - return Collections.emptyList(); + return List.of(); } @Override @@ -33,7 +32,7 @@ public class MockOsgi extends NonWorkingOsgiFramework implements Osgi { @Override public List<Bundle> install(String absolutePath) { - return Collections.emptyList(); + return List.of(); } } diff --git a/container-core/src/main/java/com/yahoo/processing/handler/ProcessingTestDriver.java b/container-core/src/main/java/com/yahoo/processing/handler/ProcessingTestDriver.java index cd22dc80a4c..b17e4229c4c 100644 --- a/container-core/src/main/java/com/yahoo/processing/handler/ProcessingTestDriver.java +++ b/container-core/src/main/java/com/yahoo/processing/handler/ProcessingTestDriver.java @@ -12,9 +12,9 @@ import com.yahoo.processing.Processor; import com.yahoo.processing.execution.chain.ChainRegistry; import com.yahoo.processing.rendering.Renderer; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @@ -38,12 +38,12 @@ public class ProcessingTestDriver extends RequestHandlerTestDriver { @SafeVarargs @SuppressWarnings("varargs") public ProcessingTestDriver(Chain<Processor> ... chains) { - this(Arrays.asList(chains), new ComponentRegistry<>()); + this(List.of(chains), new ComponentRegistry<>()); } @SafeVarargs @SuppressWarnings("varargs") public ProcessingTestDriver(String binding, Chain<Processor> ... chains) { - this(binding, Arrays.asList(chains), new ComponentRegistry<>()); + this(binding, List.of(chains), new ComponentRegistry<>()); } public ProcessingTestDriver(Collection<Chain<Processor>> chains, ComponentRegistry<Renderer> renderers) { this(createProcessingHandler(chains, renderers, AccessLog.voidAccessLog())); diff --git a/container-core/src/main/java/com/yahoo/processing/request/CompoundName.java b/container-core/src/main/java/com/yahoo/processing/request/CompoundName.java index cb4743cd83e..b4536a1c56b 100644 --- a/container-core/src/main/java/com/yahoo/processing/request/CompoundName.java +++ b/container-core/src/main/java/com/yahoo/processing/request/CompoundName.java @@ -173,7 +173,7 @@ public final class CompoundName { if (isEmpty()) return fromComponents(nameParts); List<String> newCompounds = new ArrayList<>(nameParts.length + compounds.size()); - newCompounds.addAll(Arrays.asList(nameParts)); + newCompounds.addAll(List.of(nameParts)); newCompounds.addAll(this.compounds); return new CompoundName(newCompounds); } @@ -204,7 +204,7 @@ public final class CompoundName { throw new IllegalArgumentException("Asked for the first " + n + " components but '" + this + "' only have " + compounds.size() + " components."); if (compounds.size() == n) return this; - if (compounds.size() == 0) return empty; + if (compounds.isEmpty()) return empty; if (compounds.size() - 1 == n) return first; return first.first(n); } @@ -316,7 +316,7 @@ public final class CompoundName { for (String compound : compounds) all += compound.length(); StringBuilder b = new StringBuilder(all); for (String compound : compounds) b.append(compound).append("."); - return b.length()==0 ? "" : b.substring(0, b.length()-1); + return b.isEmpty() ? "" : b.substring(0, b.length()-1); } /** diff --git a/container-core/src/main/java/com/yahoo/processing/request/Properties.java b/container-core/src/main/java/com/yahoo/processing/request/Properties.java index d06e8b26cd9..e689ea76f3a 100644 --- a/container-core/src/main/java/com/yahoo/processing/request/Properties.java +++ b/container-core/src/main/java/com/yahoo/processing/request/Properties.java @@ -3,7 +3,6 @@ package com.yahoo.processing.request; import java.util.Map; import java.util.HashMap; -import java.util.Collections; /** * The properties of a request @@ -271,7 +270,7 @@ public class Properties implements Cloneable { * @throws RuntimeException if no instance in the chain accepted this name-value pair */ public final void clearAll(String name) { - clearAll(new CompoundName(name), Collections.<String,String>emptyMap()); + clearAll(new CompoundName(name), Map.of()); } /** diff --git a/container-core/src/main/java/com/yahoo/processing/response/DefaultIncomingData.java b/container-core/src/main/java/com/yahoo/processing/response/DefaultIncomingData.java index d820c2812e5..ee2e920afcc 100644 --- a/container-core/src/main/java/com/yahoo/processing/response/DefaultIncomingData.java +++ b/container-core/src/main/java/com/yahoo/processing/response/DefaultIncomingData.java @@ -5,7 +5,6 @@ import com.yahoo.collections.Tuple2; import com.yahoo.concurrent.CompletableFutures; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; @@ -60,13 +59,13 @@ public class DefaultIncomingData<DATATYPE extends Data> implements IncomingData< /** Adds new data and marks this as completed */ @Override public synchronized void addLast(DATATYPE data) { - addLast(Collections.singletonList(data)); + addLast(List.of(data)); } /** Adds new data without completing this */ @Override public synchronized void add(DATATYPE data) { - add(Collections.singletonList(data)); + add(List.of(data)); } /** Adds new data and marks this as completed */ diff --git a/container-core/src/main/java/com/yahoo/processing/response/IncomingData.java b/container-core/src/main/java/com/yahoo/processing/response/IncomingData.java index 45dec0ad2ba..fb891f0b8ea 100644 --- a/container-core/src/main/java/com/yahoo/processing/response/IncomingData.java +++ b/container-core/src/main/java/com/yahoo/processing/response/IncomingData.java @@ -3,7 +3,6 @@ package com.yahoo.processing.response; import com.yahoo.processing.impl.ProcessingFuture; -import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; @@ -158,7 +157,7 @@ public interface IncomingData<DATATYPE extends Data> { } public List<DATATYPE> drain() { - return Collections.emptyList(); + return List.of(); } /** diff --git a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java index 8c94b5f9a93..207e18084ab 100644 --- a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java +++ b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java @@ -11,8 +11,6 @@ import com.yahoo.component.chain.dependencies.Provides; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -90,15 +88,15 @@ public class ChainBuilderTest { @Test void testPhaseAndSearcher() { ChainBuilder depHandler = newChainBuilder(); - depHandler.addPhase(new Phase("phase1", set("phase2"), Collections.<String>emptySet())); + depHandler.addPhase(new Phase("phase1", set("phase2"), Set.of())); depHandler.addPhase(new Phase("phase2", set("phase3"), set("phase1"))); - depHandler.addPhase(new Phase("phase3", Collections.<String>emptySet(), set("phase2", "phase1"))); + depHandler.addPhase(new Phase("phase3", Set.of(), set("phase2", "phase1"))); ChainedComponent first = new First(); ChainedComponent second = new Second(); depHandler.addComponent(first); depHandler.addComponent(second); - assertEquals(depHandler.orderNodes().components(), Arrays.asList(first, second)); + assertEquals(depHandler.orderNodes().components(), List.of(first, second)); } @@ -114,7 +112,7 @@ public class ChainBuilderTest { chainBuilder.addComponent(c); chainBuilder.addComponent(a2); - assertEquals(Arrays.asList(a1, c, a2), chainBuilder.orderNodes().components()); + assertEquals(List.of(a1, c, a2), chainBuilder.orderNodes().components()); } private ChainBuilder newChainBuilder() { @@ -122,7 +120,7 @@ public class ChainBuilderTest { } private Set<String> set(String... strings) { - return new HashSet<>(Arrays.asList(strings)); + return new HashSet<>(List.of(strings)); } @Before("phase1") @@ -172,9 +170,9 @@ public class ChainBuilderTest { private ChainBuilder createDependencyHandler() { ChainBuilder chainBuilder = newChainBuilder(); - chainBuilder.addPhase(new Phase("phase1", Collections.<String>emptySet(), Collections.<String>emptySet())); - chainBuilder.addPhase(new Phase("phase2", Collections.<String>emptySet(), Collections.<String>emptySet())); - chainBuilder.addPhase(new Phase("phase3", Collections.<String>emptySet(), Collections.<String>emptySet())); + chainBuilder.addPhase(new Phase("phase1", Set.of(), Set.of())); + chainBuilder.addPhase(new Phase("phase2", Set.of(), Set.of())); + chainBuilder.addPhase(new Phase("phase3", Set.of(), Set.of())); return chainBuilder; } diff --git a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java index f1dd1ff03c0..126e96c7543 100644 --- a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java +++ b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.component.chain.dependencies.ordering; -import java.util.Arrays; import com.yahoo.component.chain.ChainedComponent; @@ -11,6 +10,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.yahoo.component.ComponentId; +import java.util.List; + /** * Test for OrderedReadyNodes. @@ -20,14 +21,14 @@ import com.yahoo.component.ComponentId; @SuppressWarnings("rawtypes") public class OrderedReadyNodesTest { - class ComponentA extends ChainedComponent { + static class ComponentA extends ChainedComponent { public ComponentA(ComponentId id) { super(id); } @Override public Dependencies getDependencies() { - return new Dependencies(Arrays.asList(getId().getName()), null, null); + return new Dependencies(List.of(getId().getName()), null, null); } } diff --git a/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java b/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java index 14349d4cd51..7240b6510c5 100644 --- a/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java +++ b/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java @@ -15,7 +15,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.File; -import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -45,7 +44,7 @@ public class ConfigRetrieverTest { void require_that_bootstrap_configs_come_first() { writeConfigs(); ConfigRetriever retriever = createConfigRetriever(); - ConfigSnapshot bootstrapConfigs = retriever.getConfigs(Collections.emptySet(), 0, true); + ConfigSnapshot bootstrapConfigs = retriever.getConfigs(Set.of(), 0, true); assertTrue(bootstrapConfigs instanceof BootstrapConfigs); retriever.shutdown(); @@ -56,10 +55,10 @@ public class ConfigRetrieverTest { void require_that_components_comes_after_bootstrap() { writeConfigs(); ConfigRetriever retriever = createConfigRetriever(); - ConfigSnapshot bootstrapConfigs = retriever.getConfigs(Collections.emptySet(), 0, true); + ConfigSnapshot bootstrapConfigs = retriever.getConfigs(Set.of(), 0, true); ConfigKey<? extends ConfigInstance> testConfigKey = new ConfigKey<>(TestConfig.class, dirConfigSource.configId()); - ConfigSnapshot componentsConfigs = retriever.getConfigs(Collections.singleton(testConfigKey), 0, true); + ConfigSnapshot componentsConfigs = retriever.getConfigs(Set.of(testConfigKey), 0, true); if (componentsConfigs instanceof ComponentsConfigs) { assertEquals(3, componentsConfigs.size()); @@ -75,8 +74,8 @@ public class ConfigRetrieverTest { writeConfigs(); ConfigRetriever retriever = createConfigRetriever(); ConfigKey<? extends ConfigInstance> testConfigKey = new ConfigKey<>(TestConfig.class, dirConfigSource.configId()); - ConfigSnapshot bootstrapConfigs = retriever.getConfigs(Collections.emptySet(), 0, true); - ConfigSnapshot componentsConfigs = retriever.getConfigs(Collections.singleton(testConfigKey), 0, true); + ConfigSnapshot bootstrapConfigs = retriever.getConfigs(Set.of(), 0, true); + ConfigSnapshot componentsConfigs = retriever.getConfigs(Set.of(testConfigKey), 0, true); Set<ConfigKey<? extends ConfigInstance>> keys = new HashSet<>(); keys.add(testConfigKey); keys.add(new ConfigKey<>(TestConfig.class, "")); @@ -92,8 +91,8 @@ public class ConfigRetrieverTest { void require_that_empty_components_keys_after_bootstrap_returns_components_configs() { writeConfigs(); ConfigRetriever retriever = createConfigRetriever(); - assertTrue(retriever.getConfigs(Collections.emptySet(), 0, true) instanceof BootstrapConfigs); - assertTrue(retriever.getConfigs(Collections.emptySet(), 0, true) instanceof ComponentsConfigs); + assertTrue(retriever.getConfigs(Set.of(), 0, true) instanceof BootstrapConfigs); + assertTrue(retriever.getConfigs(Set.of(), 0, true) instanceof ComponentsConfigs); retriever.shutdown(); } diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java index aacc43d725b..e99f98cb842 100644 --- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java +++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java @@ -21,9 +21,9 @@ import com.yahoo.vespa.config.ConfigKey; import org.junit.jupiter.api.Test; import java.lang.annotation.Annotation; -import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @@ -480,7 +480,7 @@ public class ComponentGraphTest { ComponentGraph graph = new ComponentGraph(); graph.add(mockComponentNodeWithId(ExecutorProvider.class, "dummyId")); graph.complete(); - graph.setAvailableConfigs(Collections.emptyMap()); + graph.setAvailableConfigs(Map.of()); return graph; } @@ -607,7 +607,7 @@ public class ComponentGraphTest { } public static class ExecutorProvider implements Provider<Executor> { - private Executor executor = Executors.newSingleThreadExecutor(); + private final Executor executor = Executors.newSingleThreadExecutor(); public Executor get() { return executor; diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java index 59c939863dd..17ead389c48 100644 --- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java +++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java @@ -16,7 +16,7 @@ import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.SimpleCompo import com.yahoo.vespa.config.ConfigKey; import org.junit.jupiter.api.Test; -import java.util.Collections; +import java.util.Map; import java.util.concurrent.Executor; import java.util.function.Function; import java.util.function.Supplier; @@ -68,12 +68,12 @@ public class ReuseComponentsTest { Class<ComponentTakingConfig> componentClass = ComponentTakingConfig.class; ComponentGraph graph = buildGraph(componentClass); - graph.setAvailableConfigs(Collections.singletonMap(new ConfigKey<>(TestConfig.class, "component"), + graph.setAvailableConfigs(Map.of(new ConfigKey<>(TestConfig.class, "component"), ConfigGetter.getConfig(TestConfig.class, "raw: stringVal \"oldConfig\""))); ComponentTakingConfig instance = getComponent(graph, componentClass); ComponentGraph newGraph = buildGraph(componentClass); - newGraph.setAvailableConfigs(Collections.singletonMap(new ConfigKey<>(TestConfig.class, "component"), + newGraph.setAvailableConfigs(Map.of(new ConfigKey<>(TestConfig.class, "component"), ConfigGetter.getConfig(TestConfig.class, "raw: stringVal \"newConfig\""))); newGraph.reuseNodes(graph); ComponentTakingConfig instance2 = getComponent(newGraph, componentClass); @@ -98,7 +98,7 @@ public class ReuseComponentsTest { graph.add(injectedComponent); graph.complete(); - graph.setAvailableConfigs(Collections.singletonMap(new ConfigKey<>(TestConfig.class, configId), + graph.setAvailableConfigs(Map.of(new ConfigKey<>(TestConfig.class, configId), ConfigGetter.getConfig(TestConfig.class, "raw: stringVal \"" + config + "\""))); return graph; @@ -132,7 +132,7 @@ public class ReuseComponentsTest { } graph.complete(); - graph.setAvailableConfigs(Collections.emptyMap()); + graph.setAvailableConfigs(Map.of()); return graph; }; @@ -163,7 +163,7 @@ public class ReuseComponentsTest { graph.add(injectedComponent); graph.complete(); - graph.setAvailableConfigs(Collections.singletonMap(new ConfigKey<>(TestConfig.class, configId), + graph.setAvailableConfigs(Map.of(new ConfigKey<>(TestConfig.class, configId), ConfigGetter.getConfig(TestConfig.class, "raw: stringVal \"" + config + "\""))); return graph; @@ -188,7 +188,7 @@ public class ReuseComponentsTest { ComponentGraph graph = new ComponentGraph(); graph.add(mockComponentNode(ComponentTakingExecutor.class, "dummyId")); graph.complete(ComponentGraphTest.singletonExecutorInjector); - graph.setAvailableConfigs(Collections.emptyMap()); + graph.setAvailableConfigs(Map.of()); return graph; }; @@ -224,7 +224,7 @@ public class ReuseComponentsTest { private void completeNode(ComponentNode node) { node.setArguments(new Object[0]); - node.setAvailableConfigs(Collections.emptyMap()); + node.setAvailableConfigs(Map.of()); } private ComponentGraph buildGraph(Class<?> componentClass) { @@ -237,7 +237,7 @@ public class ReuseComponentsTest { private ComponentGraph buildGraphAndSetNoConfigs(Class<?> componentClass) { ComponentGraph g = buildGraph(componentClass); - g.setAvailableConfigs(Collections.emptyMap()); + g.setAvailableConfigs(Map.of()); return g; } diff --git a/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java b/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java index 3d5375a9740..11de808a415 100644 --- a/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java +++ b/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java @@ -116,7 +116,7 @@ public class ContainerThreadPoolImplTest { assertEquals(CPUS * 4 * 100, executor.getQueue().remainingCapacity()); } - private class FlipIt implements Runnable { + private static class FlipIt implements Runnable { public final Receiver<Boolean> didItRun = new Receiver<>(); @Override @@ -176,7 +176,7 @@ public class ContainerThreadPoolImplTest { } } - private class Hang implements Runnable { + private static class Hang implements Runnable { private final long hangMillis; diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java index f70772b7331..2aa5c888865 100644 --- a/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java +++ b/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java @@ -8,7 +8,7 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; -import java.util.Collections; +import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -30,7 +30,7 @@ public class HttpRequestTestCase { @BeforeEach public void setUp() throws Exception { requestData = new ByteArrayInputStream(Utf8.toBytes(X_RAY_YANKEE_ZULU)); - r = HttpRequest.createTestRequest(HTTP_MAILHOST_25_ALPHA_BRAVO_CHARLIE_DELTA, Method.GET, requestData, Collections.singletonMap("foxtrot", "golf")); + r = HttpRequest.createTestRequest(HTTP_MAILHOST_25_ALPHA_BRAVO_CHARLIE_DELTA, Method.GET, requestData, Map.of("foxtrot", "golf")); } @AfterEach diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java index 3217bff4bb3..ccc7b22f348 100644 --- a/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java +++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java @@ -3,8 +3,8 @@ package com.yahoo.container.jdisc.state; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.HashMap; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -29,8 +29,8 @@ public class MetricSnapshotTest { @Test void testEquality() { - assertEquals(Collections.unmodifiableMap(new HashMap(0)).hashCode(), Collections.emptyMap().hashCode()); - assertEquals(Collections.unmodifiableMap(new HashMap(0)), Collections.emptyMap()); + assertEquals(new HashMap(0).hashCode(), Map.of().hashCode()); + assertEquals(new HashMap(0), Map.of()); } } diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java index c99a61781cb..68a7d06e7fe 100644 --- a/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java +++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java @@ -79,10 +79,8 @@ public class StateHandlerTest extends StateHandlerTestBase { @Test public void testPrometheusFormat() { - var counterContext = StateMetricContext.newInstance(Map.of("label1", "val1", "label2", "val2")); - var otherContext = StateMetricContext.newInstance(Map.of( - "label1", "This label has \"quotes\"", - "label2", "This label, a\nnewline")); + var counterContext = StateMetricContext.newInstance(Map.of("label", "This label has \"quotes\"")); + var otherContext = StateMetricContext.newInstance(Map.of("label", "This label, a\nnewline")); var snapshot = new MetricSnapshot(0L, SNAPSHOT_INTERVAL, TimeUnit.MILLISECONDS); snapshot.add(counterContext, "some.counter", 10); snapshot.add(counterContext, "some.counter", 20); @@ -100,8 +98,8 @@ public class StateHandlerTest extends StateHandlerTestBase { bar_count 2 300000 bar_max 40.0 300000 bar_sum 60.0 300000 - some_counter_count{label1="This label has \\"quotes\\"",label2="This label, a\\nnewline",} 3 300000 - some_counter_count{label1="val1",label2="val2",} 30 300000 + some_counter_count{label="This label has \\"quotes\\"",} 30 300000 + some_counter_count{label="This label, a\\nnewline",} 3 300000 testing_infinity_count 1 300000 testing_infinity_max -Inf 300000 testing_infinity_sum -Inf 300000 diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java index a629acd0d1b..6f5af2f308b 100644 --- a/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java +++ b/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java @@ -8,8 +8,6 @@ import org.junit.jupiter.api.Test; import java.net.InetSocketAddress; import java.net.URI; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; @@ -97,11 +95,11 @@ public class HttpRequestTestCase { request.setConnectionTimeout(1, TimeUnit.SECONDS); assertEquals(Long.valueOf(1000), request.getConnectionTimeout(TimeUnit.MILLISECONDS)); - assertEquals(Arrays.asList("bar", "baz"), request.parameters().get("foo")); - assertEquals(Collections.singletonList("69"), request.parameters().get("cox")); - request.parameters().put("cox", Arrays.asList("6", "9")); - assertEquals(Arrays.asList("bar", "baz"), request.parameters().get("foo")); - assertEquals(Arrays.asList("6", "9"), request.parameters().get("cox")); + assertEquals(List.of("bar", "baz"), request.parameters().get("foo")); + assertEquals(List.of("69"), request.parameters().get("cox")); + request.parameters().put("cox", List.of("6", "9")); + assertEquals(List.of("bar", "baz"), request.parameters().get("foo")); + assertEquals(List.of("6", "9"), request.parameters().get("cox")); assertEquals(1L, request.getConnectedAt(TimeUnit.MILLISECONDS)); } @@ -170,7 +168,7 @@ public class HttpRequestTestCase { @Test void requireThatCookieHeaderCanBeEncoded() throws Exception { final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0); - final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar")); + final List<Cookie> cookies = List.of(new Cookie("foo", "bar")); request.encodeCookieHeader(cookies); final List<String> headers = request.headers().get(com.yahoo.jdisc.http.HttpHeaders.Names.COOKIE); assertEquals(1, headers.size()); @@ -180,7 +178,7 @@ public class HttpRequestTestCase { @Test void requireThatCookieHeaderCanBeDecoded() throws Exception { final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0); - final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar")); + final List<Cookie> cookies = List.of(new Cookie("foo", "bar")); request.encodeCookieHeader(cookies); assertEquals(cookies, request.decodeCookieHeader()); } diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java index da897794af2..c521462c896 100644 --- a/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java +++ b/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java @@ -4,8 +4,6 @@ package com.yahoo.jdisc.http; import com.yahoo.jdisc.Response; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -79,7 +77,7 @@ public class HttpResponseTestCase { @Test void requireThatCookieHeaderCanBeEncoded() throws Exception { final HttpResponse response = newResponse(69); - final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar")); + final List<Cookie> cookies = List.of(new Cookie("foo", "bar")); response.encodeSetCookieHeader(cookies); final List<String> headers = response.headers().get(HttpHeaders.Names.SET_COOKIE); assertEquals(1, headers.size()); @@ -89,18 +87,18 @@ public class HttpResponseTestCase { @Test void requireThatMultipleCookieHeadersCanBeEncoded() throws Exception { final HttpResponse response = newResponse(69); - final List<Cookie> cookies = Arrays.asList(new Cookie("foo", "bar"), new Cookie("baz", "cox")); + final List<Cookie> cookies = List.of(new Cookie("foo", "bar"), new Cookie("baz", "cox")); response.encodeSetCookieHeader(cookies); final List<String> headers = response.headers().get(HttpHeaders.Names.SET_COOKIE); assertEquals(2, headers.size()); - assertEquals(Cookie.toSetCookieHeaders(Arrays.asList(new Cookie("foo", "bar"), new Cookie("baz", "cox"))), + assertEquals(Cookie.toSetCookieHeaders(List.of(new Cookie("foo", "bar"), new Cookie("baz", "cox"))), headers); } @Test void requireThatCookieHeaderCanBeDecoded() throws Exception { final HttpResponse response = newResponse(69); - final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar")); + final List<Cookie> cookies = List.of(new Cookie("foo", "bar")); response.encodeSetCookieHeader(cookies); assertEquals(cookies, response.decodeSetCookieHeader()); } @@ -108,7 +106,7 @@ public class HttpResponseTestCase { @Test void requireThatMultipleCookieHeadersCanBeDecoded() throws Exception { final HttpResponse response = newResponse(69); - final List<Cookie> cookies = Arrays.asList(new Cookie("foo", "bar"), new Cookie("baz", "cox")); + final List<Cookie> cookies = List.of(new Cookie("foo", "bar"), new Cookie("baz", "cox")); response.encodeSetCookieHeader(cookies); assertEquals(cookies, response.decodeSetCookieHeader()); } diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java index 6460dee8365..9a3005c0971 100644 --- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java +++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java @@ -12,7 +12,6 @@ import org.junit.jupiter.api.Test; import java.net.InetSocketAddress; import java.net.URI; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.List; @@ -306,7 +305,7 @@ public class DiscFilterRequestTest { URI uri = URI.create("http://example.yahoo.com/test"); HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1); httpReq.headers().add("key1", "value1"); - httpReq.headers().add("key2", Arrays.asList("value1", "value2")); + httpReq.headers().add("key2", List.of("value1", "value2")); DiscFilterRequest request = new DiscFilterRequest(httpReq); HeaderFields headers = request.getUntreatedHeaders(); diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java index 9c17ce7d0da..73dfb85519c 100644 --- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java +++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java @@ -54,7 +54,6 @@ import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; @@ -667,7 +666,7 @@ public class HttpServerTest { private ResponseMetricAggregator.StatisticsEntry waitForStatistics(ResponseMetricAggregator statisticsCollector) { - List<ResponseMetricAggregator.StatisticsEntry> entries = Collections.emptyList(); + List<ResponseMetricAggregator.StatisticsEntry> entries = List.of(); int tries = 0; // Wait up to 30 seconds before giving up while (entries.isEmpty() && tries < 300) { @@ -912,7 +911,7 @@ public class HttpServerTest { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { final HttpResponse response = HttpResponse.newInstance(OK); - response.encodeSetCookieHeader(Collections.singletonList(cookie)); + response.encodeSetCookieHeader(List.of(cookie)); ResponseDispatch.newInstance(response).dispatch(handler); return null; } @@ -922,8 +921,8 @@ public class HttpServerTest { @Override public ContentChannel handleRequest(final Request request, final ResponseHandler handler) { - final List<Cookie> cookies = new ArrayList<>(((HttpRequest)request).decodeCookieHeader()); - Collections.sort(cookies, new CookieComparator()); + List<Cookie> cookies = new ArrayList<>(((HttpRequest)request).decodeCookieHeader()); + cookies.sort(new CookieComparator()); final ContentChannel out = ResponseDispatch.newInstance(Response.Status.OK).connect(handler); out.write(StandardCharsets.UTF_8.encode(cookies.toString()), null); out.close(null); diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java index 0368c925bcc..ad95c87ca8c 100644 --- a/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java +++ b/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java @@ -3,8 +3,8 @@ package com.yahoo.metrics.simple; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.HashMap; +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -15,7 +15,7 @@ public class PointTest { @Test void testPointEquality() { - Point a = new Point(Collections.emptyMap()); + Point a = new Point(Map.of()); Point b = new Point(new HashMap<>(0)); assertEquals(a.hashCode(), b.hashCode()); assertEquals(a, b); diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java index d8743d063fb..40ec5973510 100644 --- a/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java +++ b/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java @@ -14,7 +14,6 @@ import com.yahoo.metrics.simple.Point; import com.yahoo.metrics.simple.UntypedMetric; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -29,7 +28,7 @@ public class SnapshotConverterTest { @Test void testPointConversion() { - MetricDimensions a = SnapshotConverter.convert(new Point(Collections.emptyMap())); + MetricDimensions a = SnapshotConverter.convert(new Point(Map.of())); MetricDimensions b = SnapshotConverter.convert(new Point(new HashMap<>(0))); MetricDimensions c = SnapshotConverter.convert((Point) null); assertEquals(a.hashCode(), b.hashCode()); diff --git a/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java b/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java index 76de0767ef0..0149842393f 100644 --- a/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java +++ b/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java @@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.net.URI; import java.util.Collection; -import java.util.Collections; +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -30,7 +30,7 @@ public class MockUserDatabaseClientTest { Request request = null; try { Chain<Processor> chain = new Chain<>("default", new MockUserDatabaseClient()); - setupJDisc(Collections.singletonList(chain)); + setupJDisc(List.of(chain)); request = createRequest(); Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request); MockUserDatabaseClient.User user = (MockUserDatabaseClient.User) response.data().request().properties().get("User"); diff --git a/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java b/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java index 1f1f1d65677..43c7ccc75b2 100644 --- a/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java +++ b/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java @@ -5,7 +5,6 @@ import com.yahoo.lang.PublicCloneable; import com.yahoo.processing.request.properties.PropertyMap; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -24,8 +23,8 @@ public class PropertyMapTestCase { map.set("clonableArray", new ClonableObject[]{new ClonableObject()}); map.set("publicClonableArray", new ClonableObject[]{new ClonableObject()}); map.set("nonclonableArray", new NonClonableObject[]{new NonClonableObject()}); - map.set("clonableList", Collections.singletonList(new ClonableObject())); - map.set("nonclonableList", Collections.singletonList(new NonClonableObject())); + map.set("clonableList", List.of(new ClonableObject())); + map.set("nonclonableList", List.of(new NonClonableObject())); assertNotNull(map.get("clonable")); assertNotNull(map.get("nonclonable")); diff --git a/container-core/src/test/java/com/yahoo/processing/test/documentation/Federator.java b/container-core/src/test/java/com/yahoo/processing/test/documentation/Federator.java index 101f5d31648..c7892ddbc1e 100644 --- a/container-core/src/test/java/com/yahoo/processing/test/documentation/Federator.java +++ b/container-core/src/test/java/com/yahoo/processing/test/documentation/Federator.java @@ -10,7 +10,6 @@ import com.yahoo.processing.execution.Execution; import com.yahoo.processing.response.FutureResponse; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -23,7 +22,7 @@ public class Federator extends Processor { @SafeVarargs @SuppressWarnings("varargs") public Federator(Chain<? extends Processor> ... chains) { - this.chains = Arrays.asList(chains); + this.chains = List.of(chains); } @SuppressWarnings("unchecked") diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java index 6e8b8d44d0d..f0173fe4d68 100644 --- a/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java +++ b/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java @@ -13,7 +13,6 @@ import java.time.Instant; import java.util.List; import java.util.function.Supplier; -import static java.util.Collections.emptyList; import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -33,7 +32,7 @@ public class DeconstructorTest { deconstructor = new Deconstructor(); var slowDeconstructComponent = new SlowDeconstructComponent(); - deconstructor.deconstruct(0, List.of(slowDeconstructComponent), emptyList()); + deconstructor.deconstruct(0, List.of(slowDeconstructComponent), List.of()); deconstructor.shutdown(); assertTrue(slowDeconstructComponent.destructed); } @@ -41,7 +40,7 @@ public class DeconstructorTest { @Test void require_abstract_component_destructed() throws InterruptedException { TestAbstractComponent abstractComponent = new TestAbstractComponent(); - deconstructor.deconstruct(0, List.of(abstractComponent), emptyList()); + deconstructor.deconstruct(0, List.of(abstractComponent), List.of()); waitForDeconstructToComplete(() -> abstractComponent.destructed); assertTrue(abstractComponent.destructed); @@ -50,7 +49,7 @@ public class DeconstructorTest { @Test void require_provider_destructed() throws InterruptedException { TestProvider provider = new TestProvider(); - deconstructor.deconstruct(0, List.of(provider), emptyList()); + deconstructor.deconstruct(0, List.of(provider), List.of()); waitForDeconstructToComplete(() -> provider.destructed); assertTrue(provider.destructed); @@ -59,7 +58,7 @@ public class DeconstructorTest { @Test void require_shared_resource_released() throws InterruptedException { TestSharedResource sharedResource = new TestSharedResource(); - deconstructor.deconstruct(0, List.of(sharedResource), emptyList()); + deconstructor.deconstruct(0, List.of(sharedResource), List.of()); waitForDeconstructToComplete(() -> sharedResource.released); assertTrue(sharedResource.released); } @@ -68,7 +67,7 @@ public class DeconstructorTest { void bundles_are_uninstalled() throws InterruptedException { var bundle = new UninstallableMockBundle(); // Done by executor, so it takes some time even with a 0 delay. - deconstructor.deconstruct(0, emptyList(), singleton(bundle)); + deconstructor.deconstruct(0, List.of(), singleton(bundle)); waitForDeconstructToComplete(() -> bundle.uninstalled); assertTrue(bundle.uninstalled); diff --git a/container-messagebus/src/main/java/com/yahoo/messagebus/jdisc/test/ServerTestDriver.java b/container-messagebus/src/main/java/com/yahoo/messagebus/jdisc/test/ServerTestDriver.java index 5528085c5b8..bb3f4e0f5b0 100644 --- a/container-messagebus/src/main/java/com/yahoo/messagebus/jdisc/test/ServerTestDriver.java +++ b/container-messagebus/src/main/java/com/yahoo/messagebus/jdisc/test/ServerTestDriver.java @@ -14,7 +14,6 @@ import com.yahoo.messagebus.shared.ServerSession; import com.yahoo.messagebus.shared.SharedMessageBus; import com.yahoo.messagebus.test.SimpleProtocol; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; @@ -83,7 +82,7 @@ public class ServerTestDriver { if (reply == null) { return null; } - List<Integer> lst = new LinkedList<>(Arrays.asList(errCodes)); + List<Integer> lst = new LinkedList<>(List.of(errCodes)); for (int i = 0, len = reply.getNumErrors(); i < len; ++i) { Error err = reply.getError(i); System.out.println(err); diff --git a/container-messagebus/src/test/java/com/yahoo/container/jdisc/messagebus/MbusClientProviderTest.java b/container-messagebus/src/test/java/com/yahoo/container/jdisc/messagebus/MbusClientProviderTest.java index e514453bc08..1c85ec37e34 100644 --- a/container-messagebus/src/test/java/com/yahoo/container/jdisc/messagebus/MbusClientProviderTest.java +++ b/container-messagebus/src/test/java/com/yahoo/container/jdisc/messagebus/MbusClientProviderTest.java @@ -5,11 +5,9 @@ import com.yahoo.container.jdisc.ContainerMbusConfig; import com.yahoo.container.jdisc.config.SessionConfig; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.config.DocumentmanagerConfig; -import com.yahoo.documentapi.messagebus.protocol.DocumentProtocolPoliciesConfig; import com.yahoo.messagebus.MessagebusConfig; import com.yahoo.messagebus.network.NetworkMultiplexer; import com.yahoo.messagebus.shared.NullNetwork; -import com.yahoo.vespa.config.content.DistributionConfig; import org.junit.Test; import static org.junit.Assert.assertNotNull; diff --git a/container-messagebus/src/test/java/com/yahoo/messagebus/jdisc/MbusServerConformanceTest.java b/container-messagebus/src/test/java/com/yahoo/messagebus/jdisc/MbusServerConformanceTest.java index 6cc22beb921..9d1668ba671 100644 --- a/container-messagebus/src/test/java/com/yahoo/messagebus/jdisc/MbusServerConformanceTest.java +++ b/container-messagebus/src/test/java/com/yahoo/messagebus/jdisc/MbusServerConformanceTest.java @@ -24,7 +24,7 @@ import org.junit.Test; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; -import java.util.Collections; +import java.util.List; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; @@ -643,7 +643,7 @@ public class MbusServerConformanceTest extends ServerProviderConformanceTest { @Override public Iterable<ByteBuffer> newResponseContent() { - return Collections.emptyList(); + return List.of(); } @Override diff --git a/container-messagebus/src/test/java/com/yahoo/messagebus/jdisc/MbusServerTestCase.java b/container-messagebus/src/test/java/com/yahoo/messagebus/jdisc/MbusServerTestCase.java index 58b9ebb108e..cd60d4a30ea 100644 --- a/container-messagebus/src/test/java/com/yahoo/messagebus/jdisc/MbusServerTestCase.java +++ b/container-messagebus/src/test/java/com/yahoo/messagebus/jdisc/MbusServerTestCase.java @@ -28,7 +28,6 @@ import org.junit.Test; import java.net.URI; import java.nio.ByteBuffer; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -245,13 +244,13 @@ public class MbusServerTestCase { public void requireThatResponseErrorCodeDoesNotDuplicateReplyError() { assertError(Collections.<Integer>emptyList(), Response.Status.OK); - assertError(Arrays.asList(ErrorCode.APP_FATAL_ERROR), + assertError(List.of(ErrorCode.APP_FATAL_ERROR), Response.Status.BAD_REQUEST); - assertError(Arrays.asList(ErrorCode.FATAL_ERROR), + assertError(List.of(ErrorCode.FATAL_ERROR), Response.Status.BAD_REQUEST, ErrorCode.FATAL_ERROR); - assertError(Arrays.asList(ErrorCode.TRANSIENT_ERROR, ErrorCode.APP_FATAL_ERROR), + assertError(List.of(ErrorCode.TRANSIENT_ERROR, ErrorCode.APP_FATAL_ERROR), Response.Status.BAD_REQUEST, ErrorCode.TRANSIENT_ERROR); - assertError(Arrays.asList(ErrorCode.FATAL_ERROR, ErrorCode.TRANSIENT_ERROR), + assertError(List.of(ErrorCode.FATAL_ERROR, ErrorCode.TRANSIENT_ERROR), Response.Status.BAD_REQUEST, ErrorCode.FATAL_ERROR, ErrorCode.TRANSIENT_ERROR); } diff --git a/container-search/src/main/java/com/yahoo/prelude/fastsearch/FastHit.java b/container-search/src/main/java/com/yahoo/prelude/fastsearch/FastHit.java index b5e5ed9ed8f..7d4e2e8ef0a 100644 --- a/container-search/src/main/java/com/yahoo/prelude/fastsearch/FastHit.java +++ b/container-search/src/main/java/com/yahoo/prelude/fastsearch/FastHit.java @@ -13,7 +13,6 @@ import com.yahoo.data.access.Inspector; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -62,7 +61,7 @@ public class FastHit extends Hit { * that most fields passes through the container with no processing most * of the time. */ - private List<SummaryData> summaries = Collections.emptyList(); + private List<SummaryData> summaries = List.of(); /** Removed field values, which should therefore not be returned if present in summary data */ private Set<String> removedFields = null; @@ -275,7 +274,8 @@ public class FastHit extends Hit { /** Removes all fields of this */ @Override public void clearFields() { - summaries.clear(); + if (!summaries.isEmpty()) + summaries.clear(); if (removedFields != null) removedFields = null; super.clearFields(); @@ -481,7 +481,7 @@ public class FastHit extends Hit { private Set<String> createSet() { if (this.fieldSet != null) return this.fieldSet; - if ( ! hit.hasFields() && hit.summaries.isEmpty()) return Collections.emptySet(); // shortcut + if ( ! hit.hasFields() && hit.summaries.isEmpty()) return Set.of(); // shortcut Set<String> fields = new HashSet<>(); if (hit.hasFields()) diff --git a/container-search/src/main/java/com/yahoo/prelude/query/parser/CustomParser.java b/container-search/src/main/java/com/yahoo/prelude/query/parser/CustomParser.java index 44c0cb45732..520879be928 100644 --- a/container-search/src/main/java/com/yahoo/prelude/query/parser/CustomParser.java +++ b/container-search/src/main/java/com/yahoo/prelude/query/parser/CustomParser.java @@ -6,7 +6,6 @@ import com.yahoo.prelude.IndexFacts; import com.yahoo.prelude.query.Item; import com.yahoo.search.query.parser.Parser; -import java.util.Collections; import java.util.Set; /** @@ -23,7 +22,7 @@ public interface CustomParser extends Parser { Set<String> toSearch, IndexFacts indexFacts, String defaultIndexName) { if (indexFacts == null) indexFacts = new IndexFacts(); - return parse(queryToParse, filterToParse, parsingLanguage, indexFacts.newSession(toSearch, Collections.emptySet()), defaultIndexName); + return parse(queryToParse, filterToParse, parsingLanguage, indexFacts.newSession(toSearch, Set.of()), defaultIndexName); } Item parse(String queryToParse, String filterToParse, Language parsingLanguage, diff --git a/container-search/src/main/java/com/yahoo/prelude/query/parser/Tokenizer.java b/container-search/src/main/java/com/yahoo/prelude/query/parser/Tokenizer.java index 1c0d3ea2ee9..5a42efaaea0 100644 --- a/container-search/src/main/java/com/yahoo/prelude/query/parser/Tokenizer.java +++ b/container-search/src/main/java/com/yahoo/prelude/query/parser/Tokenizer.java @@ -8,8 +8,8 @@ import com.yahoo.prelude.Index; import com.yahoo.prelude.IndexFacts; import com.yahoo.prelude.query.Substring; -import java.util.Collections; import java.util.List; +import java.util.Set; import static com.yahoo.prelude.query.parser.Token.Kind.*; @@ -63,7 +63,7 @@ public final class Tokenizer { * @return a read-only list of tokens. This list can only be used by this thread */ public List<Token> tokenize(String string) { - return tokenize(string, new IndexFacts().newSession(Collections.emptySet(), Collections.emptySet())); + return tokenize(string, new IndexFacts().newSession(Set.of(), Set.of())); } /** diff --git a/container-search/src/main/java/com/yahoo/prelude/semantics/SemanticSearcher.java b/container-search/src/main/java/com/yahoo/prelude/semantics/SemanticSearcher.java index ef453492a5d..e2e0ea90632 100644 --- a/container-search/src/main/java/com/yahoo/prelude/semantics/SemanticSearcher.java +++ b/container-search/src/main/java/com/yahoo/prelude/semantics/SemanticSearcher.java @@ -14,7 +14,6 @@ import com.yahoo.search.result.ErrorMessage; import com.yahoo.search.searchchain.Execution; import com.yahoo.search.searchchain.PhaseNames; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -46,7 +45,7 @@ public class SemanticSearcher extends Searcher { } public SemanticSearcher(RuleBase ... ruleBases) { - this(Arrays.asList(ruleBases)); + this(List.of(ruleBases)); } @Inject diff --git a/container-search/src/main/java/com/yahoo/search/Query.java b/container-search/src/main/java/com/yahoo/search/Query.java index 3227b047984..4ec3fa358d2 100644 --- a/container-search/src/main/java/com/yahoo/search/Query.java +++ b/container-search/src/main/java/com/yahoo/search/Query.java @@ -772,7 +772,7 @@ public class Query extends com.yahoo.processing.Request implements Cloneable { private String serializeSortingAndLimits(boolean includeHitsAndOffset) { StringBuilder insert = new StringBuilder(); - if (getRanking().getSorting() != null && getRanking().getSorting().fieldOrders().size() > 0) { + if (getRanking().getSorting() != null && !getRanking().getSorting().fieldOrders().isEmpty()) { serializeSorting(insert); } if (includeHitsAndOffset) { diff --git a/container-search/src/main/java/com/yahoo/search/dispatch/InvokerResult.java b/container-search/src/main/java/com/yahoo/search/dispatch/InvokerResult.java index 88d6b68a610..9c41c0b930f 100644 --- a/container-search/src/main/java/com/yahoo/search/dispatch/InvokerResult.java +++ b/container-search/src/main/java/com/yahoo/search/dispatch/InvokerResult.java @@ -7,7 +7,6 @@ import com.yahoo.search.Result; import com.yahoo.search.query.Sorting; import java.util.ArrayList; -import java.util.Collections; import java.util.List; /** @@ -22,7 +21,7 @@ public class InvokerResult { public InvokerResult(Result result) { this.result = result; - this.leanHits = Collections.emptyList(); + this.leanHits = List.of(); } public InvokerResult(Query query, int expectedHits) { @@ -54,7 +53,8 @@ public class InvokerResult { fh.setCached(false); result.hits().add(fh); } - leanHits.clear(); + if (!leanHits.isEmpty()) + leanHits.clear(); } } diff --git a/container-search/src/main/java/com/yahoo/search/dispatch/SearchPath.java b/container-search/src/main/java/com/yahoo/search/dispatch/SearchPath.java index 9302ce5b7c6..add562bd5ad 100644 --- a/container-search/src/main/java/com/yahoo/search/dispatch/SearchPath.java +++ b/container-search/src/main/java/com/yahoo/search/dispatch/SearchPath.java @@ -8,7 +8,6 @@ import com.yahoo.search.dispatch.searchcluster.Node; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -163,7 +162,7 @@ public class SearchPath { nodes = parseNodeRange(nodes, ret); } else { if (isWildcard(nodes)) { // any node will be accepted - return Collections.emptyList(); + return List.of(); } nodes = parseNodeNum(nodes, ret); } @@ -231,7 +230,7 @@ public class SearchPath { public Collection<Integer> matches(int max) { if (from >= max) { - return Collections.emptyList(); + return List.of(); } int end = Math.min(to, max); return IntStream.range(from, end).boxed().toList(); diff --git a/container-search/src/main/java/com/yahoo/search/grouping/GroupingQueryParser.java b/container-search/src/main/java/com/yahoo/search/grouping/GroupingQueryParser.java index 3ad610f6ee0..da0b258d6ef 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/GroupingQueryParser.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/GroupingQueryParser.java @@ -15,7 +15,6 @@ import com.yahoo.search.query.Select; import com.yahoo.search.searchchain.Execution; import com.yahoo.search.searchchain.PhaseNames; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; @@ -83,7 +82,7 @@ public class GroupingQueryParser extends Searcher { private List<Continuation> getContinuations(String param) { if (param == null) { - return Collections.emptyList(); + return List.of(); } List<Continuation> ret = new LinkedList<>(); for (String str : param.split(" ")) { diff --git a/container-search/src/main/java/com/yahoo/search/grouping/UniqueGroupingSearcher.java b/container-search/src/main/java/com/yahoo/search/grouping/UniqueGroupingSearcher.java index 6d2b416700a..e319740f741 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/UniqueGroupingSearcher.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/UniqueGroupingSearcher.java @@ -27,7 +27,6 @@ import com.yahoo.search.searchchain.Execution; import com.yahoo.search.searchchain.PhaseNames; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.logging.Logger; @@ -188,7 +187,7 @@ public class UniqueGroupingSearcher extends Searcher { private static List<Hit> getRequestedHits(GroupList resultGroups, int offset, int hits) { List<Hit> receivedHits = getAllHitsFromGroupingResult(resultGroups); if (receivedHits.size() <= offset) { - return Collections.emptyList(); // There weren't any hits as far out as requested. + return List.of(); // There weren't any hits as far out as requested. } int lastRequestedHit = Math.min(offset + hits, receivedHits.size()); return receivedHits.subList(offset, lastRequestedHit); diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/DateFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/DateFunction.java index 3c152f00c66..f911b695853 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/DateFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/DateFunction.java @@ -1,8 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; -import java.util.stream.Collectors; +import java.util.List; /** * This class represents a timestamp-formatter function in a {@link GroupingExpression}. It evaluates to a string on the @@ -23,14 +22,12 @@ public class DateFunction extends FunctionNode { } private DateFunction(String label, Integer level, GroupingExpression exp) { - super("time.date", label, level, Arrays.asList(exp)); + super("time.date", label, level, List.of(exp)); } @Override public DateFunction copy() { - return new DateFunction(getLabel(), - getLevelOrNull(), - getArg(0).copy()); + return new DateFunction(getLabel(), getLevelOrNull(), getArg(0).copy()); } } diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfMonthFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfMonthFunction.java index c9639b4ea71..654e969221b 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfMonthFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfMonthFunction.java @@ -1,8 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; -import java.util.stream.Collectors; +import java.util.List; /** * This class represents a day-of-month timestamp-function in a {@link GroupingExpression}. It evaluates to a long that @@ -23,14 +22,12 @@ public class DayOfMonthFunction extends FunctionNode { } private DayOfMonthFunction(String label, Integer level, GroupingExpression exp) { - super("time.dayofmonth", label, level, Arrays.asList(exp)); + super("time.dayofmonth", label, level, List.of(exp)); } @Override public DayOfMonthFunction copy() { - return new DayOfMonthFunction(getLabel(), - getLevelOrNull(), - getArg(0).copy()); + return new DayOfMonthFunction(getLabel(), getLevelOrNull(), getArg(0).copy()); } } diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfWeekFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfWeekFunction.java index 644f16a4d17..7b91ab34115 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfWeekFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfWeekFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a day-of-week timestamp-function in a {@link GroupingExpression}. It evaluates to a long that @@ -22,14 +22,12 @@ public class DayOfWeekFunction extends FunctionNode { } private DayOfWeekFunction(String label, Integer level, GroupingExpression exp) { - super("time.dayofweek", label, level, Arrays.asList(exp)); + super("time.dayofweek", label, level, List.of(exp)); } @Override public DayOfWeekFunction copy() { - return new DayOfWeekFunction(getLabel(), - getLevelOrNull(), - getArg(0).copy()); + return new DayOfWeekFunction(getLabel(), getLevelOrNull(), getArg(0).copy()); } } diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfYearFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfYearFunction.java index f45a7724794..9f7ff969e49 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfYearFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/DayOfYearFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a day-of-year timestamp-function in a {@link GroupingExpression}. It evaluates to a long that @@ -22,14 +22,12 @@ public class DayOfYearFunction extends FunctionNode { } private DayOfYearFunction(String label, Integer level, GroupingExpression exp) { - super("time.dayofyear", label, level, Arrays.asList(exp)); + super("time.dayofyear", label, level, List.of(exp)); } @Override public DayOfYearFunction copy() { - return new DayOfYearFunction(getLabel(), - getLevelOrNull(), - getArg(0).copy()); + return new DayOfYearFunction(getLabel(), getLevelOrNull(), getArg(0).copy()); } } diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/DebugWaitFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/DebugWaitFunction.java index 482d6fe93ce..1477d125847 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/DebugWaitFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/DebugWaitFunction.java @@ -1,8 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; -import java.util.stream.Collectors; +import java.util.List; /** * This class represents debug_wait function in a {@link GroupingExpression}. For each hit evaluated, @@ -25,7 +24,7 @@ public class DebugWaitFunction extends FunctionNode { } private DebugWaitFunction(String label, Integer level, GroupingExpression arg1, DoubleValue arg2, BooleanValue arg3) { - super("debugwait", label, level, Arrays.asList(arg1, arg2, arg3)); + super("debugwait", label, level, List.of(arg1, arg2, arg3)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/FixedWidthFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/FixedWidthFunction.java index 04f6d155699..6e0b721a584 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/FixedWidthFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/FixedWidthFunction.java @@ -1,7 +1,8 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; + +import java.util.List; /** * This class represents a fixed-width bucket-function in a {@link GroupingExpression}. It maps the input into the given @@ -23,7 +24,7 @@ public class FixedWidthFunction extends FunctionNode { } private FixedWidthFunction(String label, Integer level, GroupingExpression exp, ConstantValue width) { - super("fixedwidth", label, level, Arrays.asList(exp, width)); + super("fixedwidth", label, level, List.of(exp, width)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/FunctionNode.java b/container-search/src/main/java/com/yahoo/search/grouping/request/FunctionNode.java index c1d86ed3059..d2be51c074b 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/FunctionNode.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/FunctionNode.java @@ -66,12 +66,12 @@ public abstract class FunctionNode extends GroupingExpression implements Iterabl @SuppressWarnings("unchecked") protected static <T> List<T> asList(T arg1, T... argN) { - return asList(Arrays.asList(arg1), Arrays.asList(argN)); + return asList(List.of(arg1), List.of(argN)); } @SuppressWarnings("unchecked") protected static <T> List<T> asList(T arg1, T arg2, T... argN) { - return asList(Arrays.asList(arg1, arg2), Arrays.asList(argN)); + return asList(List.of(arg1, arg2), List.of(argN)); } protected static <T> List<T> asList(List<T> foo, List<T> bar) { diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/GroupingOperation.java b/container-search/src/main/java/com/yahoo/search/grouping/request/GroupingOperation.java index b6fc0ffb968..fe49b46fc6f 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/GroupingOperation.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/GroupingOperation.java @@ -537,12 +537,7 @@ public abstract class GroupingOperation extends GroupingNode { } else if (level == 1) { return "single group"; } else { - StringBuilder ret = new StringBuilder(); - for (int i = 1; i < level; ++i) { - ret.append("list of "); - } - ret.append("groups"); - return ret.toString(); + return "list of ".repeat(level - 1) + "groups"; } } @@ -571,8 +566,8 @@ public abstract class GroupingOperation extends GroupingNode { * @throws IllegalArgumentException thrown if the string could not be parsed */ public static List<GroupingOperation> fromStringAsList(String string) { - if (string == null || string.trim().length() == 0) { - return Collections.emptyList(); + if (string == null || string.trim().isEmpty()) { + return List.of(); } GroupingParserInput input = new GroupingParserInput(string); try { diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/HourOfDayFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/HourOfDayFunction.java index b65e1bc2405..95dcf608a95 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/HourOfDayFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/HourOfDayFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents an hour-of-day timestamp-function in a {@link GroupingExpression}. It evaluates to a long that @@ -22,7 +22,7 @@ public class HourOfDayFunction extends FunctionNode { } private HourOfDayFunction(String label, Integer level, GroupingExpression exp) { - super("time.hourofday", label, level, Arrays.asList(exp)); + super("time.hourofday", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathACosFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathACosFunction.java index 70f3515371b..8b6ffc53680 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathACosFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathACosFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathACosFunction extends FunctionNode { } private MathACosFunction(String label, Integer level, GroupingExpression exp) { - super("math.acos", label, level, Arrays.asList(exp)); + super("math.acos", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathACosHFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathACosHFunction.java index 6b31e1cfaff..34570aedc58 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathACosHFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathACosHFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathACosHFunction extends FunctionNode { } private MathACosHFunction(String label, Integer level, GroupingExpression exp) { - super("math.acosh", label, level, Arrays.asList(exp)); + super("math.acosh", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathASinFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathASinFunction.java index cbb99536af1..1fb0b89d0aa 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathASinFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathASinFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathASinFunction extends FunctionNode { } private MathASinFunction(String label, Integer level, GroupingExpression exp) { - super("math.asin", label, level, Arrays.asList(exp)); + super("math.asin", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathASinHFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathASinHFunction.java index 9e159abe90f..e0d290c59dc 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathASinHFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathASinHFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathASinHFunction extends FunctionNode { } private MathASinHFunction(String label, Integer level, GroupingExpression exp) { - super("math.asinh", label, level, Arrays.asList(exp)); + super("math.asinh", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathATanFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathATanFunction.java index a7302769853..50c40a2ad26 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathATanFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathATanFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathATanFunction extends FunctionNode { } private MathATanFunction(String label, Integer level, GroupingExpression exp) { - super("math.atan", label, level, Arrays.asList(exp)); + super("math.atan", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathATanHFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathATanHFunction.java index f33b8883a79..c8b34e36aaa 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathATanHFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathATanHFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathATanHFunction extends FunctionNode { } private MathATanHFunction(String label, Integer level, GroupingExpression exp) { - super("math.atanh", label, level, Arrays.asList(exp)); + super("math.atanh", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathCbrtFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathCbrtFunction.java index 5e4ad8fb20f..ccec1752823 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathCbrtFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathCbrtFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathCbrtFunction extends FunctionNode { } private MathCbrtFunction(String label, Integer level, GroupingExpression exp) { - super("math.cbrt", label, level, Arrays.asList(exp)); + super("math.cbrt", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathCosFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathCosFunction.java index bbf303e0bce..56aaa16c2ae 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathCosFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathCosFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathCosFunction extends FunctionNode { } private MathCosFunction(String label, Integer level, GroupingExpression exp) { - super("math.cos", label, level, Arrays.asList(exp)); + super("math.cos", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathCosHFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathCosHFunction.java index da92164aec5..8d21435ca52 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathCosHFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathCosHFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathCosHFunction extends FunctionNode { } private MathCosHFunction(String label, Integer level, GroupingExpression exp) { - super("math.cosh", label, level, Arrays.asList(exp)); + super("math.cosh", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathExpFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathExpFunction.java index 124b4fdaf40..625c6358081 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathExpFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathExpFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathExpFunction extends FunctionNode { } private MathExpFunction(String label, Integer level, GroupingExpression exp) { - super("math.exp", label, level, Arrays.asList(exp)); + super("math.exp", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathFloorFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathFloorFunction.java index cab480e8ff6..4c775a86b19 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathFloorFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathFloorFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * Represents the math.floor(expression) function @@ -21,7 +21,7 @@ public class MathFloorFunction extends FunctionNode { } private MathFloorFunction(String label, Integer level, GroupingExpression exp) { - super("math.floor", label, level, Arrays.asList(exp)); + super("math.floor", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathFunctions.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathFunctions.java index ec2cb62b062..d76c464a6de 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathFunctions.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathFunctions.java @@ -42,29 +42,28 @@ public abstract class MathFunctions { } } public static FunctionNode newInstance(Function type, GroupingExpression x, GroupingExpression y) { - switch (type) { - case EXP: return new MathExpFunction(x); - case POW: return new MathPowFunction(x, y); - case LOG: return new MathLogFunction(x); - case LOG1P: return new MathLog1pFunction(x); - case LOG10: return new MathLog10Function(x); - case SIN: return new MathSinFunction(x); - case ASIN: return new MathASinFunction(x); - case COS: return new MathCosFunction(x); - case ACOS: return new MathACosFunction(x); - case TAN: return new MathTanFunction(x); - case ATAN: return new MathATanFunction(x); - case SQRT: return new MathSqrtFunction(x); - case SINH: return new MathSinHFunction(x); - case ASINH: return new MathASinHFunction(x); - case COSH: return new MathCosHFunction(x); - case ACOSH: return new MathACosHFunction(x); - case TANH: return new MathTanHFunction(x); - case ATANH: return new MathATanHFunction(x); - case CBRT: return new MathCbrtFunction(x); - case HYPOT: return new MathHypotFunction(x, y); - case FLOOR: return new MathFloorFunction(x); - } - return null; + return switch (type) { + case EXP -> new MathExpFunction(x); + case POW -> new MathPowFunction(x, y); + case LOG -> new MathLogFunction(x); + case LOG1P -> new MathLog1pFunction(x); + case LOG10 -> new MathLog10Function(x); + case SIN -> new MathSinFunction(x); + case ASIN -> new MathASinFunction(x); + case COS -> new MathCosFunction(x); + case ACOS -> new MathACosFunction(x); + case TAN -> new MathTanFunction(x); + case ATAN -> new MathATanFunction(x); + case SQRT -> new MathSqrtFunction(x); + case SINH -> new MathSinHFunction(x); + case ASINH -> new MathASinHFunction(x); + case COSH -> new MathCosHFunction(x); + case ACOSH -> new MathACosHFunction(x); + case TANH -> new MathTanHFunction(x); + case ATANH -> new MathATanHFunction(x); + case CBRT -> new MathCbrtFunction(x); + case HYPOT -> new MathHypotFunction(x, y); + case FLOOR -> new MathFloorFunction(x); + }; } } diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathHypotFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathHypotFunction.java index 9f7cef456cf..fd9e8d6271a 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathHypotFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathHypotFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -20,7 +20,7 @@ public class MathHypotFunction extends FunctionNode { } private MathHypotFunction(String label, Integer level, GroupingExpression x, GroupingExpression y) { - super("math.hypot", label, level, Arrays.asList(x, y)); + super("math.hypot", label, level, List.of(x, y)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathLog10Function.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathLog10Function.java index 8f4a6444bfb..0f05a1909b1 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathLog10Function.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathLog10Function.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathLog10Function extends FunctionNode { } private MathLog10Function(String label, Integer level, GroupingExpression exp) { - super("math.log10", label, level, Arrays.asList(exp)); + super("math.log10", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathLog1pFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathLog1pFunction.java index 35fcbd3f1a6..500edd9f90b 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathLog1pFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathLog1pFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathLog1pFunction extends FunctionNode { } private MathLog1pFunction(String label, Integer level, GroupingExpression exp) { - super("math.log1p", label, level, Arrays.asList(exp)); + super("math.log1p", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathLogFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathLogFunction.java index 5b06998b004..642c3230b3f 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathLogFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathLogFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathLogFunction extends FunctionNode { } private MathLogFunction(String label, Integer level, GroupingExpression exp) { - super("math.log", label, level, Arrays.asList(exp)); + super("math.log", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathPowFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathPowFunction.java index 6f4972c9af0..7dd398f7008 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathPowFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathPowFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -20,7 +20,7 @@ public class MathPowFunction extends FunctionNode { } private MathPowFunction(String label, Integer level, GroupingExpression x, GroupingExpression y) { - super("math.pow", label, level, Arrays.asList(x, y)); + super("math.pow", label, level, List.of(x, y)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathSinFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathSinFunction.java index 8d21fb8e0df..64051cb96e8 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathSinFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathSinFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathSinFunction extends FunctionNode { } private MathSinFunction(String label, Integer level, GroupingExpression exp) { - super("math.sin", label, level, Arrays.asList(exp)); + super("math.sin", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathSinHFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathSinHFunction.java index c9d30a0adec..21295278756 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathSinHFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathSinHFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathSinHFunction extends FunctionNode { } private MathSinHFunction(String label, Integer level, GroupingExpression exp) { - super("math.sinh", label, level, Arrays.asList(exp)); + super("math.sinh", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathSqrtFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathSqrtFunction.java index 268ddaaaf2d..411a3fe30fa 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathSqrtFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathSqrtFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathSqrtFunction extends FunctionNode { } private MathSqrtFunction(String label, Integer level, GroupingExpression exp) { - super("math.sqrt", label, level, Arrays.asList(exp)); + super("math.sqrt", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathTanFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathTanFunction.java index 79267e0ae17..f2a18010258 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathTanFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathTanFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathTanFunction extends FunctionNode { } private MathTanFunction(String label, Integer level, GroupingExpression exp) { - super("math.tan", label, level, Arrays.asList(exp)); + super("math.tan", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MathTanHFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MathTanHFunction.java index e1a83c0b630..5833f0bf887 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MathTanHFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MathTanHFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class MathTanHFunction extends FunctionNode { } private MathTanHFunction(String label, Integer level, GroupingExpression exp) { - super("math.tanh", label, level, Arrays.asList(exp)); + super("math.tanh", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/Md5Function.java b/container-search/src/main/java/com/yahoo/search/grouping/request/Md5Function.java index 720e071aebf..57604677b82 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/Md5Function.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/Md5Function.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents an md5-function in a {@link GroupingExpression}. It evaluates to a long that equals the md5 of @@ -22,7 +22,7 @@ public class Md5Function extends FunctionNode { } private Md5Function(String label, Integer level, GroupingExpression exp, LongValue numBits) { - super("md5", label, level, Arrays.asList(exp, numBits)); + super("md5", label, level, List.of(exp, numBits)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MinuteOfHourFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MinuteOfHourFunction.java index 73484de9e47..67ddd560ab9 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MinuteOfHourFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MinuteOfHourFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a minute-of-hour timestamp-function in a {@link GroupingExpression}. It evaluates to a long @@ -22,7 +22,7 @@ public class MinuteOfHourFunction extends FunctionNode { } private MinuteOfHourFunction(String label, Integer level, GroupingExpression exp) { - super("time.minuteofhour", label, level, Arrays.asList(exp)); + super("time.minuteofhour", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/MonthOfYearFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/MonthOfYearFunction.java index e8dace1e3bf..f9b4aef23f5 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/MonthOfYearFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/MonthOfYearFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a month-of-year timestamp-function in a {@link GroupingExpression}. It evaluates to a long that @@ -22,7 +22,7 @@ public class MonthOfYearFunction extends FunctionNode { } private MonthOfYearFunction(String label, Integer level, GroupingExpression exp) { - super("time.monthofyear", label, level, Arrays.asList(exp)); + super("time.monthofyear", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/NegFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/NegFunction.java index 9f8a8de0266..785d29301e4 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/NegFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/NegFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a negate-function in a {@link GroupingExpression}. It evaluates to a number that equals the @@ -22,7 +22,7 @@ public class NegFunction extends FunctionNode { } private NegFunction(String label, Integer level, GroupingExpression exp) { - super("neg", label, level, Arrays.asList(exp)); + super("neg", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/NormalizeSubjectFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/NormalizeSubjectFunction.java index 1b3f48052a4..c843959249d 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/NormalizeSubjectFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/NormalizeSubjectFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** */ @@ -17,7 +17,7 @@ public class NormalizeSubjectFunction extends FunctionNode { } private NormalizeSubjectFunction(String label, Integer level, GroupingExpression exp) { - super("normalizesubject", label, level, Arrays.asList(exp)); + super("normalizesubject", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/NowFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/NowFunction.java index 7026e726675..a2e2bcd649a 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/NowFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/NowFunction.java @@ -1,8 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; /** * This class represents a now-function in a {@link GroupingExpression}. It evaluates to a long that equals the number @@ -21,7 +20,7 @@ public class NowFunction extends FunctionNode { } private NowFunction(String label, Integer level) { - super("now", label, level, Collections.emptyList()); + super("now", label, level, List.of()); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/ReverseFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/ReverseFunction.java index 483f2494ea9..819dd3601c4 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/ReverseFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/ReverseFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a reverse-function in a {@link GroupingExpression}. It evaluates to a list that equals the list @@ -22,7 +22,7 @@ public class ReverseFunction extends FunctionNode { } private ReverseFunction(String label, Integer level, GroupingExpression exp) { - super("reverse", label, level, Arrays.asList(exp)); + super("reverse", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/SecondOfMinuteFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/SecondOfMinuteFunction.java index a4ef16d50d3..fdcbeefe647 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/SecondOfMinuteFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/SecondOfMinuteFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a second-of-minute timestamp-function in a {@link GroupingExpression}. It evaluates to a long @@ -22,7 +22,7 @@ public class SecondOfMinuteFunction extends FunctionNode { } private SecondOfMinuteFunction(String label, Integer level, GroupingExpression exp) { - super("time.secondofminute", label, level, Arrays.asList(exp)); + super("time.secondofminute", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/SizeFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/SizeFunction.java index 418d1513973..33b910a1119 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/SizeFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/SizeFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a size-function in a {@link GroupingExpression}. It evaluates to a number that equals the @@ -22,7 +22,7 @@ public class SizeFunction extends FunctionNode { } private SizeFunction(String label, Integer level, GroupingExpression exp) { - super("size", label, level, Arrays.asList(exp)); + super("size", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/SortFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/SortFunction.java index 03b9479afda..0acee311b11 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/SortFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/SortFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a sort-function in a {@link GroupingExpression}. It evaluates to a list that equals the list @@ -22,7 +22,7 @@ public class SortFunction extends FunctionNode { } private SortFunction(String label, Integer level, GroupingExpression exp) { - super("sort", label, level, Arrays.asList(exp)); + super("sort", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/StrLenFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/StrLenFunction.java index 28b0f021b26..21679b01170 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/StrLenFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/StrLenFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a strcat-function in a {@link GroupingExpression}. It evaluates to a long that equals the @@ -22,7 +22,7 @@ public class StrLenFunction extends FunctionNode { } private StrLenFunction(String label, Integer level, GroupingExpression exp) { - super("strlen", label, level, Arrays.asList(exp)); + super("strlen", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/ToDoubleFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/ToDoubleFunction.java index 906e7ec18cb..6d05dd69a92 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/ToDoubleFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/ToDoubleFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a todouble-function in a {@link GroupingExpression}. It converts the result of the argument to @@ -22,7 +22,7 @@ public class ToDoubleFunction extends FunctionNode { } private ToDoubleFunction(String label, Integer level, GroupingExpression exp) { - super("todouble", label, level, Arrays.asList(exp)); + super("todouble", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/ToLongFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/ToLongFunction.java index 4c7db38442d..d92cd2814aa 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/ToLongFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/ToLongFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a tolong-function in a {@link GroupingExpression}. It converts the result of the argument to a @@ -22,7 +22,7 @@ public class ToLongFunction extends FunctionNode { } private ToLongFunction(String label, Integer level, GroupingExpression exp) { - super("tolong", label, level, Arrays.asList(exp)); + super("tolong", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/ToRawFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/ToRawFunction.java index 9c0a581fb87..99cf3400bdc 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/ToRawFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/ToRawFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a toraw-function in a {@link GroupingExpression}. It @@ -23,7 +23,7 @@ public class ToRawFunction extends FunctionNode { } private ToRawFunction(String label, Integer level, GroupingExpression exp) { - super("toraw", label, level, Arrays.asList(exp)); + super("toraw", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/ToStringFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/ToStringFunction.java index 0fb891bdce0..b58765c57f0 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/ToStringFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/ToStringFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a tolong-function in a {@link GroupingExpression}. It converts the result of the argument to a @@ -22,7 +22,7 @@ public class ToStringFunction extends FunctionNode { } private ToStringFunction(String label, Integer level, GroupingExpression exp) { - super("tostring", label, level, Arrays.asList(exp)); + super("tostring", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/UcaFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/UcaFunction.java index c5e469f1379..98cb68fbb8c 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/UcaFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/UcaFunction.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -23,7 +22,7 @@ public class UcaFunction extends FunctionNode { * @param locale The locale to used for sorting. */ public UcaFunction(GroupingExpression exp, String locale) { - this(null, null, Arrays.asList(exp, new StringValue(locale))); + this(null, null, List.of(exp, new StringValue(locale))); } /** @@ -34,7 +33,7 @@ public class UcaFunction extends FunctionNode { * @param strength The strength level to use. */ public UcaFunction(GroupingExpression exp, String locale, String strength) { - this(null, null, Arrays.asList(exp, new StringValue(locale), new StringValue(strength))); + this(null, null, List.of(exp, new StringValue(locale), new StringValue(strength))); if ( ! validStrength(strength)) throw new IllegalArgumentException("Not a valid UCA strength: " + strength); } diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/XorBitFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/XorBitFunction.java index 2e0bf25b894..f03bf681e90 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/XorBitFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/XorBitFunction.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -21,7 +20,7 @@ public class XorBitFunction extends FunctionNode { * @param numBits The number of bits of the expression value to xor. */ public XorBitFunction(GroupingExpression exp, int numBits) { - this(null, null, Arrays.asList(exp, new LongValue(numBits))); + this(null, null, List.of(exp, new LongValue(numBits))); } private XorBitFunction(String label, Integer level, List<GroupingExpression> exp) { diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/YearFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/YearFunction.java index 150b54855f3..528a6253ab0 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/YearFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/YearFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * This class represents a year timestamp-function in a {@link GroupingExpression}. It evaluates to a long that equals @@ -22,7 +22,7 @@ public class YearFunction extends FunctionNode { } private YearFunction(String label, Integer level, GroupingExpression exp) { - super("time.year", label, level, Arrays.asList(exp)); + super("time.year", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/ZCurveXFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/ZCurveXFunction.java index 29216e20825..e954e2c24fc 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/ZCurveXFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/ZCurveXFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -19,7 +19,7 @@ public class ZCurveXFunction extends FunctionNode { } private ZCurveXFunction(String label, Integer level, GroupingExpression exp) { - super("zcurve.x", label, level, Arrays.asList(exp)); + super("zcurve.x", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/request/ZCurveYFunction.java b/container-search/src/main/java/com/yahoo/search/grouping/request/ZCurveYFunction.java index 4803f145487..edbc9417a6b 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/request/ZCurveYFunction.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/request/ZCurveYFunction.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.grouping.request; -import java.util.Arrays; +import java.util.List; /** * @author baldersheim @@ -18,7 +18,7 @@ public class ZCurveYFunction extends FunctionNode { } private ZCurveYFunction(String label, Integer level, GroupingExpression exp) { - super("zcurve.y", label, level, Arrays.asList(exp)); + super("zcurve.y", label, level, List.of(exp)); } @Override diff --git a/container-search/src/main/java/com/yahoo/search/grouping/vespa/GroupingExecutor.java b/container-search/src/main/java/com/yahoo/search/grouping/vespa/GroupingExecutor.java index be4f2f786e5..fba9064298c 100644 --- a/container-search/src/main/java/com/yahoo/search/grouping/vespa/GroupingExecutor.java +++ b/container-search/src/main/java/com/yahoo/search/grouping/vespa/GroupingExecutor.java @@ -21,7 +21,6 @@ import com.yahoo.search.searchchain.Execution; import com.yahoo.searchlib.aggregation.Grouping; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; @@ -357,7 +356,7 @@ public class GroupingExecutor extends Searcher { public static List<Grouping> getGroupingList(Query query) { Object obj = query.properties().get(PROP_GROUPINGLIST); if (!(obj instanceof List)) { - return Collections.emptyList(); + return List.of(); } return (List<Grouping>)obj; } diff --git a/container-search/src/main/java/com/yahoo/search/handler/SearchHandler.java b/container-search/src/main/java/com/yahoo/search/handler/SearchHandler.java index c1eff1eec67..c2a5ad0222d 100644 --- a/container-search/src/main/java/com/yahoo/search/handler/SearchHandler.java +++ b/container-search/src/main/java/com/yahoo/search/handler/SearchHandler.java @@ -3,7 +3,6 @@ package com.yahoo.search.handler; import ai.vespa.metrics.ContainerMetrics; import ai.vespa.cloud.ZoneInfo; -import ai.vespa.metrics.ContainerMetrics; import com.yahoo.collections.Tuple2; import com.yahoo.component.ComponentSpecification; import com.yahoo.component.Vtag; @@ -117,7 +116,7 @@ public class SearchHandler extends LoggingRequestHandler { ZoneInfo zoneInfo) { this(metric, threadpool.executor(), queryProfileRegistry, embedders, executionFactory, config.numQueriesToTraceOnDebugAfterConstruction(), - config.hostResponseHeaderKey().equals("") ? Optional.empty() : Optional.of(config.hostResponseHeaderKey()), + config.hostResponseHeaderKey().isEmpty() ? Optional.empty() : Optional.of(config.hostResponseHeaderKey()), zoneInfo); } diff --git a/container-search/src/main/java/com/yahoo/search/pagetemplates/PageTemplateSearcher.java b/container-search/src/main/java/com/yahoo/search/pagetemplates/PageTemplateSearcher.java index e07b290f66e..22bc97b9ca1 100644 --- a/container-search/src/main/java/com/yahoo/search/pagetemplates/PageTemplateSearcher.java +++ b/container-search/src/main/java/com/yahoo/search/pagetemplates/PageTemplateSearcher.java @@ -22,8 +22,6 @@ import com.yahoo.search.result.ErrorMessage; import com.yahoo.search.searchchain.Execution; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -99,7 +97,7 @@ public class PageTemplateSearcher extends Searcher { * @param resolvers the resolvers to use, in addition to the default resolvers */ public PageTemplateSearcher(PageTemplateRegistry templateRegistry, Resolver... resolvers) { - this(templateRegistry, Arrays.asList(resolvers)); + this(templateRegistry, List.of(resolvers)); } private PageTemplateSearcher(PageTemplateRegistry templateRegistry, List<Resolver> resolvers) { @@ -139,13 +137,13 @@ public class PageTemplateSearcher extends Searcher { if (pageIds == null) { String pageIdString = query.properties().getString(pageIdName,"").trim(); if (!pageIdString.isEmpty()) - pageIds = Arrays.asList(pageIdString.split(" ")); + pageIds = List.of(pageIdString.split(" ")); } // If none set, just return the default or null if none if (pageIds == null) { PageElement defaultPage=templateRegistry.getComponent("default"); - return (defaultPage == null ? Collections.<PageElement>emptyList() : Collections.singletonList(defaultPage)); + return (defaultPage == null ? List.of() : List.of(defaultPage)); } // Resolve the id list to page templates diff --git a/container-search/src/main/java/com/yahoo/search/pagetemplates/config/PageTemplateXMLReader.java b/container-search/src/main/java/com/yahoo/search/pagetemplates/config/PageTemplateXMLReader.java index f59124e293e..3ee195bdf55 100644 --- a/container-search/src/main/java/com/yahoo/search/pagetemplates/config/PageTemplateXMLReader.java +++ b/container-search/src/main/java/com/yahoo/search/pagetemplates/config/PageTemplateXMLReader.java @@ -72,7 +72,7 @@ public class PageTemplateXMLReader { File file = new File(fileName); pageReader = new NamedReader(fileName,new FileReader(file)); String firstName = file.getName().substring(0, file.getName().length() - 4); - return read(Collections.singletonList(pageReader), true).getComponent(firstName); + return read(List.of(pageReader), true).getComponent(firstName); } catch (IOException e) { throw new IllegalArgumentException("Could not read the page template '" + fileName + "'", e); @@ -85,7 +85,7 @@ public class PageTemplateXMLReader { private List<File> sortFiles(File dir) { ArrayList<File> files = new ArrayList<>(); - files.addAll(Arrays.asList(dir.listFiles())); + files.addAll(List.of(dir.listFiles())); Collections.sort(files); return files; } @@ -296,7 +296,7 @@ public class PageTemplateXMLReader { if ("item".equals(value.getNodeName())) map.values().add(readPageElements(value)); else - map.values().add(Collections.singletonList(readPageElement(value))); + map.values().add(List.of(readPageElement(value))); } return map; } @@ -311,7 +311,7 @@ public class PageTemplateXMLReader { else if (alternative.getNodeName().equals("include")) // Implicit include choice.alternatives().add(readInclude(alternative)); else // Other implicit - choice.alternatives().add(Collections.singletonList(readPageElement(alternative))); + choice.alternatives().add(List.of(readPageElement(alternative))); } return choice; } @@ -323,7 +323,7 @@ public class PageTemplateXMLReader { if ("alternative".equals(alternative.getNodeName())) // Explicit alternative container source.renderer().alternatives().addAll(readRenderers(XML.children(alternative))); else // Implicit alternative - yes implicit and explicit may be combined - source.renderer().alternatives().addAll(readRenderers(Collections.singletonList(alternative))); + source.renderer().alternatives().addAll(readRenderers(List.of(alternative))); } } } @@ -331,7 +331,7 @@ public class PageTemplateXMLReader { private Map<String,String> readParameters(Element containingElement) { List<Element> parameterElements=XML.getChildren(containingElement,"parameter"); - if (parameterElements.size()==0) return Collections.emptyMap(); // Shortcut + if (parameterElements.size()==0) return Map.of(); // Shortcut Map<String,String> parameters=new LinkedHashMap<>(); for (Element parameter : parameterElements) { diff --git a/container-search/src/main/java/com/yahoo/search/query/Select.java b/container-search/src/main/java/com/yahoo/search/query/Select.java index 32e28dc3ff7..6735a6bd050 100644 --- a/container-search/src/main/java/com/yahoo/search/query/Select.java +++ b/container-search/src/main/java/com/yahoo/search/query/Select.java @@ -10,7 +10,6 @@ import com.yahoo.search.query.profile.types.QueryProfileType; import com.yahoo.search.yql.VespaGroupingStep; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -53,7 +52,7 @@ public class Select implements Cloneable { } public Select(String where, String grouping, Query query) { - this(where, grouping, null, query, Collections.emptyList()); + this(where, grouping, null, query, List.of()); } private Select(String where, String grouping, String groupingExpressionString, Query query, List<GroupingRequest> groupingRequests) { diff --git a/container-search/src/main/java/com/yahoo/search/query/SelectParser.java b/container-search/src/main/java/com/yahoo/search/query/SelectParser.java index 93df7fdfb18..c897afe144c 100644 --- a/container-search/src/main/java/com/yahoo/search/query/SelectParser.java +++ b/container-search/src/main/java/com/yahoo/search/query/SelectParser.java @@ -55,7 +55,6 @@ import com.yahoo.slime.SlimeUtils; import com.yahoo.slime.Type; import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -147,7 +146,7 @@ public class SelectParser implements Parser { private final Normalizer normalizer; private IndexFacts.Session indexFactsSession; - private static final List<String> FUNCTION_CALLS = Arrays.asList(WAND, WEIGHTED_SET, DOT_PRODUCT, GEO_LOCATION, NEAREST_NEIGHBOR, PREDICATE, RANK, WEAK_AND); + private static final List<String> FUNCTION_CALLS = List.of(WAND, WEIGHTED_SET, DOT_PRODUCT, GEO_LOCATION, NEAREST_NEIGHBOR, PREDICATE, RANK, WEAK_AND); public SelectParser(ParserEnvironment environment) { indexFacts = environment.getIndexFacts(); diff --git a/container-search/src/main/java/com/yahoo/search/query/profile/CopyOnWriteContent.java b/container-search/src/main/java/com/yahoo/search/query/profile/CopyOnWriteContent.java index 53f8ccbe6de..3587175b671 100644 --- a/container-search/src/main/java/com/yahoo/search/query/profile/CopyOnWriteContent.java +++ b/container-search/src/main/java/com/yahoo/search/query/profile/CopyOnWriteContent.java @@ -66,7 +66,7 @@ public class CopyOnWriteContent extends FreezableClass implements Cloneable { public void freeze() { // Freeze this if (unmodifiableMap==null) - unmodifiableMap= map!=null ? Collections.unmodifiableMap(map) : Collections.<String, Object>emptyMap(); + unmodifiableMap= map!=null ? Collections.unmodifiableMap(map) : Map.of(); map=null; // just to keep the states simpler // Freeze content @@ -119,7 +119,7 @@ public class CopyOnWriteContent extends FreezableClass implements Cloneable { //------- Content access ------------------------------------------------------- public Map<String,Object> unmodifiableMap() { - if (isEmpty()) return Collections.emptyMap(); + if (isEmpty()) return Map.of(); if (map==null) // in COPYONWRITE or FROZEN state return unmodifiableMap; // In WRITABLE state: Create unmodifiable wrapper if necessary and return it diff --git a/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfile.java b/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfile.java index 1c694417475..d638f57422c 100644 --- a/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfile.java +++ b/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfile.java @@ -121,7 +121,7 @@ public class QueryProfile extends FreezableSimpleComponent implements Cloneable */ public List<QueryProfile> inherited() { if (isFrozen()) return inherited; // Frozen profiles always have an unmodifiable, non-null list - if (inherited == null) return Collections.emptyList(); + if (inherited == null) return List.of(); return Collections.unmodifiableList(inherited); } diff --git a/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileProperties.java b/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileProperties.java index 8778dcc7348..261e42a972d 100644 --- a/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileProperties.java +++ b/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileProperties.java @@ -18,7 +18,6 @@ import com.yahoo.search.query.profile.types.QueryProfileType; import com.yahoo.tensor.Tensor; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -127,7 +126,7 @@ public class QueryProfileProperties extends Properties { name = unalias(name, context); if (context == null) - context = Collections.emptyMap(); + context = Map.of(); if ( ! profile.isOverridable(name, context)) return; @@ -237,7 +236,7 @@ public class QueryProfileProperties extends Properties { context = contextWithZoneInfo(context); path = unalias(path, context); - if (context == null) context = Collections.emptyMap(); + if (context == null) context = Map.of(); Map<String, Object> properties = new HashMap<>(); for (var entry : profile.listValues(path, context, substitution).entrySet()) { diff --git a/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileVariants.java b/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileVariants.java index 0ed6b590227..c9dbfe9d89a 100644 --- a/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileVariants.java +++ b/container-search/src/main/java/com/yahoo/search/query/profile/QueryProfileVariants.java @@ -5,7 +5,6 @@ import com.yahoo.component.provider.Freezable; import com.yahoo.search.query.profile.types.QueryProfileType; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -187,7 +186,7 @@ public class QueryProfileVariants implements Freezable, Cloneable { * @param dimensionBinding the dimension bindings to use in this */ public Object get(String name, QueryProfileType type, boolean allowQueryProfileResult, DimensionBinding dimensionBinding) { - SingleValueQueryProfileVisitor visitor = new SingleValueQueryProfileVisitor(Collections.singletonList(name),allowQueryProfileResult); + SingleValueQueryProfileVisitor visitor = new SingleValueQueryProfileVisitor(List.of(name),allowQueryProfileResult); visitor.enter(""); accept(true, type, visitor, dimensionBinding); visitor.leave(""); @@ -370,7 +369,7 @@ public class QueryProfileVariants implements Freezable, Cloneable { /** Returns the field values (values for various dimensions) for this field as a read-only list (never null) */ public List<FieldValue> asList() { - if (resolutionList == null) return Collections.emptyList(); + if (resolutionList == null) return List.of(); return resolutionList; } diff --git a/container-search/src/main/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfile.java b/container-search/src/main/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfile.java index 4b3c3ede1e9..562d59846d1 100644 --- a/container-search/src/main/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfile.java +++ b/container-search/src/main/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfile.java @@ -9,7 +9,6 @@ import com.yahoo.search.query.profile.QueryProfileProperties; import com.yahoo.search.query.profile.SubstituteString; import com.yahoo.search.query.profile.types.QueryProfileType; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; @@ -102,7 +101,7 @@ public class CompiledQueryProfile extends AbstractComponent implements Cloneable * For example, if {a.d => "a.d-value" ,a.e => "a.e-value", b.d => "b.d-value", then calling listValues("a") * will return {"d" => "a.d-value","e" => "a.e-value"} */ - public final Map<String, Object> listValues(CompoundName prefix) { return listValues(prefix, Collections.emptyMap()); } + public final Map<String, Object> listValues(CompoundName prefix) { return listValues(prefix, Map.of()); } public final Map<String, Object> listValues(String prefix) { return listValues(new CompoundName(prefix)); } /** diff --git a/container-search/src/main/java/com/yahoo/search/query/profile/compiled/DimensionalValue.java b/container-search/src/main/java/com/yahoo/search/query/profile/compiled/DimensionalValue.java index b6fa58628a1..0823989a104 100644 --- a/container-search/src/main/java/com/yahoo/search/query/profile/compiled/DimensionalValue.java +++ b/container-search/src/main/java/com/yahoo/search/query/profile/compiled/DimensionalValue.java @@ -2,18 +2,15 @@ package com.yahoo.search.query.profile.compiled; import com.yahoo.processing.request.CompoundName; -import com.yahoo.search.query.profile.DimensionBinding; import com.yahoo.search.query.profile.SubstituteString; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Set; /** * Contains the values a given key in a DimensionalMap may take for different dimensional contexts. @@ -44,7 +41,7 @@ public class DimensionalValue<VALUE> { /** Returns the value matching this context, or null if none */ public VALUE get(Map<String, String> context) { if (context == null) - context = Collections.emptyMap(); + context = Map.of(); for (BindingSpec spec : bindingSpecs) { if ( ! spec.matches(context)) continue; @@ -156,8 +153,7 @@ public class DimensionalValue<VALUE> { variants.add(binding); // We're combining values for efficiency, so remove incorrect provenance info - if (value instanceof ValueWithSource) { - ValueWithSource v1 = (ValueWithSource)value; + if (value instanceof ValueWithSource v1) { ValueWithSource v2 = (ValueWithSource)newValue; if (v1.source() != null && ! v1.source().equals(v2.source())) @@ -220,14 +216,12 @@ public class DimensionalValue<VALUE> { private VALUE substituteIfRelative(VALUE value, Binding variant, Map<CompoundName, DimensionalValue.Builder<VALUE>> entries) { - if (value instanceof ValueWithSource && ((ValueWithSource)value).value() instanceof SubstituteString) { - ValueWithSource valueWithSource = (ValueWithSource)value; + if (value instanceof ValueWithSource valueWithSource && ((ValueWithSource)value).value() instanceof SubstituteString) { SubstituteString substitute = (SubstituteString)valueWithSource.value(); if (substitute.hasRelative()) { List<SubstituteString.Component> resolvedComponents = new ArrayList<>(substitute.components().size()); for (SubstituteString.Component component : substitute.components()) { - if (component instanceof SubstituteString.RelativePropertyComponent) { - SubstituteString.RelativePropertyComponent relativeComponent = (SubstituteString.RelativePropertyComponent)component; + if (component instanceof SubstituteString.RelativePropertyComponent relativeComponent) { var substituteValues = lookupByLocalName(relativeComponent.fieldName(), entries); if (substituteValues == null) throw new IllegalArgumentException("Could not resolve local substitution '" + @@ -274,8 +268,8 @@ public class DimensionalValue<VALUE> { /** Returns whether this context contains all the keys of this */ public boolean matches(Map<String, String> context) { - for (int i = 0; i < dimensions.length; i++) - if ( ! context.containsKey(dimensions[i])) return false; + for (String dimension : dimensions) + if (!context.containsKey(dimension)) return false; return true; } diff --git a/container-search/src/main/java/com/yahoo/search/query/profile/config/QueryProfileXMLReader.java b/container-search/src/main/java/com/yahoo/search/query/profile/config/QueryProfileXMLReader.java index f2eb76f2367..abb0129eed0 100644 --- a/container-search/src/main/java/com/yahoo/search/query/profile/config/QueryProfileXMLReader.java +++ b/container-search/src/main/java/com/yahoo/search/query/profile/config/QueryProfileXMLReader.java @@ -18,7 +18,6 @@ import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -68,7 +67,7 @@ public class QueryProfileXMLReader { private List<File> sortFiles(File dir) { ArrayList<File> files = new ArrayList<>(); - files.addAll(Arrays.asList(dir.listFiles())); + files.addAll(List.of(dir.listFiles())); Collections.sort(files); return files; } diff --git a/container-search/src/main/java/com/yahoo/search/query/textserialize/item/ItemArguments.java b/container-search/src/main/java/com/yahoo/search/query/textserialize/item/ItemArguments.java index 080f938d61a..e5319b50b4f 100644 --- a/container-search/src/main/java/com/yahoo/search/query/textserialize/item/ItemArguments.java +++ b/container-search/src/main/java/com/yahoo/search/query/textserialize/item/ItemArguments.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.search.query.textserialize.item; -import java.util.Collections; import java.util.List; import java.util.Map; @@ -19,7 +18,7 @@ public class ItemArguments { properties = (Map<?, ?>) ListUtil.first(arguments); children = ListUtil.rest(arguments); } else { - properties = Collections.emptyMap(); + properties = Map.of(); children = arguments; } } diff --git a/container-search/src/main/java/com/yahoo/search/query/textserialize/item/ItemInitializer.java b/container-search/src/main/java/com/yahoo/search/query/textserialize/item/ItemInitializer.java index c8c9f7241d2..7971bc0a30e 100644 --- a/container-search/src/main/java/com/yahoo/search/query/textserialize/item/ItemInitializer.java +++ b/container-search/src/main/java/com/yahoo/search/query/textserialize/item/ItemInitializer.java @@ -7,7 +7,6 @@ import com.yahoo.prelude.query.TaggableItem; import com.yahoo.search.query.textserialize.serializer.DispatchForm; import com.yahoo.search.query.textserialize.serializer.ItemIdMapper; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -116,7 +115,7 @@ public class ItemInitializer { Item connectedItem = taggableItem.getConnectedItem(); if (connectedItem != null) { form.setProperty("connectivity", - Arrays.asList(itemIdMapper.getId(connectedItem), taggableItem.getConnectivity())); + List.of(itemIdMapper.getId(connectedItem), taggableItem.getConnectivity())); } if (taggableItem.hasExplicitSignificance()) { diff --git a/container-search/src/main/java/com/yahoo/search/rendering/RendererRegistry.java b/container-search/src/main/java/com/yahoo/search/rendering/RendererRegistry.java index d62860afcda..74e79475ce6 100644 --- a/container-search/src/main/java/com/yahoo/search/rendering/RendererRegistry.java +++ b/container-search/src/main/java/com/yahoo/search/rendering/RendererRegistry.java @@ -10,7 +10,7 @@ import com.yahoo.search.Result; import com.yahoo.search.pagetemplates.result.PageTemplatesXmlRenderer; import java.util.Collection; -import java.util.Collections; +import java.util.List; import java.util.concurrent.Executor; /** @@ -34,7 +34,7 @@ public final class RendererRegistry extends ComponentRegistry<com.yahoo.processi * Use MoreExecutors.directExecutor(). */ public RendererRegistry(Executor executor) { - this(Collections.emptyList(), executor); + this(List.of(), executor); } /** @@ -111,7 +111,7 @@ public final class RendererRegistry extends ComponentRegistry<com.yahoo.processi private String rendererNames() { StringBuilder r = new StringBuilder(); for (Renderer<Result> c : allComponents()) { - if (r.length() > 0) + if (!r.isEmpty()) r.append(", "); r.append(c.getId().stringValue()); } diff --git a/container-search/src/main/java/com/yahoo/search/rendering/SectionedRenderer.java b/container-search/src/main/java/com/yahoo/search/rendering/SectionedRenderer.java index 6f376042f2d..7bd3ca1174f 100644 --- a/container-search/src/main/java/com/yahoo/search/rendering/SectionedRenderer.java +++ b/container-search/src/main/java/com/yahoo/search/rendering/SectionedRenderer.java @@ -15,7 +15,6 @@ import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.List; @@ -156,7 +155,7 @@ abstract public class SectionedRenderer<WRITER> extends Renderer { } private void renderResultContent(WRITER writer, Result result) throws IOException { - if (result.hits().getError() != null || result.hits().getQuery().errors().size() > 0) { + if (result.hits().getError() != null || !result.hits().getQuery().errors().isEmpty()) { error(writer, asUnmodifiableSearchErrorList(result.hits().getQuery().errors(), result.hits().getError())); } @@ -172,14 +171,14 @@ abstract public class SectionedRenderer<WRITER> extends Renderer { } private Collection<ErrorMessage> asUnmodifiableSearchErrorList(List<com.yahoo.processing.request.ErrorMessage> queryErrors,ErrorMessage resultError) { - if (queryErrors.size() == 0) - return Collections.singletonList(resultError); + if (queryErrors.isEmpty()) + return List.of(resultError); List<ErrorMessage> searchErrors = new ArrayList<>(queryErrors.size() + (resultError != null ? 1 :0) ); - for (int i=0; i<queryErrors.size(); i++) - searchErrors.add(ErrorMessage.from(queryErrors.get(i))); + for (com.yahoo.processing.request.ErrorMessage queryError : queryErrors) + searchErrors.add(ErrorMessage.from(queryError)); if (resultError != null) searchErrors.add(resultError); - return Collections.unmodifiableCollection(searchErrors); + return List.copyOf(searchErrors); } private void renderHitGroup(WRITER writer, HitGroup hitGroup) throws IOException { diff --git a/container-search/src/main/java/com/yahoo/search/result/FeatureData.java b/container-search/src/main/java/com/yahoo/search/result/FeatureData.java index 0f26ecdcce7..55a4c6c11f2 100644 --- a/container-search/src/main/java/com/yahoo/search/result/FeatureData.java +++ b/container-search/src/main/java/com/yahoo/search/result/FeatureData.java @@ -14,7 +14,6 @@ import com.yahoo.tensor.serialization.TypedBinaryFormat; import static com.yahoo.searchlib.rankingexpression.Reference.wrapInRankingExpression; import java.nio.charset.StandardCharsets; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -150,7 +149,7 @@ public class FeatureData implements Inspectable, JsonProducer { /** Returns the names of the features available in this */ public Set<String> featureNames() { - if (this == empty) return Collections.emptySet(); + if (this == empty) return Set.of(); if (featureNames != null) return featureNames; featureNames = new HashSet<>(); diff --git a/container-search/src/main/java/com/yahoo/search/result/Hit.java b/container-search/src/main/java/com/yahoo/search/result/Hit.java index d81880cc548..4d3b8bb0884 100644 --- a/container-search/src/main/java/com/yahoo/search/result/Hit.java +++ b/container-search/src/main/java/com/yahoo/search/result/Hit.java @@ -333,6 +333,7 @@ public class Hit extends ListenableFreezableClass implements Data, Comparable<Hi */ public void setFillable() { if (filled == null) { + //TODO Should have used Set.of(), but it checks that contains is not called with null filled = Collections.emptySet(); unmodifiableFilled = filled; } @@ -347,6 +348,7 @@ public class Hit extends ListenableFreezableClass implements Data, Comparable<Hi */ public void setFilled(String summaryClass) { if (filled == null || filled.isEmpty()) { + //TODO Should have used Set.of(), but it checks that contains is not called with null filled = Collections.singleton(summaryClass); unmodifiableFilled = filled; } else if (filled.size() == 1) { @@ -483,7 +485,7 @@ public class Hit extends ListenableFreezableClass implements Data, Comparable<Hi private Map<String, Object> getUnmodifiableFieldMap() { if (unmodifiableFieldMap == null) { if (fields == null) { - return Collections.emptyMap(); + return Map.of(); } else { unmodifiableFieldMap = Collections.unmodifiableMap(fields); } @@ -574,12 +576,12 @@ public class Hit extends ListenableFreezableClass implements Data, Comparable<Hi /** Attach some data to this hit for this searcher */ public void setSearcherSpecificMetaData(Searcher searcher, Object data) { if (searcherSpecificMetaData == null) { - searcherSpecificMetaData = Collections.singletonMap(searcher, data); + if (data != null) + searcherSpecificMetaData = Map.of(searcher, data); } else { if (searcherSpecificMetaData.size() == 1) { - Object tmp = searcherSpecificMetaData.get(searcher); - if (tmp != null) { - searcherSpecificMetaData = Collections.singletonMap(searcher, data); + if (searcherSpecificMetaData.containsKey(searcher)) { + searcherSpecificMetaData = (data != null) ? Map.of(searcher, data) : null; } else { searcherSpecificMetaData = new TreeMap<>(searcherSpecificMetaData); searcherSpecificMetaData.put(searcher, data); diff --git a/container-search/src/main/java/com/yahoo/search/result/HitGroup.java b/container-search/src/main/java/com/yahoo/search/result/HitGroup.java index 51c0caf38a9..be31b91a304 100644 --- a/container-search/src/main/java/com/yahoo/search/result/HitGroup.java +++ b/container-search/src/main/java/com/yahoo/search/result/HitGroup.java @@ -718,6 +718,7 @@ public class HitGroup extends Hit implements DataList<Hit>, Cloneable, Iterable< if (hitFilled.isEmpty()) { filled = null; } else if (hitFilled.size() == 1) { + //TODO Avoid needing set that allows null .... filled = Collections.singleton(hitFilled.iterator().next()); } else { filled = new HashSet<>(hitFilled); @@ -799,6 +800,7 @@ public class HitGroup extends Hit implements DataList<Hit>, Cloneable, Iterable< analyzeHit(hit); Set<String> hitFilled = hit.getFilled(); if (hitFilled != null) { + //TODO Avoid needing set that allows null .... filled = (hitFilled.size() == 1) ? Collections.singleton(hitFilled.iterator().next()) : hitFilled.isEmpty() ? null : new HashSet<>(hitFilled); diff --git a/container-search/src/main/java/com/yahoo/search/searchchain/SearchChain.java b/container-search/src/main/java/com/yahoo/search/searchchain/SearchChain.java index 27d7430a0d9..9698735fb52 100644 --- a/container-search/src/main/java/com/yahoo/search/searchchain/SearchChain.java +++ b/container-search/src/main/java/com/yahoo/search/searchchain/SearchChain.java @@ -6,7 +6,6 @@ import com.yahoo.component.chain.Chain; import com.yahoo.component.chain.Phase; import com.yahoo.search.Searcher; -import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -33,7 +32,7 @@ public class SearchChain extends Chain<Searcher> { } public SearchChain(ComponentId id, Searcher... searchers) { - this(id, Arrays.asList(searchers)); + this(id, List.of(searchers)); } public SearchChain(ComponentId id, Collection<Searcher> searchers) { diff --git a/container-search/src/main/java/com/yahoo/search/searchchain/model/VespaSearchers.java b/container-search/src/main/java/com/yahoo/search/searchchain/model/VespaSearchers.java index f21ea506fde..69a1f8ec6cb 100644 --- a/container-search/src/main/java/com/yahoo/search/searchchain/model/VespaSearchers.java +++ b/container-search/src/main/java/com/yahoo/search/searchchain/model/VespaSearchers.java @@ -11,7 +11,6 @@ import com.yahoo.search.searchchain.model.federation.FederationSearcherModel; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -61,7 +60,7 @@ public class VespaSearchers { private static FederationSearcherModel federationSearcherModel() { return new FederationSearcherModel(new ComponentSpecification("federation"), Dependencies.emptyDependencies(), - Collections.emptyList(), + List.of(), true); } diff --git a/container-search/src/main/java/com/yahoo/search/yql/YqlParser.java b/container-search/src/main/java/com/yahoo/search/yql/YqlParser.java index 7ae02c18e7a..e66cac5766c 100644 --- a/container-search/src/main/java/com/yahoo/search/yql/YqlParser.java +++ b/container-search/src/main/java/com/yahoo/search/yql/YqlParser.java @@ -913,7 +913,7 @@ public class YqlParser implements Parser { GroupingOperation groupingOperation = GroupingOperation.fromString(groupingAst.getArgument(0)); VespaGroupingStep groupingStep = new VespaGroupingStep(groupingOperation); List<Object> continuations = getAnnotation(groupingAst, "continuations", List.class, - Collections.emptyList(), "grouping continuations"); + List.of(), "grouping continuations"); for (Object continuation : continuations) { groupingStep.continuations().add(Continuation.fromString(dereference(continuation))); @@ -1614,7 +1614,7 @@ public class YqlParser implements Parser { { Item leaf = (Item) out; Map<?, ?> itemAnnotations = getAnnotation(ast, ANNOTATIONS, - Map.class, Collections.emptyMap(), "item annotation map"); + Map.class, Map.of(), "item annotation map"); for (Map.Entry<?, ?> entry : itemAnnotations.entrySet()) { Preconditions.checkArgument(entry.getKey() instanceof String, "Expected String annotation key, got %s.", entry.getKey().getClass()); diff --git a/container-search/src/main/java/com/yahoo/text/interpretation/Annotations.java b/container-search/src/main/java/com/yahoo/text/interpretation/Annotations.java index 561d2bf34d0..c957432a957 100644 --- a/container-search/src/main/java/com/yahoo/text/interpretation/Annotations.java +++ b/container-search/src/main/java/com/yahoo/text/interpretation/Annotations.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.text.interpretation; -import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -28,7 +27,7 @@ public class Annotations { public Map<String,Object> getMap() { if (annotations == null) { - return Collections.emptyMap(); + return Map.of(); } else { return annotations; } diff --git a/container-search/src/main/java/com/yahoo/vespa/streamingvisitors/QueryEncoder.java b/container-search/src/main/java/com/yahoo/vespa/streamingvisitors/QueryEncoder.java index 112c3669133..c0ded6a4c39 100644 --- a/container-search/src/main/java/com/yahoo/vespa/streamingvisitors/QueryEncoder.java +++ b/container-search/src/main/java/com/yahoo/vespa/streamingvisitors/QueryEncoder.java @@ -8,7 +8,6 @@ import com.yahoo.search.Query; import com.yahoo.search.dispatch.rpc.ProtobufSerialization; import java.nio.ByteBuffer; -import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -68,10 +67,10 @@ class QueryEncoder { return cacheSettingMap; } if (query.getGroupingSessionCache()) - return Collections.singletonMap("grouping", true); + return Map.of("grouping", true); if (query.getRanking().getQueryCache()) - return Collections.singletonMap("query", true); - return Collections.emptyMap(); + return Map.of("query", true); + return Map.of(); } private static Map<String, String> createModelMap(Query query) { diff --git a/container-search/src/test/java/com/yahoo/container/core/config/testutil/MockOsgiWrapper.java b/container-search/src/test/java/com/yahoo/container/core/config/testutil/MockOsgiWrapper.java index 150a2a5d78a..ebe4ccdd2ba 100644 --- a/container-search/src/test/java/com/yahoo/container/core/config/testutil/MockOsgiWrapper.java +++ b/container-search/src/test/java/com/yahoo/container/core/config/testutil/MockOsgiWrapper.java @@ -8,8 +8,6 @@ import org.osgi.framework.Bundle; import java.util.Collection; import java.util.List; -import static java.util.Collections.emptyList; - /** * @author gjoranv */ @@ -22,7 +20,7 @@ public class MockOsgiWrapper implements OsgiWrapper { @Override public List<Bundle> getCurrentBundles() { - return emptyList(); + return List.of(); } @Override @@ -32,7 +30,7 @@ public class MockOsgiWrapper implements OsgiWrapper { @Override public List<Bundle> install(String absolutePath) { - return emptyList(); + return List.of(); } @Override diff --git a/container-search/src/test/java/com/yahoo/prelude/fastsearch/IndexedBackendTestCase.java b/container-search/src/test/java/com/yahoo/prelude/fastsearch/IndexedBackendTestCase.java index 58427bee30a..3cefeeabdcf 100644 --- a/container-search/src/test/java/com/yahoo/prelude/fastsearch/IndexedBackendTestCase.java +++ b/container-search/src/test/java/com/yahoo/prelude/fastsearch/IndexedBackendTestCase.java @@ -20,7 +20,6 @@ import com.yahoo.search.schema.Schema; import com.yahoo.search.schema.SchemaInfo; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; @@ -98,7 +97,7 @@ public class IndexedBackendTestCase { var backend = new IndexedBackend(new ClusterParams(CLUSTER_PARAMS.getSearcherName(), CLUSTER_PARAMS.getServerId(), CLUSTER_PARAMS.getDefaultSummary(), CLUSTER_PARAMS.getDocumentdbInfoConfig(), new SchemaInfo(List.of(schema.build()), List.of())), - MockDispatcher.create(Collections.singletonList(new Node(CLUSTER, 0, "host0", 0)))); + MockDispatcher.create(List.of(new Node(CLUSTER, 0, "host0", 0)))); Query q = new Query("?query=foo"); Result result = doSearch(backend, q, 0, 10); assertFalse(backend.summaryNeedsQuery(q)); diff --git a/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java index f8fe0c92020..d2d5d124297 100644 --- a/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java +++ b/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java @@ -4,7 +4,7 @@ package com.yahoo.prelude.query; import static org.junit.jupiter.api.Assertions.*; import java.nio.ByteBuffer; -import java.util.Arrays; +import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.regex.PatternSyntaxException; @@ -211,7 +211,7 @@ public class ItemsCommonStuffTestCase { w.setConnectivity(v, 1.0); String expected = "puppy"; String expected2 = "kvalp"; - EquivItem e = new EquivItem(w, Arrays.asList(expected, expected2)); + EquivItem e = new EquivItem(w, List.of(expected, expected2)); assertEquals(1.0, e.getConnectivity(), 1e-9); assertSame(v, e.getConnectedItem()); assertEquals(expected, ((WordItem) e.getItem(1)).getWord()); diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java index fbede4613da..0b12cf99396 100644 --- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java +++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java @@ -13,8 +13,8 @@ import com.yahoo.prelude.query.parser.Tokenizer; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Collections; import java.util.List; +import java.util.Set; import static com.yahoo.prelude.query.parser.Token.Kind.COLON; import static com.yahoo.prelude.query.parser.Token.Kind.COMMA; @@ -283,7 +283,7 @@ public class TokenizerTestCase { sd.addIndex(index2); IndexFacts facts = new IndexFacts(new IndexModel(sd)); - IndexFacts.Session session = facts.newSession(Collections.emptySet(), Collections.emptySet()); + IndexFacts.Session session = facts.newSession(Set.of(), Set.of()); Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics()); List<?> tokens = tokenizer.tokenize("normal a:b (normal testexact1:/,%#%&+-+ ) testexact2:ho_/&%&/()/aa*::*& b:c", "default", session); // tokenizer.print(); @@ -328,7 +328,7 @@ public class TokenizerTestCase { IndexFacts facts = new IndexFacts(new IndexModel(sd)); Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics()); - IndexFacts.Session session = facts.newSession(Collections.emptySet(), Collections.emptySet()); + IndexFacts.Session session = facts.newSession(Set.of(), Set.of()); List<?> tokens = tokenizer.tokenize("normal a:b (normal testexact1:/,%#%&+-+ ) testexact2:ho_/&%&/()/aa*::*&", session); assertEquals(new Token(WORD, "normal"), tokens.get(0)); assertEquals(new Token(SPACE, " "), tokens.get(1)); @@ -365,7 +365,7 @@ public class TokenizerTestCase { IndexFacts facts = new IndexFacts(new IndexModel(sd)); Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics()); - IndexFacts.Session session = facts.newSession(Collections.emptySet(), Collections.emptySet()); + IndexFacts.Session session = facts.newSession(Set.of(), Set.of()); List<?> tokens = tokenizer.tokenize("normal a:b (normal testexact1:/,%#%&+-+ ) testexact2:ho_/&%&/()/aa*::*", session); assertEquals(new Token(WORD, "normal"), tokens.get(0)); assertEquals(new Token(SPACE, " "), tokens.get(1)); @@ -402,7 +402,7 @@ public class TokenizerTestCase { IndexFacts facts = new IndexFacts(new IndexModel(sd)); Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics()); - IndexFacts.Session session = facts.newSession(Collections.emptySet(), Collections.emptySet()); + IndexFacts.Session session = facts.newSession(Set.of(), Set.of()); List<?> tokens = tokenizer.tokenize("normal a:b (normal testexact1:!/%#%&+-+ ) testexact2:ho_/&%&/()/aa*::*&b:", session); assertEquals(new Token(WORD, "normal"), tokens.get(0)); assertEquals(new Token(SPACE, " "), tokens.get(1)); @@ -439,7 +439,7 @@ public class TokenizerTestCase { sd.addIndex(index2); IndexFacts indexFacts = new IndexFacts(new IndexModel(sd)); - IndexFacts.Session facts = indexFacts.newSession(Collections.emptySet(), Collections.emptySet()); + IndexFacts.Session facts = indexFacts.newSession(Set.of(), Set.of()); Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics()); List<?> tokens = tokenizer.tokenize("normal a:b (normal testexact1:foo) testexact2:bar", facts); diff --git a/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java index f5dc598485a..475b8ddc02a 100644 --- a/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java +++ b/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java @@ -5,9 +5,9 @@ import java.io.BufferedReader; import java.io.FileReader; import java.nio.ByteBuffer; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import com.yahoo.prelude.query.Item; @@ -29,7 +29,7 @@ public class TextualQueryRepresentationTestCase { example; } - private class MockItem extends Item { + private static class MockItem extends Item { private final String name; @Override @@ -71,7 +71,7 @@ public class TextualQueryRepresentationTestCase { Map<Integer, Object> exampleMap = new HashMap<>(); exampleMap.put(1, "one"); exampleMap.put(2, "two"); - exampleMap.put(3, Arrays.asList('x', 'y', 'z')); + exampleMap.put(3, List.of('x', 'y', 'z')); discloser.addProperty("01", null); discloser.addProperty("02", "a string."); @@ -79,9 +79,9 @@ public class TextualQueryRepresentationTestCase { discloser.addProperty("04", true); discloser.addProperty("05", ExampleEnum.example); discloser.addProperty("06", new int[]{1, 2, 3}); - discloser.addProperty("07", Arrays.asList('x', 'y', 'z')); + discloser.addProperty("07", List.of('x', 'y', 'z')); discloser.addProperty("08", new ArrayList()); - discloser.addProperty("09", new HashSet(Arrays.asList(1, 2, 3))); + discloser.addProperty("09", new HashSet(List.of(1, 2, 3))); discloser.addProperty("10", exampleMap); discloser.setValue("example-value: \"12\""); diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java index 4ce1cd5a10d..4b7c7e592cf 100644 --- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java +++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.prelude.searcher.test; -import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -286,7 +285,7 @@ public class BlendingSearcherTestCase { assertEquals(1, cr.getConcreteHitCount()); com.yahoo.search.result.ErrorHit errorHit = cr.hits().getErrorHit(); Iterator errorIterator = errorHit.errorIterator(); - List<String> errorList = Arrays.asList("Source 'a': No backends in service. Try later", + List<String> errorList = List.of("Source 'a': No backends in service. Try later", "Source 'b': 2: Request too large"); String a = errorIterator.next().toString(); assertTrue(errorList.contains(a), a); diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java index 8ced7d3895e..152056dfb72 100644 --- a/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java +++ b/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java @@ -28,11 +28,10 @@ import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.stream.StreamSupport; @@ -203,10 +202,10 @@ public class InterleavedSearchInvokerTest { } private static final double DELTA = 0.000000000001; - private static final List<Double> A5 = Arrays.asList(11.0,8.5,7.5,3.0,2.0); - private static final List<Double> B5 = Arrays.asList(9.0,8.0,7.0,6.0,1.0); - private static final List<Double> A5Aux = Arrays.asList(-1.0,11.0,8.5,7.5,-7.0,3.0,2.0); - private static final List<Double> B5Aux = Arrays.asList(9.0,8.0,-3.0,7.0,6.0,1.0, -1.0); + private static final List<Double> A5 = List.of(11.0,8.5,7.5,3.0,2.0); + private static final List<Double> B5 = List.of(9.0,8.0,7.0,6.0,1.0); + private static final List<Double> A5Aux = List.of(-1.0,11.0,8.5,7.5,-7.0,3.0,2.0); + private static final List<Double> B5Aux = List.of(9.0,8.0,-3.0,7.0,6.0,1.0, -1.0); private void validateThatTopKProbabilityOverrideTakesEffect(Double topKProbability, int expectedK, Group group) throws IOException { try (InterleavedSearchInvoker invoker = createInterLeavedTestInvoker(A5, B5, group)) { @@ -356,7 +355,7 @@ public class InterleavedSearchInvokerTest { .addAggregationResult(new MinAggregationResult().setMin(new IntegerResultNode(6)).setTag(3)))); invokers.add(new MockInvoker(0).setHits(List.of(new GroupingListHit(List.of(grouping2))))); - try (InterleavedSearchInvoker invoker = new InterleavedSearchInvoker(Timer.monotonic, invokers, hitEstimator, dispatchConfig, new Group(0, List.of()), Collections.emptySet())) { + try (InterleavedSearchInvoker invoker = new InterleavedSearchInvoker(Timer.monotonic, invokers, hitEstimator, dispatchConfig, new Group(0, List.of()), Set.of())) { invoker.responseAvailable(invokers.get(0)); invoker.responseAvailable(invokers.get(1)); Result result = invoker.search(query); @@ -373,7 +372,7 @@ public class InterleavedSearchInvokerTest { List<SearchInvoker> invokers = new ArrayList<>(); invokers.add(createInvoker(a, 0)); invokers.add(createInvoker(b, 1)); - InterleavedSearchInvoker invoker = new InterleavedSearchInvoker(Timer.monotonic, invokers, hitEstimator, dispatchConfig, group, Collections.emptySet()); + InterleavedSearchInvoker invoker = new InterleavedSearchInvoker(Timer.monotonic, invokers, hitEstimator, dispatchConfig, group, Set.of()); invoker.responseAvailable(invokers.get(0)); invoker.responseAvailable(invokers.get(1)); return invoker; diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java index 8b6b3c4d13a..3053fe7d730 100644 --- a/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java +++ b/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java @@ -10,7 +10,6 @@ import org.junit.jupiter.api.Test; import java.time.Duration; import java.time.Instant; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -238,7 +237,7 @@ public class LoadBalancerTest { } private GroupStatus newGroupStatus(int id) { - Group dummyGroup = new Group(id, Collections.emptyList()) { + Group dummyGroup = new Group(id, List.of()) { @Override public boolean hasSufficientCoverage() { return true; diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java index be8f99a4ef4..6459d67480d 100644 --- a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java +++ b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java @@ -14,7 +14,6 @@ import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry; import com.yahoo.search.query.profile.config.QueryProfileXMLReader; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; import java.util.Set; @@ -66,7 +65,7 @@ public class ProtobufSerializationTest { builder.setTimeout(0); var hit = new FastHit(); hit.setGlobalId(new GlobalId(IdString.createIdString("id:ns:type::id")).getRawId()); - var bytes = ProtobufSerialization.serializeDocsumRequest(builder, Collections.singletonList(hit)); + var bytes = ProtobufSerialization.serializeDocsumRequest(builder, List.of(hit)); assertEquals(56, bytes.length); } diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java index 5223eb0b06b..1b36c2b8151 100644 --- a/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java +++ b/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java @@ -12,7 +12,6 @@ import com.yahoo.search.result.ErrorMessage; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -46,7 +45,7 @@ public class SearchClusterTest { List<AtomicInteger> pingCounts; State(String clusterId, int nodesPergroup, String ... nodeNames) { - this(clusterId, nodesPergroup, Arrays.asList(nodeNames)); + this(clusterId, nodesPergroup, List.of(nodeNames)); } State(String clusterId, int nodesPerGroup, List<String> nodeNames) { diff --git a/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java b/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java index 4d3e3c18e0b..1ac6dcbe1b6 100644 --- a/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java +++ b/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java @@ -23,7 +23,6 @@ import com.yahoo.search.searchchain.model.federation.FederationOptions; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -339,7 +338,7 @@ public class FederationSearcherTest { @Override public Collection<FederationTarget<String>> getTargets(Query query, ChainRegistry<Searcher> searcherChainRegistry) { - return Arrays.asList(createTarget(1), createTarget(2)); + return List.of(createTarget(1), createTarget(2)); } private FederationTarget<String> createTarget(int number) { diff --git a/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java index 76a1a71f6ed..540ecfa6e12 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java @@ -9,7 +9,6 @@ import com.yahoo.search.searchchain.Execution; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; import java.util.TimeZone; @@ -22,12 +21,12 @@ public class GroupingQueryParserTestCase { @Test void requireThatNoRequestIsSkipped() { - assertEquals(Collections.emptyList(), executeQuery(null, null, null)); + assertEquals(List.of(), executeQuery(null, null, null)); } @Test void requireThatEmptyRequestIsSkipped() { - assertEquals(Collections.emptyList(), executeQuery("", null, null)); + assertEquals(List.of(), executeQuery("", null, null)); } @Test diff --git a/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java index 97eed95946f..3af2614b6fb 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java @@ -11,8 +11,6 @@ import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -34,7 +32,7 @@ public class GroupingRequestTestCase { } }; req.continuations().add(foo); - assertEquals(Arrays.asList(foo), req.continuations()); + assertEquals(List.of(foo), req.continuations()); req.continuations().clear(); assertTrue(req.continuations().isEmpty()); @@ -121,7 +119,7 @@ public class GroupingRequestTestCase { @Test void requireThatGetRequestsReturnsAllRequests() { Query query = new Query(); - assertEquals(Collections.emptyList(), query.getSelect().getGrouping()); + assertEquals(List.of(), query.getSelect().getGrouping()); GroupingRequest foo = GroupingRequest.newInstance(query); assertEquals(List.of(foo), query.getSelect().getGrouping()); diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java index 800faa4c0d1..19fd4234cfc 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java @@ -4,7 +4,6 @@ package com.yahoo.search.grouping.request; import org.junit.jupiter.api.Test; import java.text.ChoiceFormat; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -72,30 +71,30 @@ public class BucketResolverTestCase { @Test void testBucketType() { - checkPushFail(Arrays.asList((ConstantValue) new StringValue("a"), new LongValue(1L)), + checkPushFail(List.of((ConstantValue) new StringValue("a"), new LongValue(1L)), "Bucket type mismatch, expected 'StringValue' got 'LongValue'."); - checkPushFail(Arrays.asList((ConstantValue) new StringValue("a"), new DoubleValue(1.0)), + checkPushFail(List.of((ConstantValue) new StringValue("a"), new DoubleValue(1.0)), "Bucket type mismatch, expected 'StringValue' got 'DoubleValue'."); - checkPushFail(Arrays.asList((ConstantValue) new LongValue(1L), new StringValue("a")), + checkPushFail(List.of((ConstantValue) new LongValue(1L), new StringValue("a")), "Bucket type mismatch, expected 'LongValue' got 'StringValue'."); - checkPushFail(Arrays.asList((ConstantValue) new LongValue(1L), new DoubleValue(1.0)), + checkPushFail(List.of((ConstantValue) new LongValue(1L), new DoubleValue(1.0)), "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'."); - checkPushFail(Arrays.asList((ConstantValue) new DoubleValue(1.0), new StringValue("a")), + checkPushFail(List.of((ConstantValue) new DoubleValue(1.0), new StringValue("a")), "Bucket type mismatch, expected 'DoubleValue' got 'StringValue'."); - checkPushFail(Arrays.asList((ConstantValue) new DoubleValue(1.0), new LongValue(1L)), + checkPushFail(List.of((ConstantValue) new DoubleValue(1.0), new LongValue(1L)), "Bucket type mismatch, expected 'DoubleValue' got 'LongValue'."); - checkPushFail(Arrays.asList((ConstantValue) new InfiniteValue(new Infinite(true)), new InfiniteValue(new Infinite(false))), + checkPushFail(List.of((ConstantValue) new InfiniteValue(new Infinite(true)), new InfiniteValue(new Infinite(false))), "Bucket type mismatch, cannot both be infinity."); } @Test void testBucketOrder() { - checkPushFail(Arrays.asList((ConstantValue) new LongValue(2L), new LongValue(1L)), + checkPushFail(List.of((ConstantValue) new LongValue(2L), new LongValue(1L)), "Bucket to-value can not be less than from-value."); - checkPushFail(Arrays.asList((ConstantValue) new DoubleValue(2.0), new DoubleValue(1.0)), + checkPushFail(List.of((ConstantValue) new DoubleValue(2.0), new DoubleValue(1.0)), "Bucket to-value can not be less than from-value."); - checkPushFail(Arrays.asList((ConstantValue) new StringValue("b"), new StringValue("a")), + checkPushFail(List.of((ConstantValue) new StringValue("b"), new StringValue("a")), "Bucket to-value can not be less than from-value."); } diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java index 85f19e0b19a..daed437e93f 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java @@ -9,6 +9,7 @@ import static org.junit.jupiter.api.Assertions.*; * @author Einar M R Rosenvinge */ public class MathFunctionsTestCase { + private static final DoubleValue ZERO = new DoubleValue(0.0); @Test void testMathFunctions() { @@ -37,27 +38,27 @@ public class MathFunctionsTestCase { assertSame(MathFunctions.Function.create(19), MathFunctions.Function.HYPOT); assertSame(MathFunctions.Function.create(20), MathFunctions.Function.FLOOR); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.EXP, null, null) instanceof MathExpFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.POW, null, null) instanceof MathPowFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.LOG, null, null) instanceof MathLogFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.LOG1P, null, null) instanceof MathLog1pFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.LOG10, null, null) instanceof MathLog10Function); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.SIN, null, null) instanceof MathSinFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.ASIN, null, null) instanceof MathASinFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.COS, null, null) instanceof MathCosFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.ACOS, null, null) instanceof MathACosFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.TAN, null, null) instanceof MathTanFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.ATAN, null, null) instanceof MathATanFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.SQRT, null, null) instanceof MathSqrtFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.SINH, null, null) instanceof MathSinHFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.ASINH, null, null) instanceof MathASinHFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.COSH, null, null) instanceof MathCosHFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.ACOSH, null, null) instanceof MathACosHFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.TANH, null, null) instanceof MathTanHFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.ATANH, null, null) instanceof MathATanHFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.CBRT, null, null) instanceof MathCbrtFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.HYPOT, null, null) instanceof MathHypotFunction); - assertTrue(MathFunctions.newInstance(MathFunctions.Function.FLOOR, null, null) instanceof MathFloorFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.EXP, ZERO, ZERO) instanceof MathExpFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.POW, ZERO, ZERO) instanceof MathPowFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.LOG, ZERO, ZERO) instanceof MathLogFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.LOG1P, ZERO, ZERO) instanceof MathLog1pFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.LOG10, ZERO, ZERO) instanceof MathLog10Function); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.SIN, ZERO, ZERO) instanceof MathSinFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.ASIN, ZERO, ZERO) instanceof MathASinFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.COS, ZERO, ZERO) instanceof MathCosFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.ACOS, ZERO, ZERO) instanceof MathACosFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.TAN, ZERO, ZERO) instanceof MathTanFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.ATAN, ZERO, ZERO) instanceof MathATanFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.SQRT, ZERO, ZERO) instanceof MathSqrtFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.SINH, ZERO, ZERO) instanceof MathSinHFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.ASINH, ZERO, ZERO) instanceof MathASinHFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.COSH, ZERO, ZERO) instanceof MathCosHFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.ACOSH, ZERO, ZERO) instanceof MathACosHFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.TANH, ZERO, ZERO) instanceof MathTanHFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.ATANH, ZERO, ZERO) instanceof MathATanHFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.CBRT, ZERO, ZERO) instanceof MathCbrtFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.HYPOT, ZERO, ZERO) instanceof MathHypotFunction); + assertTrue(MathFunctions.newInstance(MathFunctions.Function.FLOOR, ZERO, ZERO) instanceof MathFloorFunction); } } diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java index babeebdf8c1..71ffc5e928d 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java @@ -4,7 +4,6 @@ package com.yahoo.search.grouping.request; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -42,8 +41,8 @@ public class RawBufferTestCase { @Test void requireThatToStringWorks() { - assertToString(Arrays.asList("a".getBytes()[0], "b".getBytes()[0]), "{97,98}"); - assertToString(Arrays.asList((byte) 2, (byte) 6), "{2,6}"); + assertToString(List.of("a".getBytes()[0], "b".getBytes()[0]), "{97,98}"); + assertToString(List.of((byte) 2, (byte) 6), "{2,6}"); } public void assertToString(List<Byte> data, String expected) { diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java index 0b6ab49867b..24049264d4b 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.search.grouping.request; import org.junit.jupiter.api.Test; -import java.util.Arrays; +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -17,7 +17,7 @@ public class RequestTestCase { GroupingOperation op = new AllOperation() .setGroupBy(new AttributeValue("foo")) .addOrderBy(new CountAggregator()) - .addChildren(Arrays.asList(new AllOperation(), new EachOperation())) + .addChildren(List.of(new AllOperation(), new EachOperation())) .addChild(new EachOperation() .addOutput(new CountAggregator()) .addOutput(new MinAggregator(new AttributeValue("bar"))) diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java index 2471acfb115..4d03c4aff95 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java @@ -4,7 +4,6 @@ package com.yahoo.search.grouping.request.parser; import com.yahoo.search.grouping.request.GroupingOperation; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -51,7 +50,7 @@ public class GroupingParserBenchmarkTest { } private static List<String> getInputs() { - return Arrays.asList( + return List.of( " all(group(foo)each(output(max(bar))))", "all( group(foo)each(output(max(bar))))", "all(group( foo)each(output(max(bar))))", diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java index e78ebfbd5af..01963e94546 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java @@ -13,7 +13,6 @@ import com.yahoo.search.yql.YqlParser; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -29,7 +28,7 @@ public class GroupingParserTestCase { @Test void requireThatMathAllowsWhitespace() { - for (String op : Arrays.asList("+", " +", " + ", "+ ", + for (String op : List.of("+", " +", " + ", "+ ", "-", " -", " - ", "- ", "*", " *", " * ", "* ", "/", " /", " / ", "/ ", @@ -64,7 +63,7 @@ public class GroupingParserTestCase { @Test void requireThatTokenImagesAreNotReservedWords() { - List<String> images = Arrays.asList("acos", + List<String> images = List.of("acos", "acosh", "accuracy", "add", @@ -489,7 +488,7 @@ public class GroupingParserTestCase { @Test void testMisc() { - for (String fnc : Arrays.asList("time.date", + for (String fnc : List.of("time.date", "time.dayofmonth", "time.dayofweek", "time.dayofyear", @@ -634,7 +633,7 @@ public class GroupingParserTestCase { actual.add(operation.toString()); } if (expectedOperations.length > 0) { - assertEquals(Arrays.asList(expectedOperations), actual); + assertEquals(List.of(expectedOperations), actual); } // make sure that operation does not mutate through toString() -> fromString() @@ -656,7 +655,7 @@ public class GroupingParserTestCase { actual.add(step.getOperation().toString()); } if (expectedOperations.length > 0) { - assertEquals(Arrays.asList(expectedOperations), actual); + assertEquals(List.of(expectedOperations), actual); } } diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java index 9e8fcb0ea21..c17bc985aef 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java @@ -28,7 +28,6 @@ import com.yahoo.searchlib.aggregation.hll.SparseSketch; import com.yahoo.searchlib.expression.StringResultNode; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; @@ -105,7 +104,7 @@ public class FlatteningSearcherTestCase { } private static Execution newExecution(Searcher... searchers) { - return new Execution(new SearchChain(new ComponentId("foo"), Arrays.asList(searchers)), + return new Execution(new SearchChain(new ComponentId("foo"), List.of(searchers)), Execution.Context.createContextStub()); } diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java index ef2ef9724a9..780066d0afe 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java @@ -35,7 +35,6 @@ import com.yahoo.searchlib.expression.StringResultNode; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; @@ -180,7 +179,7 @@ public class GroupingExecutorTestCase { .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MinAggregationResult().setMin(new IntegerResultNode(6)).setTag(3))) ); Execution exec = newExecution(new GroupingExecutor(), - new ResultProvider(Arrays.asList( + new ResultProvider(List.of( new GroupingListHit(List.of(grpA), null, query), new GroupingListHit(List.of(grpB), null, query)))); Group grp = req.getResultGroup(exec.search(query)); @@ -213,7 +212,7 @@ public class GroupingExecutorTestCase { .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("unexpected")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(96)).setTag(3))) ); Execution exec = newExecution(new GroupingExecutor(), - new ResultProvider(Arrays.asList( + new ResultProvider(List.of( new GroupingListHit(List.of(grpExpected), null, query), new GroupingListHit(List.of(grpUnexpected), null, query)))); Group grp = req.getResultGroup(exec.search(query)); @@ -244,7 +243,7 @@ public class GroupingExecutorTestCase { .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit())) )); Execution exec = newExecution(new GroupingExecutor(), - new ResultProvider(Arrays.asList( + new ResultProvider(List.of( new GroupingListHit(List.of(grp0), null, query), new GroupingListHit(List.of(grp1), null, query))), new FillRequestThrower()); @@ -284,7 +283,7 @@ public class GroupingExecutorTestCase { new HitsAggregationResult(1, "bar") .addHit(new com.yahoo.searchlib.aggregation.FS4Hit())))); Execution exec = newExecution(new GroupingExecutor(), - new ResultProvider(Arrays.asList( + new ResultProvider(List.of( new GroupingListHit(List.of(grp0), null, query), new GroupingListHit(List.of(grp1), null, query))), new FillErrorProvider()); @@ -310,7 +309,7 @@ public class GroupingExecutorTestCase { .addAggregationResult(new CountAggregationResult(2)) .addOrderBy(new AggregationRefNode(0), true))); Result res = newExecution(new GroupingExecutor(), - new ResultProvider(Arrays.asList( + new ResultProvider(List.of( new GroupingListHit(List.of(grp), null, query), new GroupingListHit(List.of(grp), null, query)))).search(query); @@ -339,7 +338,7 @@ public class GroupingExecutorTestCase { ErrorProvider err = new ErrorProvider(1); Execution exec = newExecution(new GroupingExecutor(), err, - new ResultProvider(Arrays.asList( + new ResultProvider(List.of( new GroupingListHit(List.of(grp0), null, query), new GroupingListHit(List.of(grp1), null, query)))); Result res = exec.search(query); @@ -350,7 +349,7 @@ public class GroupingExecutorTestCase { err = new ErrorProvider(0); exec = newExecution(new GroupingExecutor(), err, - new ResultProvider(Arrays.asList( + new ResultProvider(List.of( new GroupingListHit(List.of(grp0), null, query), new GroupingListHit(List.of(grp1), null, query)))); res = exec.search(query); @@ -389,9 +388,9 @@ public class GroupingExecutorTestCase { )); SummaryMapper sm = new SummaryMapper(); Execution exec = newExecution(new GroupingExecutor(), - new ResultProvider(Arrays.asList( - new GroupingListHit(Arrays.asList(pass0A, pass0B), null, query), - new GroupingListHit(Arrays.asList(pass1A, pass1B), null, query))), + new ResultProvider(List.of( + new GroupingListHit(List.of(pass0A, pass0B), null, query), + new GroupingListHit(List.of(pass1A, pass1B), null, query))), sm); exec.fill(exec.search(query), "default"); assertEquals(2, sm.hitsBySummary.size()); @@ -433,7 +432,7 @@ public class GroupingExecutorTestCase { new HitsAggregationResult(1, ExpressionConverter.DEFAULT_SUMMARY_NAME) .addHit(new com.yahoo.searchlib.aggregation.FS4Hit())))); Execution exec = newExecution(new GroupingExecutor(), - new ResultProvider(Arrays.asList( + new ResultProvider(List.of( new GroupingListHit(List.of(pass0), null, query), new GroupingListHit(List.of(pass1), null, query)))); Result res = exec.search(query); @@ -468,7 +467,7 @@ public class GroupingExecutorTestCase { QueryMapper qm = new QueryMapper(); Execution exec = newExecution(new GroupingExecutor(), - new ResultProvider(Arrays.asList(pass0, pass1)), + new ResultProvider(List.of(pass0, pass1)), qm); exec.fill(exec.search(queryA)); assertEquals(1, qm.hitsByQuery.size()); @@ -607,7 +606,7 @@ public class GroupingExecutorTestCase { } private static Execution newExecution(Searcher... searchers) { - return new Execution(new SearchChain(new ComponentId("foo"), Arrays.asList(searchers)), + return new Execution(new SearchChain(new ComponentId("foo"), List.of(searchers)), Execution.Context.createContextStub()); } diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java index 6230899ec49..7e049e44f4d 100644 --- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java @@ -36,7 +36,6 @@ import com.yahoo.searchlib.expression.StringResultNode; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; @@ -916,10 +915,11 @@ public class ResultBuilderTestCase { assertOutput(test); } + private static void assertOutput(ResultTest test) { RequestBuilder reqBuilder = new RequestBuilder(REQUEST_ID); reqBuilder.setRootOperation(GroupingOperation.fromString(test.request)); - reqBuilder.addContinuations(Arrays.asList(test.continuation)); + reqBuilder.addContinuations(test.getContinuations()); reqBuilder.build(); assertEquals(reqBuilder.getRequestList().size(), test.result.size()); @@ -973,6 +973,9 @@ public class ResultBuilderTestCase { String expectedException; OutputWriter outputWriter; Continuation continuation; + List<Continuation> getContinuations() { + return continuation != null ? List.of(continuation) : List.of(); + } } private static interface OutputWriter { diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java index 1869e0e4bf0..78875b5b831 100644 --- a/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java @@ -100,7 +100,7 @@ public class PageTemplateSearcherTestCase { { // Specifying two templates as a list, should override the page.id setting Query query = new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic"); - query.properties().set("page.idList", Arrays.asList("oneSource", "threeSources")); + query.properties().set("page.idList", List.of("oneSource", "threeSources")); Result result = new Execution(chain, Execution.Context.createContextStub()).search(query); assertSources("source1 source2 source3", "source1 source2 source3", result); } @@ -172,11 +172,11 @@ public class PageTemplateSearcherTestCase { } private void assertSources(String expectedQuerySourceString,String expectedResultSourceString,Result result) { - Set<String> expectedQuerySources=new HashSet<>(Arrays.asList(expectedQuerySourceString.split(" "))); + Set<String> expectedQuerySources=new HashSet<>(List.of(expectedQuerySourceString.split(" "))); assertEquals(expectedQuerySources,result.getQuery().getModel().getSources()); - Set<String> expectedResultSources=new HashSet<>(Arrays.asList(expectedResultSourceString.split(" "))); - for (String sourceName : Arrays.asList("source1 source2 source3".split(" "))) { + Set<String> expectedResultSources=new HashSet<>(List.of(expectedResultSourceString.split(" "))); + for (String sourceName : List.of("source1 source2 source3".split(" "))) { if (expectedResultSources.contains(sourceName)) assertNotNull(result.hits().get(sourceName),"Result contains '" + sourceName + "'"); else @@ -189,7 +189,7 @@ public class PageTemplateSearcherTestCase { @Override public Result search(Query query,Execution execution) { Result result=new Result(query); - for (String sourceName : Arrays.asList("source1 source2 source3".split(" "))) + for (String sourceName : List.of("source1 source2 source3".split(" "))) if (query.getModel().getSources().isEmpty() || query.getModel().getSources().contains(sourceName)) result.hits().add(createSource(sourceName)); return result; diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java index 20043f23256..58f1fa62fe6 100644 --- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java @@ -20,7 +20,6 @@ import com.yahoo.search.searchchain.Execution; import com.yahoo.yolean.trace.TraceNode; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -125,7 +124,7 @@ public class QueryProfileTestCase { far.set("a.far", "a.far", null); CompiledQueryProfile cbarn = barn.compile(null); - assertSameObjects(cbarn, "a", Arrays.asList("mormor", "far", "barn")); + assertSameObjects(cbarn, "a", List.of("mormor", "far", "barn")); assertEquals("b.mor", cbarn.get("b.mor")); assertEquals("b.far", cbarn.get("b.far")); diff --git a/container-search/src/test/java/com/yahoo/search/query/properties/SubPropertiesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/properties/SubPropertiesTestCase.java index 467a0b0845c..266cb4daf67 100644 --- a/container-search/src/test/java/com/yahoo/search/query/properties/SubPropertiesTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/query/properties/SubPropertiesTestCase.java @@ -4,8 +4,8 @@ package com.yahoo.search.query.properties; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; -import java.util.Arrays; import java.util.HashSet; +import java.util.List; import com.yahoo.processing.request.properties.PropertyMap; import org.junit.jupiter.api.Test; @@ -34,7 +34,7 @@ public class SubPropertiesTestCase { assertEquals("1", sub.get("e")); assertEquals(2, sub.get("f")); assertNull(sub.get("d")); - assertEquals(new HashSet<>(Arrays.asList("e", "f")), sub.listProperties("").keySet()); + assertEquals(new HashSet<>(List.of("e", "f")), sub.listProperties("").keySet()); } } diff --git a/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java b/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java index 42dcab41015..793a907b5d1 100644 --- a/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java @@ -4,7 +4,6 @@ package com.yahoo.search.query.properties.test; import com.yahoo.processing.request.properties.PropertyMap; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -22,8 +21,8 @@ public class PropertyMapTestCase { map.set("nonclonable", new NonClonableObject()); map.set("clonableArray", new ClonableObject[]{new ClonableObject()}); map.set("nonclonableArray", new NonClonableObject[]{new NonClonableObject()}); - map.set("clonableList", Collections.singletonList(new ClonableObject())); - map.set("nonclonableList", Collections.singletonList(new NonClonableObject())); + map.set("clonableList", List.of(new ClonableObject())); + map.set("nonclonableList", List.of(new NonClonableObject())); assertNotNull(map.get("clonable")); assertNotNull(map.get("nonclonable")); diff --git a/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java index 2cd43257b12..89a62abddcc 100644 --- a/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java @@ -10,8 +10,8 @@ import org.junit.jupiter.api.Test; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; -import java.util.Arrays; import java.util.LinkedHashSet; +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -91,8 +91,8 @@ public class ModelTestCase { Model sr = new Model(q); sr.setRestrict("music, cheese,other"); sr.setSources("cluster1"); - assertEquals(sr.getSources(), new LinkedHashSet<>(Arrays.asList(new String[]{"cluster1"}))); - assertEquals(sr.getRestrict(), new LinkedHashSet<>(Arrays.asList(new String[]{"cheese", "music", "other"}))); + assertEquals(sr.getSources(), new LinkedHashSet<>(List.of(new String[]{"cluster1"}))); + assertEquals(sr.getRestrict(), new LinkedHashSet<>(List.of(new String[]{"cheese", "music", "other"}))); } @Test diff --git a/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java index 732fdd7dcbb..7bfbeef4e23 100644 --- a/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java @@ -36,7 +36,6 @@ public class RankFeaturesTestCase { } @Test - @SuppressWarnings("deprecation") void requireThatRankFeaturesUsingDoubleAndDoubleToStringEncodeTheSameWay() { RankFeatures withDouble = new RankFeatures(new Ranking(new Query())); withDouble.put("query(myDouble)", 3.8); @@ -68,20 +67,12 @@ public class RankFeaturesTestCase { TensorType type = new TensorType.Builder().mapped("x").mapped("y").mapped("z").build(); Tensor tensor1 = Tensor.from(type, "{ {x:a, y:b, z:c}:2.0, {x:a, y:b, z:c2}:3.0 }"); Tensor tensor2 = Tensor.from(type, "{ {x:a, y:b, z:c}:5.0 }"); - assertTensorEncodingAndDecoding(type, Arrays.asList( + assertTensorEncodingAndDecoding(type, List.of( new Entry("query(tensor1)", "tensor1", tensor1), new Entry("$tensor2", "tensor2", tensor2))); } - private static class Entry { - final String key; - final String normalizedKey; - final Tensor tensor; - Entry(String key, String normalizedKey, Tensor tensor) { - this.key = key; - this.normalizedKey = normalizedKey; - this.tensor = tensor; - } + private record Entry(String key, String normalizedKey, Tensor tensor) { } private static void assertTensorEncodingAndDecoding(TensorType type, List<Entry> entries) { @@ -97,7 +88,7 @@ public class RankFeaturesTestCase { } private static void assertTensorEncodingAndDecoding(TensorType type, String key, String normalizedKey, Tensor tensor) { - assertTensorEncodingAndDecoding(type, Arrays.asList(new Entry(key, normalizedKey, tensor))); + assertTensorEncodingAndDecoding(type, List.of(new Entry(key, normalizedKey, tensor))); } private static RankProperties createRankPropertiesWithTensors(List<Entry> entries) { diff --git a/container-search/src/test/java/com/yahoo/search/ranking/GlobalPhaseRerankHitsImplTest.java b/container-search/src/test/java/com/yahoo/search/ranking/GlobalPhaseRerankHitsImplTest.java index 39b202daf1e..b37e1d5551b 100644 --- a/container-search/src/test/java/com/yahoo/search/ranking/GlobalPhaseRerankHitsImplTest.java +++ b/container-search/src/test/java/com/yahoo/search/ranking/GlobalPhaseRerankHitsImplTest.java @@ -35,7 +35,7 @@ public class GlobalPhaseRerankHitsImplTest { } } static FunEvalSpec makeConstSpec(double constValue) { - return new FunEvalSpec(() -> new EvalSum(constValue), Collections.emptyList(), Collections.emptyList()); + return new FunEvalSpec(() -> new EvalSum(constValue), List.of(), List.of()); } static FunEvalSpec makeSumSpec(List<String> fromQuery, List<String> fromMF) { List<MatchFeatureInput> mfList = new ArrayList<>(); @@ -175,15 +175,15 @@ public class GlobalPhaseRerankHitsImplTest { } @Test void partialRerankWithRescaling() { var setup = setup().rerank(2).eval(makeConstSpec(3.0)).build(); - var query = makeQuery(Collections.emptyList()); + var query = makeQuery(List.of()); var result = makeResult(query, List.of(hit("a", 3), hit("b", 4), hit("c", 5), hit("d", 6))); var expect = Expect.make(List.of(hit("a", 1), hit("b", 2), hit("c", 3), hit("d", 3))); GlobalPhaseRanker.rerankHitsImpl(setup, query, result); expect.verifyScores(result); } @Test void matchFeaturesCanBePartiallyHidden() { - var setup = setup().eval(makeSumSpec(Collections.emptyList(), List.of("public_value", "private_value"))).hide("private_value").build(); - var query = makeQuery(Collections.emptyList()); + var setup = setup().eval(makeSumSpec(List.of(), List.of("public_value", "private_value"))).hide("private_value").build(); + var query = makeQuery(List.of()); var factory = new HitFactory(List.of("public_value", "private_value")); var result = makeResult(query, List.of(factory.create("a", 1, List.of(value("public_value", 2), value("private_value", 3))), factory.create("b", 2, List.of(value("public_value", 5), value("private_value", 7))))); @@ -194,8 +194,8 @@ public class GlobalPhaseRerankHitsImplTest { verifyDoesNotHaveMF(result, "private_value"); } @Test void matchFeaturesCanBeRemoved() { - var setup = setup().eval(makeSumSpec(Collections.emptyList(), List.of("private_value"))).hide("private_value").build(); - var query = makeQuery(Collections.emptyList()); + var setup = setup().eval(makeSumSpec(List.of(), List.of("private_value"))).hide("private_value").build(); + var query = makeQuery(List.of()); var factory = new HitFactory(List.of("private_value")); var result = makeResult(query, List.of(factory.create("a", 1, List.of(value("private_value", 3))), factory.create("b", 2, List.of(value("private_value", 7))))); @@ -227,7 +227,7 @@ public class GlobalPhaseRerankHitsImplTest { verifyHasMF(result, "bar"); } @Test void queryFeaturesCanBeDefaultValues() { - var setup = setup().eval(makeSumSpec(List.of("foo", "bar"), Collections.emptyList())) + var setup = setup().eval(makeSumSpec(List.of("foo", "bar"), List.of())) .addDefault("query(bar)", Tensor.from(5.0)).build(); var query = makeQuery(List.of(value("query(foo)", 7))); var result = makeResult(query, List.of(hit("a", 1))); @@ -236,7 +236,7 @@ public class GlobalPhaseRerankHitsImplTest { expect.verifyScores(result); } @Test void withNormalizer() { - var setup = setup().eval(makeSumSpec(Collections.emptyList(), List.of("bar"))) + var setup = setup().eval(makeSumSpec(List.of(), List.of("bar"))) .addNormalizer(makeNormalizer("foo", List.of(115.0, 65.0, 55.0, 45.0, 15.0), makeSumSpec(List.of("x"), List.of("bar")))).build(); var query = makeQuery(List.of(value("query(x)", 5))); var factory = new HitFactory(List.of("bar")); diff --git a/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java b/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java index 298673a1ae7..d8f4f39c5b8 100644 --- a/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java @@ -5,7 +5,8 @@ import com.yahoo.search.result.Hit; import com.yahoo.search.result.HitGroup; import org.junit.jupiter.api.Test; -import java.util.Collections; + +import java.util.Set; import static org.junit.jupiter.api.Assertions.*; @@ -63,7 +64,7 @@ public class FillingTestCase { hits.add(hit1); hits.add(hit2); - assertEquals(Collections.emptySet(), hits.getFilled()); + assertEquals(Set.of(), hits.getFilled()); } @Test @@ -82,7 +83,7 @@ public class FillingTestCase { hits.add(hit2); hits.add(hit3); - assertEquals(Collections.singleton("summary1"), hits.getFilled()); + assertEquals(Set.of("summary1"), hits.getFilled()); } private Hit createNonFilled(String id) { diff --git a/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java b/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java index 5f8fbbd08df..42098051b82 100644 --- a/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java @@ -9,7 +9,6 @@ import com.yahoo.search.result.Hit; import com.yahoo.search.result.HitGroup; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -165,14 +164,14 @@ public class HitGroupTestCase { Hit hit = new Hit("http://nalle.balle/1.html", 832); hit.setField("url", "http://nalle.balle/1.html"); hit.setField("clickurl", "javascript:openWindow('http://www.foo');"); - hit.setField("attributes", Arrays.asList("typevideo")); + hit.setField("attributes", List.of("typevideo")); hg.add(hit); } { Hit hit = new Hit("http://nalle.balle/2.html", 442); hit.setField("url", "http://nalle.balle/2.html"); hit.setField("clickurl", ""); - hit.setField("attributes", Arrays.asList("typevideo")); + hit.setField("attributes", List.of("typevideo")); hg.add(hit); } assertFalse(hg.isFillable()); @@ -187,7 +186,7 @@ public class HitGroupTestCase { Hit hit = new Hit("http://nalle.balle/1.html", 832); hit.setField("url", "http://nalle.balle/1.html"); hit.setField("clickurl", "javascript:openWindow('http://www.foo');"); - hit.setField("attributes", Arrays.asList("typevideo")); + hit.setField("attributes", List.of("typevideo")); hit.setFillable(); hg.add(hit); } @@ -195,7 +194,7 @@ public class HitGroupTestCase { Hit hit = new Hit("http://nalle.balle/2.html", 442); hit.setField("url", "http://nalle.balle/2.html"); hit.setField("clickurl", ""); - hit.setField("attributes", Arrays.asList("typevideo")); + hit.setField("attributes", List.of("typevideo")); hit.setFillable(); hg.add(hit); } @@ -211,14 +210,14 @@ public class HitGroupTestCase { Hit hit = new Hit("http://nalle.balle/1.html", 832); hit.setField("url", "http://nalle.balle/1.html"); hit.setField("clickurl", "javascript:openWindow('http://www.foo');"); - hit.setField("attributes", Arrays.asList("typevideo")); + hit.setField("attributes", List.of("typevideo")); hg.add(hit); } { Hit hit = new Hit("http://nalle.balle/2.html", 442); hit.setField("url", "http://nalle.balle/2.html"); hit.setField("clickurl", ""); - hit.setField("attributes", Arrays.asList("typevideo")); + hit.setField("attributes", List.of("typevideo")); hg.add(hit); } assertFalse(hg.isFillable()); diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java index e8a85e38e80..1bf04eb44fb 100644 --- a/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java @@ -10,7 +10,6 @@ import com.yahoo.search.result.Hit; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; @@ -70,20 +69,20 @@ public class AsyncExecutionTestCase { void testWaitForAll() { Chain<Searcher> slowChain = new Chain<>( new ComponentId("slow"), - Arrays.asList(new Searcher[]{new WaitingSearcher("slow", 30000)} + List.of(new Searcher[]{new WaitingSearcher("slow", 30000)} ) ); Chain<Searcher> fastChain = new Chain<>( new ComponentId("fast"), - Arrays.asList(new Searcher[]{new SimpleSearcher()}) + List.of(new Searcher[]{new SimpleSearcher()}) ); FutureResult slowFuture = new AsyncExecution(slowChain, Execution.Context.createContextStub()).search(new Query("?hits=0")); FutureResult fastFuture = new AsyncExecution(fastChain, Execution.Context.createContextStub()).search(new Query("?hits=0")); fastFuture.get(); FutureResult [] reslist = new FutureResult[]{slowFuture, fastFuture}; - List<Result> results = AsyncExecution.waitForAll(Arrays.asList(reslist), 0); + List<Result> results = AsyncExecution.waitForAll(List.of(reslist), 0); //assertTrue(slowFuture.isCancelled()); assertTrue(fastFuture.isDone() && !fastFuture.isCancelled()); diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java index 924aa7ae999..16e9adecdba 100644 --- a/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.search.searchchain.config.test; import java.io.File; import java.io.IOException; -import java.util.Arrays; +import java.util.List; import com.yahoo.component.chain.dependencies.After; @@ -72,8 +72,8 @@ public class DependencyConfigTestCase { void test() { Dependencies dependencies = registry.getSearcherRegistry().getComponent(Searcher1.class.getName()).getDependencies(); - assertTrue(dependencies.provides().containsAll(Arrays.asList("P", "P1", "P2", Searcher1.class.getSimpleName()))); - assertTrue(dependencies.before().containsAll(Arrays.asList("B", "B1", "B2"))); - assertTrue(dependencies.after().containsAll(Arrays.asList("A", "A1", "A2"))); + assertTrue(dependencies.provides().containsAll(List.of("P", "P1", "P2", Searcher1.class.getSimpleName()))); + assertTrue(dependencies.before().containsAll(List.of("B", "B1", "B2"))); + assertTrue(dependencies.after().containsAll(List.of("A", "A1", "A2"))); } } diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java index bfcde54d65b..fda7bec9d71 100644 --- a/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java @@ -16,7 +16,7 @@ import com.yahoo.search.searchchain.SearchChainRegistry; import com.yahoo.search.searchchain.model.federation.FederationOptions; import org.junit.jupiter.api.Test; -import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -82,7 +82,7 @@ public class FutureDataTestCase { void testFutureData() throws InterruptedException, ExecutionException, TimeoutException { // Set up AsyncProviderSearcher futureDataSource = new AsyncProviderSearcher(); - Chain<Searcher> chain = new Chain<>(Collections.<Searcher>singletonList(futureDataSource)); + Chain<Searcher> chain = new Chain<>(List.of(futureDataSource)); // Execute Query query = new Query(); diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java index 2f04b695774..87384a15979 100644 --- a/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java @@ -5,7 +5,6 @@ import static com.yahoo.search.searchchain.test.SimpleSearchChain.searchChain; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; @@ -40,7 +39,7 @@ public class SearchChainTestCase { assertEquals("test", searchChain.getId().getName()); assertEquals(Version.emptyVersion, searchChain.getId().getVersion()); assertEquals(new Version(), searchChain.getId().getVersion()); - assertEqualMembers(Arrays.asList("one", "two"), searcherNames(searchChain.searchers())); + assertEqualMembers(List.of("one", "two"), searcherNames(searchChain.searchers())); } public List<String> searcherNames(Collection<Searcher> searchers) { diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/SimpleSearchChain.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/SimpleSearchChain.java index de2fc46d803..833fd2c8657 100644 --- a/container-search/src/test/java/com/yahoo/search/searchchain/test/SimpleSearchChain.java +++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/SimpleSearchChain.java @@ -2,7 +2,6 @@ package com.yahoo.search.searchchain.test; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -38,7 +37,7 @@ public class SimpleSearchChain { @Override public Collection<ForkingSearcher.CommentedSearchChain> getSearchChainsForwarded(SearchChainRegistry registry) { - return Arrays.asList( + return List.of( new ForkingSearcher.CommentedSearchChain("Reason for forwarding to this search chain.", dummySearchChain()), new ForkingSearcher.CommentedSearchChain(null, dummySearchChain())); } diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java index 036c41aab66..fb77073f68e 100644 --- a/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java @@ -15,7 +15,6 @@ import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; -import java.util.Arrays; import java.util.Iterator; import java.util.List; @@ -308,7 +307,7 @@ public class TraceTestCase { public Forker(boolean carryOverContext, boolean parallel, Searcher ... branches) { this.carryOverContext = carryOverContext; this.parallel = parallel; - this.branches = Arrays.asList(branches); + this.branches = List.of(branches); } @Override diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/MockMetric.java b/container-search/src/test/java/com/yahoo/search/searchers/test/MockMetric.java deleted file mode 100644 index 7835a9934c7..00000000000 --- a/container-search/src/test/java/com/yahoo/search/searchers/test/MockMetric.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -package com.yahoo.search.searchers.test; - -import com.yahoo.jdisc.Metric; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -/** -* @author bratseth -*/ -class MockMetric implements Metric { - - private Map<Context, Map<String, Number>> metrics = new HashMap<>(); - - public Map<String, Number> values(Context context) { - return metricsForContext(context); - } - - @Override - public void set(String key, Number val, Context context) { - metricsForContext(context).put(key, val); - } - - @Override - public void add(String key, Number value, Context context) { - Number previousValue = metricsForContext(context).get(key); - if (previousValue == null) - previousValue = 0; - metricsForContext(context).put(key, value.doubleValue() + previousValue.doubleValue()); - } - - /** Returns the metrics for a given context, never null */ - private Map<String, Number> metricsForContext(Context context) { - Map<String, Number> metricsForContext = metrics.get(context); - if (metricsForContext == null) { - metricsForContext = new HashMap<>(); - metrics.put(context, metricsForContext); - } - return metricsForContext; - } - - @Override - public Context createContext(Map<String, ?> dimensions) { - return new MapContext(dimensions); - } - - /** Creates a context containing a single dimension */ - public Metric.Context createContext(String dimensionName, String dimensionValue) { - if (dimensionName.isEmpty()) - return createContext(Collections.emptyMap()); - return createContext(Collections.singletonMap(dimensionName, dimensionValue)); - } - - private class MapContext implements Metric.Context { - - private final Map<String, ?> dimensions; - - public MapContext(Map<String, ?> dimensions) { - this.dimensions = dimensions; - } - - @Override - public int hashCode() { - return dimensions.hashCode(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if ( ! (o instanceof MapContext)) return false; - return dimensions.equals(((MapContext)o).dimensions); - } - - } - -} diff --git a/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java index 87bc602f072..20ca81234a6 100644 --- a/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java @@ -27,7 +27,8 @@ import com.yahoo.search.query.QueryTree; import com.yahoo.search.query.parser.Parsable; import com.yahoo.search.query.parser.ParserEnvironment; -import java.util.Arrays; + +import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -383,7 +384,7 @@ public class VespaSerializerTestCase { private static void newGroupingRequest(Query query, GroupingOperation grouping, Continuation... continuations) { GroupingRequest request = GroupingRequest.newInstance(query); request.setRootOperation(grouping); - request.continuations().addAll(Arrays.asList(continuations)); + request.continuations().addAll(List.of(continuations)); } @Test diff --git a/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java index 87d18c18db5..675acabe906 100644 --- a/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java +++ b/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java @@ -3,7 +3,6 @@ package com.yahoo.search.yql; import static org.junit.jupiter.api.Assertions.*; -import java.util.Arrays; import java.util.List; import com.yahoo.search.schema.DocumentSummary; @@ -48,9 +47,9 @@ public class YqlFieldAndSourceTestCase { DocumentSourceSearcher mockBackend = new DocumentSourceSearcher(); mockBackend.addResult(query, result); - mockBackend.addSummaryClassByCopy(DEFAULT_SUMMARY_CLASS, Arrays.asList(FIELD1, FIELD2)); - mockBackend.addSummaryClassByCopy(SORTABLE_ATTRIBUTES_SUMMARY_CLASS, Arrays.asList(FIELD2)); - mockBackend.addSummaryClassByCopy(THIRD_OPTION, Arrays.asList(FIELD3)); + mockBackend.addSummaryClassByCopy(DEFAULT_SUMMARY_CLASS, List.of(FIELD1, FIELD2)); + mockBackend.addSummaryClassByCopy(SORTABLE_ATTRIBUTES_SUMMARY_CLASS, List.of(FIELD2)); + mockBackend.addSummaryClassByCopy(THIRD_OPTION, List.of(FIELD3)); searchChain = new Chain<>(new FieldFiller(schemaInfo()), mockBackend); context = Execution.Context.createContextStub(); diff --git a/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java b/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java index dd2725f2d6e..3fa81e948a2 100644 --- a/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java +++ b/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java @@ -2,7 +2,6 @@ package com.yahoo.text.interpretation.test; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -50,7 +49,7 @@ public class AnnotationTestCase { } Set<AnnotationClass> annotationClasses = a.getClasses(0, 3); - Set<AnnotationClass> testClass = new HashSet<>(Arrays.asList( + Set<AnnotationClass> testClass = new HashSet<>(List.of( new AnnotationClass("token"), new AnnotationClass("state"))); assertEquals(testClass, annotationClasses); @@ -75,7 +74,7 @@ public class AnnotationTestCase { //This is bad about the API, getTokens may not necessairily return what a user thinks a token is //But it should still be tested a.annotate(0, 1, "n"); - Set<String> testSet = new HashSet<>(Arrays.asList("n", "york", "hotel")); + Set<String> testSet = new HashSet<>(List.of("n", "york", "hotel")); for (Span span :a.getTokens()) { assertTrue(testSet.remove(span.getText())); } @@ -118,7 +117,7 @@ public class AnnotationTestCase { //if a number is not found woe_id = annotations.getInteger("woe_id"); } - assertEquals(Arrays.asList("crab"), toppings); + assertEquals(List.of("crab"), toppings); assertEquals(2459115, woe_id); } diff --git a/default_build_settings.cmake b/default_build_settings.cmake index 63ac2c306cb..3a06a33ab44 100644 --- a/default_build_settings.cmake +++ b/default_build_settings.cmake @@ -205,9 +205,6 @@ function(vespa_use_default_cxx_compiler) if(APPLE) set(DEFAULT_CMAKE_C_COMPILER "${VESPA_HOMEBREW_PREFIX}/bin/gcc-13") set(DEFAULT_CMAKE_CXX_COMPILER "${VESPA_HOMEBREW_PREFIX}/bin/g++-13") - elseif(VESPA_OS_DISTRO_COMBINED STREQUAL "amzn 2") - set(DEFAULT_CMAKE_C_COMPILER "/usr/bin/gcc10-gcc") - set(DEFAULT_CMAKE_CXX_COMPILER "/usr/bin/gcc10-g++") elseif(VESPA_OS_DISTRO_COMBINED STREQUAL "ubuntu 22.04" AND EXISTS "/usr/bin/gcc-12" AND EXISTS "/usr/bin/g++-12") set(DEFAULT_CMAKE_C_COMPILER "/usr/bin/gcc-12") diff --git a/dependency-versions/pom.xml b/dependency-versions/pom.xml index 24819113c4e..43573ce0e93 100644 --- a/dependency-versions/pom.xml +++ b/dependency-versions/pom.xml @@ -68,7 +68,7 @@ <assertj.vespa.version>3.25.3</assertj.vespa.version> <!-- Athenz dependencies. Make sure these dependencies match those in Vespa's internal repositories --> - <aws-sdk.vespa.version>1.12.697</aws-sdk.vespa.version> + <aws-sdk.vespa.version>1.12.700</aws-sdk.vespa.version> <athenz.vespa.version>1.11.55</athenz.vespa.version> <!-- Athenz END --> @@ -140,7 +140,7 @@ <plexus-utils.vespa.version>4.0.0</plexus-utils.vespa.version> <plexus-xml.vespa.version>4.0.3</plexus-xml.vespa.version> <protobuf.vespa.version>3.25.3</protobuf.vespa.version> - <questdb.vespa.version>7.3.10</questdb.vespa.version> + <questdb.vespa.version>7.4.0</questdb.vespa.version> <spifly.vespa.version>1.3.7</spifly.vespa.version> <snappy.vespa.version>1.1.10.5</snappy.vespa.version> <surefire.vespa.version>3.2.5</surefire.vespa.version> @@ -174,7 +174,7 @@ <maven-deploy-plugin.vespa.version>3.1.1</maven-deploy-plugin.vespa.version> <maven-enforcer-plugin.vespa.version>3.4.1</maven-enforcer-plugin.vespa.version> <maven-failsafe-plugin.vespa.version>3.2.5</maven-failsafe-plugin.vespa.version> - <maven-gpg-plugin.vespa.version>3.2.2</maven-gpg-plugin.vespa.version> + <maven-gpg-plugin.vespa.version>3.2.3</maven-gpg-plugin.vespa.version> <maven-install-plugin.vespa.version>3.1.1</maven-install-plugin.vespa.version> <maven-jar-plugin.vespa.version>3.3.0</maven-jar-plugin.vespa.version> <maven-javadoc-plugin.vespa.version>3.6.3</maven-javadoc-plugin.vespa.version> diff --git a/docproc/src/main/java/com/yahoo/docproc/Processing.java b/docproc/src/main/java/com/yahoo/docproc/Processing.java index cc9d7b9e8b7..c8c536cb4c1 100644 --- a/docproc/src/main/java/com/yahoo/docproc/Processing.java +++ b/docproc/src/main/java/com/yahoo/docproc/Processing.java @@ -9,7 +9,6 @@ import com.yahoo.document.DocumentOperation; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -221,7 +220,7 @@ public final class Processing extends ProcessingAccess { @Override protected List<DocumentOperation> getOnceOperationsToBeProcessed() { if (operationsGotten) - return Collections.emptyList(); + return List.of(); operationsGotten = true; return getDocumentOperations(); diff --git a/docproc/src/test/java/com/yahoo/docproc/jdisc/DocumentProcessingHandlerAllMessageTypesTestCase.java b/docproc/src/test/java/com/yahoo/docproc/jdisc/DocumentProcessingHandlerAllMessageTypesTestCase.java index aacac7b5c04..822359d7c09 100644 --- a/docproc/src/test/java/com/yahoo/docproc/jdisc/DocumentProcessingHandlerAllMessageTypesTestCase.java +++ b/docproc/src/test/java/com/yahoo/docproc/jdisc/DocumentProcessingHandlerAllMessageTypesTestCase.java @@ -25,9 +25,8 @@ import com.yahoo.messagebus.Reply; import org.junit.Test; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; @@ -48,7 +47,7 @@ public class DocumentProcessingHandlerAllMessageTypesTestCase extends DocumentPr this.type.addField(new Field("blahblah", DataType.STRING)); this.type.addField(new Field("defaultWait", DataType.INT)); this.type.addField(new Field("customWait", DataType.INT)); - type.addFieldSets(Collections.singletonMap(DocumentType.DOCUMENT, Arrays.asList("blahblah", "defaultWait", "customWait"))); + type.addFieldSets(Map.of(DocumentType.DOCUMENT, List.of("blahblah", "defaultWait", "customWait"))); } @Test @@ -158,8 +157,7 @@ public class DocumentProcessingHandlerAllMessageTypesTestCase extends DocumentPr Document doc = ((DocumentPut) op).getDocument(); for (Field f : doc.getDataType().fieldSet()) { FieldValue val = doc.getFieldValue(f); - if (val instanceof StringFieldValue) { - StringFieldValue sf = (StringFieldValue) val; + if (val instanceof StringFieldValue sf) { doc.setFieldValue(f, new StringFieldValue(sf.getString().toUpperCase())); } } diff --git a/docprocs/src/test/java/com/yahoo/docprocs/indexing/DocumentScriptTestCase.java b/docprocs/src/test/java/com/yahoo/docprocs/indexing/DocumentScriptTestCase.java index 2f07958e39e..7abfdc324b3 100644 --- a/docprocs/src/test/java/com/yahoo/docprocs/indexing/DocumentScriptTestCase.java +++ b/docprocs/src/test/java/com/yahoo/docprocs/indexing/DocumentScriptTestCase.java @@ -21,7 +21,6 @@ import com.yahoo.document.fieldpathupdate.AssignFieldPathUpdate; import com.yahoo.document.fieldpathupdate.FieldPathUpdate; import com.yahoo.document.update.AssignValueUpdate; import com.yahoo.document.update.FieldUpdate; -import com.yahoo.document.update.MapValueUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.vespa.indexinglanguage.AdapterFactory; import com.yahoo.vespa.indexinglanguage.SimpleAdapterFactory; @@ -33,8 +32,7 @@ import com.yahoo.vespa.indexinglanguage.parser.ParseException; import org.junit.Test; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -160,7 +158,7 @@ public class DocumentScriptTestCase { assertSpanTrees(str, "mySpanTree"); } - private class FieldPathFixture { + private static class FieldPathFixture { final DocumentType type; final StructDataType structType; final DataType structMap; @@ -264,7 +262,7 @@ public class DocumentScriptTestCase { } private static DocumentScript newScript(DocumentType docType, String fieldName) { - return new DocumentScript(docType.getName(), Collections.singletonList(fieldName), + return new DocumentScript(docType.getName(), List.of(fieldName), new StatementExpression(new InputExpression(fieldName), new IndexExpression(fieldName))); } @@ -285,7 +283,7 @@ public class DocumentScriptTestCase { private static void assertSpanTrees(FieldValue actual, String... expectedSpanTrees) { assertTrue(actual instanceof StringFieldValue); StringFieldValue str = (StringFieldValue)actual; - assertEquals(new ArrayList<>(Arrays.asList(expectedSpanTrees)), + assertEquals(List.of(expectedSpanTrees), new ArrayList<>(str.getSpanTreeMap().keySet())); } @@ -359,7 +357,7 @@ public class DocumentScriptTestCase { } private static DocumentScript newScript() throws ParseException { - return new DocumentScript("documentType", Arrays.asList("documentField"), + return new DocumentScript("documentType", List.of("documentField"), Expression.fromString("input documentField | index documentField")); } } diff --git a/document/src/main/java/com/yahoo/document/DocumentType.java b/document/src/main/java/com/yahoo/document/DocumentType.java index 38bd3bfdeca..3b58b50dc4f 100644 --- a/document/src/main/java/com/yahoo/document/DocumentType.java +++ b/document/src/main/java/com/yahoo/document/DocumentType.java @@ -62,13 +62,13 @@ public class DocumentType extends StructuredDataType { * @param contentStructType The type of the content struct */ public DocumentType(String name, StructDataType contentStructType) { - this(name, contentStructType, Collections.emptySet()); + this(name, contentStructType, Set.of()); } public DocumentType(String name, StructDataType contentStructType, Set<String> importedFieldNames) { super(name); this.contentStructType = contentStructType; - this.importedFieldNames = Collections.unmodifiableSet(importedFieldNames); + this.importedFieldNames = Set.copyOf(importedFieldNames); } public DocumentType(String name, Set<String> importedFieldNames) { diff --git a/document/src/main/java/com/yahoo/document/FieldPath.java b/document/src/main/java/com/yahoo/document/FieldPath.java index b78e48d2b41..7596e359d99 100755..100644 --- a/document/src/main/java/com/yahoo/document/FieldPath.java +++ b/document/src/main/java/com/yahoo/document/FieldPath.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document; -import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -19,7 +18,7 @@ public class FieldPath implements Iterable<FieldPathEntry> { * Constructs an empty path. */ public FieldPath() { - list = Collections.emptyList(); + list = List.of(); } /** @@ -109,7 +108,7 @@ public class FieldPath implements Iterable<FieldPathEntry> { FieldPathEntry.Type type = entry.getType(); switch (type) { case STRUCT_FIELD: - if (out.length() > 0) { + if (!out.isEmpty()) { out.append("."); } Field field = entry.getFieldRef(); diff --git a/document/src/main/java/com/yahoo/document/annotation/AnnotationTypes.java b/document/src/main/java/com/yahoo/document/annotation/AnnotationTypes.java index 4750e64a784..312f2800e6c 100644 --- a/document/src/main/java/com/yahoo/document/annotation/AnnotationTypes.java +++ b/document/src/main/java/com/yahoo/document/annotation/AnnotationTypes.java @@ -3,7 +3,6 @@ package com.yahoo.document.annotation; import com.yahoo.document.DataType; -import java.util.Arrays; import java.util.List; /** @@ -29,7 +28,7 @@ public final class AnnotationTypes { public static final AnnotationType PROXIMITY_BREAK = new AnnotationType("proximity_break", DataType.DOUBLE, 8); public static final AnnotationType SPECIAL_TOKEN = new AnnotationType("special_token", 9); - public static final List<AnnotationType> ALL_TYPES = Arrays.asList(TERM, TOKEN_TYPE, CANONICAL, NORMALIZED, READING, + public static final List<AnnotationType> ALL_TYPES = List.of(TERM, TOKEN_TYPE, CANONICAL, NORMALIZED, READING, STEM, TRANSFORMED, PROXIMITY_BREAK, SPECIAL_TOKEN); } diff --git a/document/src/main/java/com/yahoo/document/fieldpathupdate/FieldPathUpdate.java b/document/src/main/java/com/yahoo/document/fieldpathupdate/FieldPathUpdate.java index 35d12f32906..42405bb6f06 100644 --- a/document/src/main/java/com/yahoo/document/fieldpathupdate/FieldPathUpdate.java +++ b/document/src/main/java/com/yahoo/document/fieldpathupdate/FieldPathUpdate.java @@ -13,6 +13,7 @@ import com.yahoo.document.select.parser.ParseException; import com.yahoo.document.serialization.DocumentUpdateReader; import com.yahoo.document.serialization.VespaDocumentSerializer6; import java.util.ListIterator; +import java.util.Objects; /** * @author Thomas Gundersen @@ -48,8 +49,8 @@ public abstract class FieldPathUpdate { private DocumentSelector selector; private String originalFieldPath; private String whereClause; - private Type updType; - private DocumentType docType; + private final Type updType; + private final DocumentType docType; public FieldPathUpdate(Type updType, DocumentType docType, String fieldPath, String whereClause) { this.updType = updType; @@ -97,7 +98,7 @@ public abstract class FieldPathUpdate { public void setWhereClause(String whereClause) throws ParseException { this.whereClause = whereClause; selector = null; - if (whereClause != null && !whereClause.equals("")) { + if (whereClause != null && !whereClause.isEmpty()) { selector = new DocumentSelector(whereClause); } } @@ -135,15 +136,11 @@ public abstract class FieldPathUpdate { } public static FieldPathUpdate create(Type type, DocumentType docType, DocumentUpdateReader reader) { - switch (type) { - case ASSIGN: - return new AssignFieldPathUpdate(docType, reader); - case ADD: - return new AddFieldPathUpdate(docType, reader); - case REMOVE: - return new RemoveFieldPathUpdate(docType, reader); - } - throw new IllegalArgumentException("Field path update type '" + type + "' not supported."); + return switch (type) { + case ASSIGN -> new AssignFieldPathUpdate(docType, reader); + case ADD -> new AddFieldPathUpdate(docType, reader); + case REMOVE -> new RemoveFieldPathUpdate(docType, reader); + }; } @Override @@ -153,10 +150,10 @@ public abstract class FieldPathUpdate { FieldPathUpdate that = (FieldPathUpdate) o; - if (docType != null ? !docType.equals(that.docType) : that.docType != null) return false; - if (originalFieldPath != null ? !originalFieldPath.equals(that.originalFieldPath) : that.originalFieldPath != null) + if (!Objects.equals(docType, that.docType)) return false; + if (!Objects.equals(originalFieldPath, that.originalFieldPath)) return false; - if (whereClause != null ? !whereClause.equals(that.whereClause) : that.whereClause != null) return false; + if (!Objects.equals(whereClause, that.whereClause)) return false; return true; } diff --git a/document/src/main/java/com/yahoo/vespaxmlparser/VespaXMLUpdateReader.java b/document/src/main/java/com/yahoo/vespaxmlparser/VespaXMLUpdateReader.java index 656fb8dd033..334a994ebe8 100644 --- a/document/src/main/java/com/yahoo/vespaxmlparser/VespaXMLUpdateReader.java +++ b/document/src/main/java/com/yahoo/vespaxmlparser/VespaXMLUpdateReader.java @@ -1,7 +1,17 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespaxmlparser; -import com.yahoo.document.*; +import com.yahoo.document.ArrayDataType; +import com.yahoo.document.DataType; +import com.yahoo.document.DocumentId; +import com.yahoo.document.DocumentType; +import com.yahoo.document.DocumentTypeManager; +import com.yahoo.document.DocumentUpdate; +import com.yahoo.document.Field; +import com.yahoo.document.FieldPath; +import com.yahoo.document.MapDataType; +import com.yahoo.document.NumericDataType; +import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.document.datatypes.IntegerFieldValue; diff --git a/document/src/test/java/com/yahoo/document/DocumentTypeTestCase.java b/document/src/test/java/com/yahoo/document/DocumentTypeTestCase.java index 5f8e95a2b4f..17d1d745f6a 100644 --- a/document/src/test/java/com/yahoo/document/DocumentTypeTestCase.java +++ b/document/src/test/java/com/yahoo/document/DocumentTypeTestCase.java @@ -3,15 +3,14 @@ package com.yahoo.document; import org.junit.Test; -import java.util.Arrays; -import java.util.Collections; import java.util.Iterator; +import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; /** * @author Thomas Gundersen @@ -37,7 +36,7 @@ public class DocumentTypeTestCase { root.addField("rootfield1", DataType.STRING); root.addField("rootfield2", DataType.STRING); root.addField("rootfield3", DataType.STRING); - root.addFieldSets(Collections.singletonMap(DocumentType.DOCUMENT, Arrays.asList("rootfield2"))); + root.addFieldSets(Map.of(DocumentType.DOCUMENT, List.of("rootfield2"))); assertEquals(1, root.fieldSet().size()); assertEquals("rootfield2", root.fieldSet().iterator().next().getName()); assertEquals(3, root.fieldSetAll().size()); @@ -49,25 +48,25 @@ public class DocumentTypeTestCase { DocumentType root = new DocumentType("root"); root.addField("rootfield", DataType.STRING); - root.addFieldSets(Collections.singletonMap(DocumentType.DOCUMENT, Arrays.asList("rootfield"))); + root.addFieldSets(Map.of(DocumentType.DOCUMENT, List.of("rootfield"))); DocumentType parent1 = new DocumentType("parent1"); parent1.addField("overridden", DataType.STRING); parent1.addField("parent1field", DataType.STRING); parent1.inherit(root); - parent1.addFieldSets(Collections.singletonMap(DocumentType.DOCUMENT, Arrays.asList("parent1field", "overridden"))); + parent1.addFieldSets(Map.of(DocumentType.DOCUMENT, List.of("parent1field", "overridden"))); DocumentType parent2 = new DocumentType("parent2"); parent2.addField("parent2field", DataType.STRING); parent2.inherit(root); - parent2.addFieldSets(Collections.singletonMap(DocumentType.DOCUMENT, Arrays.asList("parent2field"))); + parent2.addFieldSets(Map.of(DocumentType.DOCUMENT, List.of("parent2field"))); DocumentType child = new DocumentType("child"); child.addField("childfield", DataType.INT); child.addField("overridden", DataType.STRING); child.inherit(parent1); child.inherit(parent2); - child.addFieldSets(Collections.singletonMap(DocumentType.DOCUMENT, Arrays.asList("childfield", "overridden"))); + child.addFieldSets(Map.of(DocumentType.DOCUMENT, List.of("childfield", "overridden"))); typeManager.register(root); typeManager.register(parent1); @@ -77,19 +76,19 @@ public class DocumentTypeTestCase { Iterator inherited = child.getInheritedTypes().iterator(); assertEquals(parent1, inherited.next()); assertEquals(parent2, inherited.next()); - assertTrue(!inherited.hasNext()); + assertFalse(inherited.hasNext()); inherited = parent1.getInheritedTypes().iterator(); assertEquals(root, inherited.next()); - assertTrue(!inherited.hasNext()); + assertFalse(inherited.hasNext()); inherited = parent2.getInheritedTypes().iterator(); assertEquals(root, inherited.next()); - assertTrue(!inherited.hasNext()); + assertFalse(inherited.hasNext()); inherited = root.getInheritedTypes().iterator(); assertEquals(DataType.DOCUMENT, inherited.next()); - assertTrue(!inherited.hasNext()); + assertFalse(inherited.hasNext()); Iterator fields = child.fieldSet().iterator(); Field field; diff --git a/document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java b/document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java index aa043a25d78..e72d3720024 100644 --- a/document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java +++ b/document/src/test/java/com/yahoo/document/json/JsonReaderTestCase.java @@ -20,7 +20,6 @@ import com.yahoo.document.MapDataType; import com.yahoo.document.PositionDataType; import com.yahoo.document.StructDataType; import com.yahoo.document.TensorDataType; -import com.yahoo.document.TestAndSetCondition; import com.yahoo.document.WeightedSetDataType; import com.yahoo.document.datatypes.Array; import com.yahoo.document.datatypes.BoolFieldValue; @@ -32,7 +31,6 @@ import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.document.datatypes.Struct; import com.yahoo.document.datatypes.TensorFieldValue; import com.yahoo.document.datatypes.WeightedSet; -import com.yahoo.document.fieldpathupdate.FieldPathUpdate; import com.yahoo.document.internal.GeoPosType; import com.yahoo.document.json.readers.DocumentParseInfo; import com.yahoo.document.json.readers.VespaJsonDocumentReader; @@ -64,7 +62,6 @@ import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collections; diff --git a/document/src/test/java/com/yahoo/document/select/DocumentSelectorTestCase.java b/document/src/test/java/com/yahoo/document/select/DocumentSelectorTestCase.java index 63255f90919..b09d33a2fe4 100644 --- a/document/src/test/java/com/yahoo/document/select/DocumentSelectorTestCase.java +++ b/document/src/test/java/com/yahoo/document/select/DocumentSelectorTestCase.java @@ -32,7 +32,6 @@ import org.junit.Before; import org.junit.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -852,10 +851,10 @@ public class DocumentSelectorTestCase { @Test public void testThatSelectionIsConvertedToQueries() throws ParseException { - assertThatQueriesAreCreated("music.expire > now()", Arrays.asList("music"), Arrays.asList("expire:>now(0)")); - assertThatQueriesAreCreated("music.expire > now() - 300", Arrays.asList("music"), Arrays.asList("expire:>now(300)")); - assertThatQueriesAreCreated("music.expire > now() - 300 and video.expire > now() - 3600", Arrays.asList("music", "video"), Arrays.asList("expire:>now(300)", "expire:>now(3600)")); - assertThatQueriesAreCreated("music.expire > now() - 300 or video", Arrays.asList("music"), Arrays.asList("expire:>now(300)")); + assertThatQueriesAreCreated("music.expire > now()", List.of("music"), List.of("expire:>now(0)")); + assertThatQueriesAreCreated("music.expire > now() - 300", List.of("music"), List.of("expire:>now(300)")); + assertThatQueriesAreCreated("music.expire > now() - 300 and video.expire > now() - 3600", List.of("music", "video"), List.of("expire:>now(300)", "expire:>now(3600)")); + assertThatQueriesAreCreated("music.expire > now() - 300 or video", List.of("music"), List.of("expire:>now(300)")); assertVisitWithInvalidNowFails("music.field1 > now() - 300 and music.field2 > now() - 300", "Specifying multiple document types is not allowed"); assertVisitWithInvalidNowFails("music.field1 > now() - 300 and video.field1 > now() and music.field2 > now() - 300", "Specifying multiple document types is not allowed"); assertVisitWithInvalidNowFails("now() > music.field", "Left hand side of comparison must be a document field"); diff --git a/documentapi/src/main/java/com/yahoo/documentapi/messagebus/MessageBusVisitorSession.java b/documentapi/src/main/java/com/yahoo/documentapi/messagebus/MessageBusVisitorSession.java index 68a8f964575..21771558f05 100755..100644 --- a/documentapi/src/main/java/com/yahoo/documentapi/messagebus/MessageBusVisitorSession.java +++ b/documentapi/src/main/java/com/yahoo/documentapi/messagebus/MessageBusVisitorSession.java @@ -18,6 +18,8 @@ import com.yahoo.documentapi.messagebus.protocol.DocumentMessage; import com.yahoo.documentapi.messagebus.protocol.DocumentProtocol; import com.yahoo.documentapi.messagebus.protocol.VisitorInfoMessage; import com.yahoo.documentapi.messagebus.protocol.WrongDistributionReply; + +import java.util.List; import java.util.logging.Level; import com.yahoo.messagebus.DestinationSession; import com.yahoo.messagebus.DestinationSessionParams; @@ -37,7 +39,6 @@ import com.yahoo.messagebus.routing.RoutingTable; import com.yahoo.vdslib.VisitorStatistics; import com.yahoo.vdslib.state.ClusterState; -import java.util.Arrays; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -162,14 +163,13 @@ public class MessageBusVisitorSession implements VisitorSession { } VisitorControlHandler.CompletionCode toCompletionCode() { - switch (state) { - case COMPLETED: return VisitorControlHandler.CompletionCode.SUCCESS; - case ABORTED: return VisitorControlHandler.CompletionCode.ABORTED; - case FAILED: return VisitorControlHandler.CompletionCode.FAILURE; - case TIMED_OUT: return VisitorControlHandler.CompletionCode.TIMEOUT; - default: - throw new IllegalStateException("Current state did not have a valid value: " + state); - } + return switch (state) { + case COMPLETED -> VisitorControlHandler.CompletionCode.SUCCESS; + case ABORTED -> VisitorControlHandler.CompletionCode.ABORTED; + case FAILED -> VisitorControlHandler.CompletionCode.FAILURE; + case TIMED_OUT -> VisitorControlHandler.CompletionCode.TIMEOUT; + default -> throw new IllegalStateException("Current state did not have a valid value: " + state); + }; } public boolean failed() { @@ -312,9 +312,7 @@ public class MessageBusVisitorSession implements VisitorSession { return sessionCounter.incrementAndGet(); } private static String createSessionName() { - StringBuilder sb = new StringBuilder(); - sb.append("visitor-").append(getNextSessionId()).append('-').append(System.currentTimeMillis()); - return sb.toString(); + return "visitor-" + getNextSessionId() + '-' + System.currentTimeMillis(); } private final VisitorParameters params; @@ -647,7 +645,7 @@ public class MessageBusVisitorSession implements VisitorSession { msg.getTrace().setLevel(params.getTraceLevel()); msg.setTimeRemaining(messageTimeoutMs); - msg.setBuckets(Arrays.asList(bucket.getSuperbucket(), bucket.getProgress())); + msg.setBuckets(List.of(bucket.getSuperbucket(), bucket.getProgress())); msg.setDocumentSelection(params.getDocumentSelection()); msg.setBucketSpace(params.getBucketSpace()); msg.setFromTimestamp(params.getFromTimestamp()); @@ -881,7 +879,7 @@ public class MessageBusVisitorSession implements VisitorSession { } try { - if (msg.getErrorMessage().length() > 0) { + if (!msg.getErrorMessage().isEmpty()) { params.getControlHandler().onVisitorError(msg.getErrorMessage()); } synchronized (progress.getToken()) { diff --git a/documentapi/src/main/java/com/yahoo/documentapi/messagebus/protocol/DocumentProtocol.java b/documentapi/src/main/java/com/yahoo/documentapi/messagebus/protocol/DocumentProtocol.java index 0a0fc5f4991..5eb5b6f2567 100755..100644 --- a/documentapi/src/main/java/com/yahoo/documentapi/messagebus/protocol/DocumentProtocol.java +++ b/documentapi/src/main/java/com/yahoo/documentapi/messagebus/protocol/DocumentProtocol.java @@ -16,7 +16,6 @@ import com.yahoo.messagebus.routing.RoutingPolicy; import com.yahoo.text.Utf8String; import com.yahoo.vespa.config.content.DistributionConfig; -import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; @@ -283,7 +282,7 @@ public class DocumentProtocol implements Protocol { // Prepare version specifications to use when adding routable factories. VersionSpecification version6 = new VersionSpecification(6, 221); - List<VersionSpecification> from6 = Collections.singletonList(version6); + List<VersionSpecification> from6 = List.of(version6); // 6.x serialization (keep alphabetized please) putRoutableFactory(MESSAGE_CREATEVISITOR, new RoutableFactories60.CreateVisitorMessageFactory(), from6); @@ -322,7 +321,7 @@ public class DocumentProtocol implements Protocol { private void registerV8Factories() { var version8 = new VersionSpecification(8, 310); // Must be same as in C++ impl - var from8 = Collections.singletonList(version8); + var from8 = List.of(version8); putRoutableFactory(MESSAGE_CREATEVISITOR, RoutableFactories80.createCreateVisitorMessageFactory(), from8); putRoutableFactory(MESSAGE_DESTROYVISITOR, RoutableFactories80.createDestroyVisitorMessageFactory(), from8); diff --git a/documentapi/src/main/java/com/yahoo/documentapi/messagebus/systemstate/rule/Location.java b/documentapi/src/main/java/com/yahoo/documentapi/messagebus/systemstate/rule/Location.java index 4ca6fb03821..77ec8f175df 100755..100644 --- a/documentapi/src/main/java/com/yahoo/documentapi/messagebus/systemstate/rule/Location.java +++ b/documentapi/src/main/java/com/yahoo/documentapi/messagebus/systemstate/rule/Location.java @@ -3,7 +3,6 @@ package com.yahoo.documentapi.messagebus.systemstate.rule; import java.util.ArrayList; import java.util.List; -import java.util.Arrays; /** * @author Simon Thoresen Hult @@ -25,7 +24,7 @@ public class Location { * @param loc The location string to parse. */ public Location(String loc) { - items.addAll(Arrays.asList(loc.split("/"))); + items.addAll(List.of(loc.split("/"))); normalize(); } diff --git a/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/LoadBalancerTestCase.java b/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/LoadBalancerTestCase.java index 0bbd3549869..a9d6a7a4cbf 100644 --- a/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/LoadBalancerTestCase.java +++ b/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/LoadBalancerTestCase.java @@ -4,7 +4,6 @@ package com.yahoo.documentapi.messagebus.protocol; import com.yahoo.jrt.slobrok.api.Mirror; import org.junit.Test; -import java.util.Arrays; import java.util.List; import java.util.Random; @@ -55,7 +54,7 @@ public class LoadBalancerTestCase { public void testAdaptiveLoadBalancer() { LoadBalancer lb = new AdaptiveLoadBalancer("foo", new Random(1)); - List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1"), + List<Mirror.Entry> entries = List.of(new Mirror.Entry("foo/0/default", "tcp/bar:1"), new Mirror.Entry("foo/1/default", "tcp/bar:2"), new Mirror.Entry("foo/2/default", "tcp/bar:3")); List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights(); @@ -112,7 +111,7 @@ public class LoadBalancerTestCase { private void verifyLoadBalancerOneItemOnly(LoadBalancer lb) { - List<Mirror.Entry> entries = Arrays.asList(new Mirror.Entry("foo/0/default", "tcp/bar:1") ); + List<Mirror.Entry> entries = List.of(new Mirror.Entry("foo/0/default", "tcp/bar:1") ); List<LoadBalancer.NodeMetrics> weights = lb.getNodeWeights(); assertEquals("foo/0/default" , lb.getRecipient(entries).entry.getName()); diff --git a/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PolicyTestCase.java b/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PolicyTestCase.java index 25bdeb60013..472ce00aac3 100755..100644 --- a/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PolicyTestCase.java +++ b/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PolicyTestCase.java @@ -52,7 +52,6 @@ import org.junit.Ignore; import org.junit.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; @@ -116,12 +115,12 @@ public class PolicyTestCase { frame.setHop(new HopSpec("test", "[AND]") .addRecipient("foo") .addRecipient("bar")); - frame.assertSelect(Arrays.asList("foo", "bar")); + frame.assertSelect(List.of("foo", "bar")); frame.setHop(new HopSpec("test", "[AND:baz]") .addRecipient("foo") .addRecipient("bar")); - frame.assertSelect(Arrays.asList("baz")); // param precedes recipients + frame.assertSelect(List.of("baz")); // param precedes recipients frame.setHop(new HopSpec("test", "[AND:foo]")); frame.assertMergeOneReply("foo"); @@ -414,10 +413,10 @@ public class PolicyTestCase { PolicyTestFrame frame = createFrameWithTwoRoutes(); frame.setMessage(createRemove("id:ns:testdoc::1")); - frame.assertSelect(Arrays.asList("testdoc-route")); + frame.assertSelect(List.of("testdoc-route")); frame.setMessage(createRemove("id:ns:other::1")); - frame.assertSelect(Arrays.asList("other-route")); + frame.assertSelect(List.of("other-route")); frame.destroy(); } @@ -426,10 +425,10 @@ public class PolicyTestCase { PolicyTestFrame frame = createFrameWithTwoRoutes(); frame.setMessage(createGet("id:ns:testdoc::1")); - frame.assertSelect(Arrays.asList("testdoc-route")); + frame.assertSelect(List.of("testdoc-route")); frame.setMessage(createGet("id:ns:other::1")); - frame.assertSelect(Arrays.asList("other-route")); + frame.assertSelect(List.of("other-route")); frame.destroy(); } @@ -586,19 +585,19 @@ public class PolicyTestCase { "route[1].feed \"myfeed\"\n]").addRecipient("foo").addRecipient("bar")); frame.setMessage(new GetDocumentMessage(new DocumentId("id:ns:testdoc::"), "fieldSet")); - frame.assertSelect(Arrays.asList("foo")); + frame.assertSelect(List.of("foo")); Message put = new PutDocumentMessage(new DocumentPut(new Document(manager.getDocumentType("testdoc"), new DocumentId("id:ns:testdoc::")))); frame.setMessage(put); - frame.assertSelect(Arrays.asList("foo")); + frame.assertSelect(List.of("foo")); frame.setMessage(new RemoveDocumentMessage(new DocumentId("id:ns:testdoc::"))); - frame.assertSelect(Arrays.asList("foo")); + frame.assertSelect(List.of("foo")); frame.setMessage(new UpdateDocumentMessage(new DocumentUpdate(manager.getDocumentType("testdoc"), new DocumentId("id:ns:testdoc::")))); - frame.assertSelect(Arrays.asList("foo")); + frame.assertSelect(List.of("foo")); frame.setMessage(put); frame.assertMergeOneReply("foo"); @@ -619,13 +618,13 @@ public class PolicyTestCase { "route[1].feed \"myfeed\"\n]").addRecipient("foo").addRecipient("bar")); frame.setMessage(new GetDocumentMessage(new DocumentId("id:ns:testdoc::"), "fieldSet")); - frame.assertSelect(Arrays.asList("foo")); + frame.assertSelect(List.of("foo")); Document doc = new Document(manager.getDocumentType("testdoc"), new DocumentId("id:ns:testdoc::")); doc.setFieldValue("intfield", 3000); Message put = new PutDocumentMessage(new DocumentPut(doc)); frame.setMessage(put); - frame.assertSelect(Arrays.asList("foo")); + frame.assertSelect(List.of("foo")); frame.setMessage(put); frame.assertMergeOneReply("foo"); @@ -653,7 +652,7 @@ public class PolicyTestCase { frame.setMessage(new UpdateDocumentMessage(new DocumentUpdate(manager.getDocumentType("testdoc"), new DocumentId("id:ns:testdoc::")))); - frame.assertSelect(Arrays.asList("docproc/cluster.foo")); + frame.assertSelect(List.of("docproc/cluster.foo")); frame.destroy(); } @@ -667,7 +666,7 @@ public class PolicyTestCase { assertTrue(frame.waitSlobrok("docproc/cluster.default/*/chain.default", 1)); frame.setHop(new HopSpec("test", "[LoadBalancer:cluster=docproc/cluster.default;session=chain.default]")); - assertSelect(frame, 1, Arrays.asList(frame.getNetwork().getConnectionSpec() + "/chain.default")); + assertSelect(frame, 1, List.of(frame.getNetwork().getConnectionSpec() + "/chain.default")); frame.destroy(); } @@ -685,16 +684,16 @@ public class PolicyTestCase { .addRecipient("docproc/cluster.default/3/chain.default") .addRecipient("docproc/cluster.default/6/chain.default") .addRecipient("docproc/cluster.default/9/chain.default")); - assertSelect(frame, 32, Arrays.asList("docproc/cluster.default/3/chain.default", + assertSelect(frame, 32, List.of("docproc/cluster.default/3/chain.default", "docproc/cluster.default/6/chain.default", "docproc/cluster.default/9/chain.default")); frame.getNetwork().unregisterSession("6/chain.default"); assertTrue(frame.waitSlobrok("docproc/cluster.default/*/chain.default", 9)); - assertSelect(frame, 32, Arrays.asList("docproc/cluster.default/3/chain.default", + assertSelect(frame, 32, List.of("docproc/cluster.default/3/chain.default", "docproc/cluster.default/9/chain.default")); frame.getNetwork().unregisterSession("3/chain.default"); assertTrue(frame.waitSlobrok("docproc/cluster.default/*/chain.default", 8)); - assertSelect(frame, 32, Arrays.asList("docproc/cluster.default/9/chain.default")); + assertSelect(frame, 32, List.of("docproc/cluster.default/9/chain.default")); frame.getNetwork().unregisterSession("9/chain.default"); assertTrue(frame.waitSlobrok("docproc/cluster.default/*/chain.default", 7)); assertSelect(frame, 32, new ArrayList<>()); diff --git a/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PolicyTestFrame.java b/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PolicyTestFrame.java index f51f285723f..8e2fcdcd946 100755..100644 --- a/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PolicyTestFrame.java +++ b/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PolicyTestFrame.java @@ -28,7 +28,6 @@ import com.yahoo.messagebus.test.SimpleProtocol; import com.yahoo.messagebus.test.SimpleReply; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -219,7 +218,7 @@ public class PolicyTestFrame { * @param recipient The expected recipient. */ public void assertMergeOneReply(String recipient) { - assertSelect(Arrays.asList(recipient)); + assertSelect(List.of(recipient)); Map<String, Integer> replies = new HashMap<>(); replies.put(recipient, ErrorCode.NONE); @@ -237,7 +236,7 @@ public class PolicyTestFrame { * @param recipientTwo The second expected recipient. */ public void assertMergeTwoReplies(String recipientOne, String recipientTwo) { - assertSelect(Arrays.asList(recipientOne, recipientTwo)); + assertSelect(List.of(recipientOne, recipientTwo)); Map<String, Integer> replies = new HashMap<>(); replies.put(recipientOne, ErrorCode.NONE); @@ -254,7 +253,7 @@ public class PolicyTestFrame { replies.put(recipientOne, ErrorCode.TRANSIENT_ERROR); replies.put(recipientTwo, ErrorCode.TRANSIENT_ERROR); - assertMerge(replies, Arrays.asList(ErrorCode.TRANSIENT_ERROR, ErrorCode.TRANSIENT_ERROR), List.of(recipientOne, recipientTwo)); + assertMerge(replies, List.of(ErrorCode.TRANSIENT_ERROR, ErrorCode.TRANSIENT_ERROR), List.of(recipientOne, recipientTwo)); replies.put(recipientOne, ErrorCode.NONE); replies.put(recipientTwo, DocumentProtocol.ERROR_MESSAGE_IGNORED); diff --git a/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PriorityTestCase.java b/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PriorityTestCase.java index 681c47209cb..bca2922ab2c 100644 --- a/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PriorityTestCase.java +++ b/documentapi/src/test/java/com/yahoo/documentapi/messagebus/protocol/test/PriorityTestCase.java @@ -8,7 +8,6 @@ import org.junit.Test; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; @@ -26,7 +25,7 @@ public class PriorityTestCase { String path = "test/crosslanguagefiles/5.1-Priority.txt"; BufferedReader in = new BufferedReader(new FileReader(path)); - List<Priority> expected = new LinkedList<Priority>(Arrays.asList(Priority.values())); + List<Priority> expected = new LinkedList<Priority>(List.of(Priority.values())); String str; while ((str = in.readLine()) != null) { String arr[] = str.split(":", 2); diff --git a/documentgen-test/src/test/java/com/yahoo/vespa/config/DocumentGenPluginTest.java b/documentgen-test/src/test/java/com/yahoo/vespa/config/DocumentGenPluginTest.java index cae11d66d13..625906fc6a2 100644 --- a/documentgen-test/src/test/java/com/yahoo/vespa/config/DocumentGenPluginTest.java +++ b/documentgen-test/src/test/java/com/yahoo/vespa/config/DocumentGenPluginTest.java @@ -66,7 +66,6 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -538,7 +537,7 @@ public class DocumentGenPluginTest { } private static DocumentTypeManager typeManagerFromSDs(String... files) { - var cfg = getDocumentConfig(Arrays.asList(files)); + var cfg = getDocumentConfig(List.of(files)); return new DocumentTypeManager(cfg); } diff --git a/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileDownloaderTest.java b/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileDownloaderTest.java index 2442ffa7b1f..0007c4e0127 100644 --- a/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileDownloaderTest.java +++ b/filedistribution/src/test/java/com/yahoo/vespa/filedistribution/FileDownloaderTest.java @@ -23,7 +23,7 @@ import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; -import java.util.Arrays; +import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -148,7 +148,7 @@ public class FileDownloaderTest { File barFile = new File(subdir, "really-long-filename-over-100-bytes-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); IOUtils.writeFile(barFile, "bar", false); - File tarFile = new FileReferenceCompressor(compressed, gzip).compress(tempPath.toFile(), Arrays.asList(fooFile, barFile), new File(tempPath.toFile(), filename)); + File tarFile = new FileReferenceCompressor(compressed, gzip).compress(tempPath.toFile(), List.of(fooFile, barFile), new File(tempPath.toFile(), filename)); byte[] tarredContent = IOUtils.readFileBytes(tarFile); receiveFile(fileReference, filename, compressed, tarredContent); Optional<File> downloadedFile = getFile(fileReference); diff --git a/flags/src/main/java/com/yahoo/vespa/flags/OrderedFlagSource.java b/flags/src/main/java/com/yahoo/vespa/flags/OrderedFlagSource.java index 4f191c06022..a5d88010a24 100644 --- a/flags/src/main/java/com/yahoo/vespa/flags/OrderedFlagSource.java +++ b/flags/src/main/java/com/yahoo/vespa/flags/OrderedFlagSource.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.flags; -import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -18,7 +17,7 @@ public class OrderedFlagSource implements FlagSource { * @param sources Flag sources in descending priority order. */ public OrderedFlagSource(FlagSource... sources) { - this.sources = Arrays.asList(sources); + this.sources = List.of(sources); } @Override diff --git a/flags/src/main/java/com/yahoo/vespa/flags/file/FlagDbFile.java b/flags/src/main/java/com/yahoo/vespa/flags/file/FlagDbFile.java index c4597d1d3b4..73803e5bc5f 100644 --- a/flags/src/main/java/com/yahoo/vespa/flags/file/FlagDbFile.java +++ b/flags/src/main/java/com/yahoo/vespa/flags/file/FlagDbFile.java @@ -14,7 +14,6 @@ import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -55,7 +54,7 @@ public class FlagDbFile { public Map<FlagId, FlagData> read() { Optional<byte[]> bytes = readFile(); - if (!bytes.isPresent()) return Collections.emptyMap(); + if (!bytes.isPresent()) return Map.of(); return FlagData.deserializeList(bytes.get()).stream().collect(Collectors.toMap(FlagData::id, Function.identity())); } diff --git a/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java b/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java index 4ea4f8ab638..d8530bf0a9d 100644 --- a/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java +++ b/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java @@ -12,7 +12,6 @@ import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; -import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -68,7 +67,7 @@ public class FlagDbFileTest { assertThat(anotherReadDataMap, IsMapContaining.hasKey(id3)); assertThat(anotherReadDataMap.get(id1).serializeToJson(), equalTo("{\"id\":\"id1\",\"attributes\":{\"hostname\":\"h1\"}}")); - assertThat(flagDb.sync(Collections.emptyMap()), equalTo(true)); + assertThat(flagDb.sync(Map.of()), equalTo(true)); assertThat(getDbContent(), equalTo("{\"flags\":[]}")); } diff --git a/hosted-api/src/test/java/ai/vespa/hosted/api/TestDescriptorTest.java b/hosted-api/src/test/java/ai/vespa/hosted/api/TestDescriptorTest.java index ca4e6f6963c..f5674b15a79 100644 --- a/hosted-api/src/test/java/ai/vespa/hosted/api/TestDescriptorTest.java +++ b/hosted-api/src/test/java/ai/vespa/hosted/api/TestDescriptorTest.java @@ -5,7 +5,6 @@ import com.yahoo.test.json.JsonTestHelper; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Collections; import java.util.List; /** @@ -31,13 +30,13 @@ public class TestDescriptorTest { Assertions.assertIterableEquals(List.of("ai.vespa.test.SystemTest1", "ai.vespa.test.SystemTest2"), systemTests); var stagingTests = testClassDescriptor.getConfiguredTests(TestDescriptor.TestCategory.stagingtest); - Assertions.assertIterableEquals(Collections.emptyList(), stagingTests); + Assertions.assertIterableEquals(List.of(), stagingTests); var stagingSetupTests = testClassDescriptor.getConfiguredTests(TestDescriptor.TestCategory.stagingtest); - Assertions.assertIterableEquals(Collections.emptyList(), stagingSetupTests); + Assertions.assertIterableEquals(List.of(), stagingSetupTests); var productionTests = testClassDescriptor.getConfiguredTests(TestDescriptor.TestCategory.productiontest); - Assertions.assertIterableEquals(Collections.emptyList(), productionTests); + Assertions.assertIterableEquals(List.of(), productionTests); } @Test diff --git a/http-client/src/main/java/ai/vespa/hosted/client/HttpClient.java b/http-client/src/main/java/ai/vespa/hosted/client/HttpClient.java index 57a7615421d..c17ae63fda2 100644 --- a/http-client/src/main/java/ai/vespa/hosted/client/HttpClient.java +++ b/http-client/src/main/java/ai/vespa/hosted/client/HttpClient.java @@ -83,7 +83,7 @@ public interface HttpClient extends Closeable { /** Sets query parameters without a value, like {@code ?debug&recursive}. */ default RequestBuilder emptyParameters(String... keys) { - return emptyParameters(Arrays.asList(keys)); + return emptyParameters(List.of(keys)); } /** Sets query parameters without a value, like {@code ?debug&recursive}. */ diff --git a/http-client/src/test/java/ai/vespa/hosted/client/ApacheHttpClientTest.java b/http-client/src/test/java/ai/vespa/hosted/client/ApacheHttpClientTest.java index a80d80bb248..69e7ab6f744 100644 --- a/http-client/src/test/java/ai/vespa/hosted/client/ApacheHttpClientTest.java +++ b/http-client/src/test/java/ai/vespa/hosted/client/ApacheHttpClientTest.java @@ -60,7 +60,7 @@ class ApacheHttpClientTest { URI.create("http://localhost:" + server.port() + "/"))), Method.GET) .at("root") - .parameters("query", "foo") + .parameters("query", "foo", null, null) .discard()); server.verify(2, getRequestedFor(urlEqualTo("/root?query=foo"))); server.verify(2, anyRequestedFor(anyUrl())); diff --git a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java index c843b77e359..0f4477b49cd 100644 --- a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java +++ b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java @@ -8,7 +8,7 @@ import javax.net.ssl.SSLException; import java.io.IOException; import java.net.ConnectException; import java.time.Duration; -import java.util.Arrays; +import java.util.List; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -105,7 +105,7 @@ public class DelayedConnectionLevelRetryHandlerTest { DelayedConnectionLevelRetryHandler handler = DelayedConnectionLevelRetryHandler.Builder .withFixedDelay(Duration.ofSeconds(2), maxRetries) - .retryForExceptions(Arrays.asList(SSLException.class, ConnectException.class)) + .retryForExceptions(List.of(SSLException.class, ConnectException.class)) .withSleeper(mock(Sleeper.class)) .build(); @@ -122,7 +122,7 @@ public class DelayedConnectionLevelRetryHandlerTest { void does_not_retry_for_non_listed_exception() { DelayedConnectionLevelRetryHandler handler = DelayedConnectionLevelRetryHandler.Builder .withFixedDelay(Duration.ofSeconds(2), 2) - .retryForExceptions(Arrays.asList(SSLException.class, ConnectException.class)) + .retryForExceptions(List.of(SSLException.class, ConnectException.class)) .withSleeper(mock(Sleeper.class)) .build(); diff --git a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java index b7d15f3cd12..83c87ab3a23 100644 --- a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java +++ b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java @@ -10,7 +10,6 @@ import org.apache.http.message.BasicStatusLine; import org.junit.jupiter.api.Test; import java.time.Duration; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -84,7 +83,7 @@ public class DelayedResponseLevelRetryHandlerTest { HttpClientContext ctx = new HttpClientContext(); int lastExecutionCount = maxRetries + 1; List<Duration> expectedIntervals = - Arrays.asList( + List.of( startDelay, Duration.ofSeconds(1), Duration.ofSeconds(2), Duration.ofSeconds(4), Duration.ofSeconds(5), Duration.ofSeconds(5), Duration.ofSeconds(5), Duration.ofSeconds(5), Duration.ofSeconds(5), Duration.ofSeconds(5), Duration.ofSeconds(5)); @@ -100,7 +99,7 @@ public class DelayedResponseLevelRetryHandlerTest { DelayedResponseLevelRetryHandler handler = DelayedResponseLevelRetryHandler.Builder .withFixedDelay(Duration.ofSeconds(2), maxRetries) - .retryForStatusCodes(Arrays.asList(HttpStatus.SC_SERVICE_UNAVAILABLE, HttpStatus.SC_BAD_GATEWAY)) + .retryForStatusCodes(List.of(HttpStatus.SC_SERVICE_UNAVAILABLE, HttpStatus.SC_BAD_GATEWAY)) .build(); HttpResponse response = createResponse(HttpStatus.SC_SERVICE_UNAVAILABLE); @@ -116,7 +115,7 @@ public class DelayedResponseLevelRetryHandlerTest { void does_not_retry_for_non_listed_exception() { DelayedResponseLevelRetryHandler handler = DelayedResponseLevelRetryHandler.Builder .withFixedDelay(Duration.ofSeconds(2), 2) - .retryForStatusCodes(Arrays.asList(HttpStatus.SC_SERVICE_UNAVAILABLE, HttpStatus.SC_BAD_GATEWAY)) + .retryForStatusCodes(List.of(HttpStatus.SC_SERVICE_UNAVAILABLE, HttpStatus.SC_BAD_GATEWAY)) .build(); HttpResponse response = createResponse(HttpStatus.SC_OK); diff --git a/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/CatExpression.java b/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/CatExpression.java index 6e90142d8a1..c12239a99c3 100644 --- a/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/CatExpression.java +++ b/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/CatExpression.java @@ -19,7 +19,7 @@ import java.util.*; public final class CatExpression extends ExpressionList<Expression> { public CatExpression(Expression... lst) { - this(Arrays.asList(lst)); + this(List.of(lst)); } public CatExpression(Collection<? extends Expression> lst) { diff --git a/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/ChoiceExpression.java b/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/ChoiceExpression.java index 9038fbad33c..7a556bd90d0 100644 --- a/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/ChoiceExpression.java +++ b/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/ChoiceExpression.java @@ -5,7 +5,6 @@ import com.yahoo.document.DataType; import com.yahoo.document.datatypes.FieldValue; import com.yahoo.vespa.indexinglanguage.ExpressionConverter; -import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; @@ -25,7 +24,7 @@ public class ChoiceExpression extends ExpressionList<Expression> { } public ChoiceExpression(Expression... choices) { - this(Arrays.asList(choices)); + this(List.of(choices)); } public ChoiceExpression(Collection<? extends Expression> choices) { diff --git a/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/ScriptExpression.java b/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/ScriptExpression.java index 7d180b9fd7a..810ff261f2d 100644 --- a/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/ScriptExpression.java +++ b/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/ScriptExpression.java @@ -12,9 +12,7 @@ import com.yahoo.vespa.indexinglanguage.ScriptParserContext; import com.yahoo.vespa.indexinglanguage.parser.IndexingInput; import com.yahoo.vespa.indexinglanguage.parser.ParseException; -import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -26,11 +24,11 @@ import java.util.Objects; public final class ScriptExpression extends ExpressionList<StatementExpression> { public ScriptExpression() { - this(Collections.emptyList()); + this(List.of()); } public ScriptExpression(StatementExpression... statements) { - this(Arrays.asList(statements)); + this(List.of(statements)); } public ScriptExpression(Collection<? extends StatementExpression> statements) { diff --git a/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/SelectInputExpression.java b/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/SelectInputExpression.java index 3d28f70cbd5..9c92dd452c3 100644 --- a/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/SelectInputExpression.java +++ b/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/SelectInputExpression.java @@ -10,7 +10,6 @@ import com.yahoo.vespa.indexinglanguage.ExpressionConverter; import com.yahoo.vespa.objects.ObjectOperation; import com.yahoo.vespa.objects.ObjectPredicate; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -25,7 +24,7 @@ public final class SelectInputExpression extends CompositeExpression { @SafeVarargs @SuppressWarnings("varargs") public SelectInputExpression(Pair<String, Expression>... cases) { - this(Arrays.asList(cases)); + this(List.of(cases)); } public SelectInputExpression(List<Pair<String, Expression>> cases) { diff --git a/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/StatementExpression.java b/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/StatementExpression.java index 2db6c760380..f9d8002100f 100644 --- a/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/StatementExpression.java +++ b/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/StatementExpression.java @@ -30,7 +30,7 @@ public final class StatementExpression extends ExpressionList<Expression> { private String outputField; public StatementExpression(Expression... lst) { - this(Arrays.asList(lst)); + this(Arrays.asList(lst)); //TODO Can contain null - necessary ? } public StatementExpression(Iterable<Expression> lst) { diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionConverterTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionConverterTestCase.java index 72a03e938fb..52a015137aa 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionConverterTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionConverterTestCase.java @@ -55,7 +55,6 @@ import com.yahoo.vespa.indexinglanguage.expressions.ZCurveExpression; import com.yahoo.vespa.indexinglanguage.linguistics.AnnotatorConfig; import org.junit.Test; -import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -109,7 +108,7 @@ public class ExpressionConverterTestCase { assertConvertable(new StatementExpression(new InputExpression("foo"))); assertConvertable(new SubstringExpression(6, 9)); assertConvertable(new SummaryExpression("foo")); - assertConvertable(new SwitchExpression(Collections.singletonMap("foo", (Expression)new IndexExpression("bar")), + assertConvertable(new SwitchExpression(Map.of("foo", (Expression)new IndexExpression("bar")), new InputExpression("baz"))); assertConvertable(new ThisExpression()); assertConvertable(new ToArrayExpression()); diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionSearcherTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionSearcherTestCase.java index 4a8348204a6..c4f71402afa 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionSearcherTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionSearcherTestCase.java @@ -17,8 +17,8 @@ import com.yahoo.vespa.indexinglanguage.expressions.StatementExpression; import com.yahoo.vespa.indexinglanguage.expressions.SwitchExpression; import org.junit.Test; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; +import java.util.Map; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -67,18 +67,18 @@ public class ExpressionSearcherTestCase { assertFound(exp, new ScriptExpression(new StatementExpression(new AttributeExpression("foo")), new StatementExpression(exp))); assertFound(exp, new SelectInputExpression( - Arrays.asList(new Pair<String, Expression>("foo", exp), - new Pair<String, Expression>("bar", new AttributeExpression("bar"))))); + List.of(new Pair<>("foo", exp), + new Pair<>("bar", new AttributeExpression("bar"))))); assertFound(exp, new SelectInputExpression( - Arrays.asList(new Pair<String, Expression>("foo", new AttributeExpression("bar")), - new Pair<String, Expression>("bar", exp)))); + List.of(new Pair<>("foo", new AttributeExpression("bar")), + new Pair<>("bar", exp)))); assertFound(exp, new StatementExpression(exp)); assertFound(exp, new StatementExpression(new AttributeExpression("foo"), exp)); assertFound(exp, new SwitchExpression( - Collections.singletonMap("foo", exp), + Map.of("foo", exp), new AttributeExpression("bar"))); assertFound(exp, new SwitchExpression( - Collections.singletonMap("foo", new AttributeExpression("bar")), + Map.of("foo", new AttributeExpression("bar")), exp)); } diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionVisitorTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionVisitorTestCase.java index 5bbf62bfff7..de512997b64 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionVisitorTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/ExpressionVisitorTestCase.java @@ -55,7 +55,8 @@ import com.yahoo.vespa.indexinglanguage.expressions.ZCurveExpression; import com.yahoo.vespa.indexinglanguage.linguistics.AnnotatorConfig; import org.junit.Test; -import java.util.Collections; + +import java.util.Map; import static org.junit.Assert.assertEquals; @@ -64,7 +65,6 @@ import static org.junit.Assert.assertEquals; */ public class ExpressionVisitorTestCase { - @SuppressWarnings("unchecked") @Test public void requireThatAllExpressionsAreVisited() { assertCount(3, new ArithmeticExpression(new InputExpression("foo"), ArithmeticExpression.Operator.ADD, @@ -96,8 +96,8 @@ public class ExpressionVisitorTestCase { assertCount(2, new ParenthesisExpression(new InputExpression("foo"))); assertCount(1, new RandomExpression(69)); assertCount(3, new ScriptExpression(new StatementExpression(new InputExpression("foo")))); - assertCount(3, new SelectInputExpression(new Pair<String, Expression>("foo", new IndexExpression("bar")), - new Pair<String, Expression>("bar", new IndexExpression("foo")))); + assertCount(3, new SelectInputExpression(new Pair<>("foo", new IndexExpression("bar")), + new Pair<>("bar", new IndexExpression("foo")))); assertCount(1, new SetLanguageExpression()); assertCount(1, new ConstantExpression(new IntegerFieldValue(69))); assertCount(1, new SetVarExpression("foo")); @@ -105,7 +105,7 @@ public class ExpressionVisitorTestCase { assertCount(2, new StatementExpression(new InputExpression("foo"))); assertCount(1, new SummaryExpression("foo")); assertCount(1, new SubstringExpression(6, 9)); - assertCount(3, new SwitchExpression(Collections.singletonMap("foo", (Expression)new IndexExpression("bar")), + assertCount(3, new SwitchExpression(Map.of("foo", (Expression)new IndexExpression("bar")), new InputExpression("baz"))); assertCount(1, new ThisExpression()); assertCount(1, new ToArrayExpression()); diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/CatTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/CatTestCase.java index 6403bbb24ac..17388f65656 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/CatTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/CatTestCase.java @@ -7,7 +7,8 @@ import com.yahoo.document.datatypes.*; import com.yahoo.vespa.indexinglanguage.SimpleTestAdapter; import org.junit.Test; -import java.util.Arrays; + +import java.util.List; import static org.junit.Assert.*; @@ -25,7 +26,7 @@ public class CatTestCase { assertEquals(2, exp.size()); assertSame(foo, exp.get(0)); assertSame(bar, exp.get(1)); - assertEquals(Arrays.asList(foo, bar), exp.asList()); + assertEquals(List.of(foo, bar), exp.asList()); } @Test @@ -33,11 +34,11 @@ public class CatTestCase { Expression foo = new AttributeExpression("foo"); Expression bar = new AttributeExpression("bar"); Expression exp = new CatExpression(foo, bar); - assertFalse(exp.equals(new Object())); - assertFalse(exp.equals(new StatementExpression(foo, bar))); - assertFalse(exp.equals(new CatExpression())); - assertFalse(exp.equals(new CatExpression(foo))); - assertFalse(exp.equals(new CatExpression(bar, foo))); + assertNotEquals(exp, new Object()); + assertNotEquals(exp, new StatementExpression(foo, bar)); + assertNotEquals(exp, new CatExpression()); + assertNotEquals(exp, new CatExpression(foo)); + assertNotEquals(exp, new CatExpression(bar, foo)); assertEquals(exp, new CatExpression(foo, bar)); assertEquals(exp.hashCode(), new CatExpression(foo, bar).hashCode()); } diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/IfThenTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/IfThenTestCase.java index 287398de030..c45b16beadb 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/IfThenTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/IfThenTestCase.java @@ -10,7 +10,6 @@ import com.yahoo.document.serialization.XmlStream; import com.yahoo.vespa.indexinglanguage.SimpleTestAdapter; import org.junit.Test; -import java.util.Arrays; import java.util.List; import static com.yahoo.vespa.indexinglanguage.expressions.ExpressionAssert.assertVerify; @@ -174,12 +173,12 @@ public class IfThenTestCase { @Test public void requireThatNumericValuesSupportNumericCompareTo() { - List<NumericFieldValue> sixes = Arrays.asList(new ByteFieldValue((byte)6), + List<NumericFieldValue> sixes = List.of(new ByteFieldValue((byte)6), new DoubleFieldValue(6.0), new FloatFieldValue(6.0f), new IntegerFieldValue(6), new LongFieldValue(6L)); - List<NumericFieldValue> nines = Arrays.asList(new ByteFieldValue((byte)9), + List<NumericFieldValue> nines = List.of(new ByteFieldValue((byte)9), new DoubleFieldValue(9.0), new FloatFieldValue(9.0f), new IntegerFieldValue(9), diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/ScriptTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/ScriptTestCase.java index df7f99d22d2..c6fb7c1db8c 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/ScriptTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/ScriptTestCase.java @@ -8,7 +8,8 @@ import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.vespa.indexinglanguage.SimpleTestAdapter; import org.junit.Test; -import java.util.Arrays; + +import java.util.List; import static com.yahoo.vespa.indexinglanguage.expressions.ExpressionAssert.assertVerify; import static com.yahoo.vespa.indexinglanguage.expressions.ExpressionAssert.assertVerifyThrows; @@ -32,7 +33,7 @@ public class ScriptTestCase { assertEquals(2, exp.size()); assertSame(foo, exp.get(0)); assertSame(bar, exp.get(1)); - assertEquals(Arrays.asList(foo, bar), exp.asList()); + assertEquals(List.of(foo, bar), exp.asList()); } @Test diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/SelectInputTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/SelectInputTestCase.java index 2c10606850c..23392c00110 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/SelectInputTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/SelectInputTestCase.java @@ -8,7 +8,6 @@ import com.yahoo.document.datatypes.StringFieldValue; import com.yahoo.vespa.indexinglanguage.SimpleTestAdapter; import org.junit.Test; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; @@ -66,11 +65,11 @@ public class SelectInputTestCase { @Test public void requireThatSelectedExpressionIsRun() { - assertSelect(Arrays.asList("foo", "bar"), List.of("foo"), "foo"); - assertSelect(Arrays.asList("foo", "bar"), List.of("bar"), "bar"); - assertSelect(Arrays.asList("foo", "bar"), List.of("foo", "bar"), "foo"); - assertSelect(Arrays.asList("foo", "bar"), List.of("bar", "baz"), "bar"); - assertSelect(Arrays.asList("foo", "bar"), List.of("baz", "cox"), null); + assertSelect(List.of("foo", "bar"), List.of("foo"), "foo"); + assertSelect(List.of("foo", "bar"), List.of("bar"), "bar"); + assertSelect(List.of("foo", "bar"), List.of("foo", "bar"), "foo"); + assertSelect(List.of("foo", "bar"), List.of("bar", "baz"), "bar"); + assertSelect(List.of("foo", "bar"), List.of("baz", "cox"), null); } private static void assertVerify(FieldTypeAdapter adapter, DataType value, Expression exp) { diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/StatementTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/StatementTestCase.java index 7e5b17dbc37..3612e3bd9fc 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/StatementTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/StatementTestCase.java @@ -7,7 +7,8 @@ import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.vespa.indexinglanguage.SimpleTestAdapter; import org.junit.Test; -import java.util.Arrays; + +import java.util.List; import static com.yahoo.vespa.indexinglanguage.expressions.ExpressionAssert.assertVerify; import static com.yahoo.vespa.indexinglanguage.expressions.ExpressionAssert.assertVerifyThrows; @@ -31,7 +32,7 @@ public class StatementTestCase { assertEquals(2, exp.size()); assertSame(foo, exp.get(0)); assertSame(bar, exp.get(1)); - assertEquals(Arrays.asList(foo, bar), exp.asList()); + assertEquals(List.of(foo, bar), exp.asList()); } @Test diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/SwitchTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/SwitchTestCase.java index 62d333e356f..376677b6f57 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/SwitchTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/expressions/SwitchTestCase.java @@ -7,7 +7,6 @@ import com.yahoo.document.datatypes.IntegerFieldValue; import com.yahoo.document.datatypes.StringFieldValue; import org.junit.Test; -import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -45,10 +44,10 @@ public class SwitchTestCase { cases.put("bar", bar); SwitchExpression exp = new SwitchExpression(cases, baz); - assertFalse(exp.equals(new Object())); - assertFalse(exp.equals(new SwitchExpression(Collections.singletonMap("foo", foo)))); - assertFalse(exp.equals(new SwitchExpression(Collections.singletonMap("foo", foo), baz))); - assertFalse(exp.equals(new SwitchExpression(cases))); + assertNotEquals(exp, new Object()); + assertNotEquals(exp, new SwitchExpression(Map.of("foo", foo))); + assertNotEquals(exp, new SwitchExpression(Map.of("foo", foo), baz)); + assertNotEquals(exp, new SwitchExpression(cases)); assertEquals(exp, new SwitchExpression(cases, baz)); assertEquals(exp.hashCode(), new SwitchExpression(cases, baz).hashCode()); } @@ -56,7 +55,7 @@ public class SwitchTestCase { @Test public void requireThatExpressionCanBeVerified() { Expression foo = SimpleExpression.newConversion(DataType.STRING, DataType.INT); - Expression exp = new SwitchExpression(Collections.singletonMap("foo", foo)); + Expression exp = new SwitchExpression(Map.of("foo", foo)); assertVerify(DataType.STRING, exp, DataType.STRING); // does not touch output assertVerifyThrows(null, exp, "Expected string input, but no input is specified"); assertVerifyThrows(DataType.INT, exp, "Expected string input, got int"); @@ -68,15 +67,14 @@ public class SwitchTestCase { cases.put("foo", SimpleExpression.newRequired(DataType.INT)); assertVerifyThrows(DataType.STRING, new SwitchExpression(cases), "Expected int input, got string"); - assertVerifyThrows(DataType.STRING, new SwitchExpression(Collections.<String, Expression>emptyMap(), - SimpleExpression.newRequired(DataType.INT)), + assertVerifyThrows(DataType.STRING, new SwitchExpression(Map.of(), SimpleExpression.newRequired(DataType.INT)), "Expected int input, got string"); } @Test public void requireThatIllegalArgumentThrows() { try { - new SwitchExpression(Collections.<String, Expression>emptyMap()).execute(new IntegerFieldValue(69)); + new SwitchExpression(Map.of()).execute(new IntegerFieldValue(69)); fail(); } catch (IllegalArgumentException e) { assertEquals("Expected string input, got int", e.getMessage()); @@ -85,18 +83,18 @@ public class SwitchTestCase { @Test public void requireThatDefaultExpressionIsNullIfNotGiven() { - assertNull(new SwitchExpression(Collections.<String, Expression>emptyMap()).getDefaultExpression()); + assertNull(new SwitchExpression(Map.of()).getDefaultExpression()); } @Test public void requireThatIsEmptyReflectsOnBothCasesAndDefault() { - assertTrue(new SwitchExpression(Collections.<String, Expression>emptyMap()).isEmpty()); - assertTrue(new SwitchExpression(Collections.<String, Expression>emptyMap(), null).isEmpty()); - assertFalse(new SwitchExpression(Collections.<String, Expression>emptyMap(), + assertTrue(new SwitchExpression(Map.of()).isEmpty()); + assertTrue(new SwitchExpression(Map.of(), null).isEmpty()); + assertFalse(new SwitchExpression(Map.of(), new AttributeExpression("foo")).isEmpty()); - assertFalse(new SwitchExpression(Collections.singletonMap("foo", new AttributeExpression("foo")), + assertFalse(new SwitchExpression(Map.of("foo", new AttributeExpression("foo")), null).isEmpty()); - assertFalse(new SwitchExpression(Collections.singletonMap("foo", new AttributeExpression("foo")), + assertFalse(new SwitchExpression(Map.of("foo", new AttributeExpression("foo")), new AttributeExpression("foo")).isEmpty()); } diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/linguistics/LinguisticsAnnotatorTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/linguistics/LinguisticsAnnotatorTestCase.java index 0bdf98f2ae0..136e71564d8 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/linguistics/LinguisticsAnnotatorTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/linguistics/LinguisticsAnnotatorTestCase.java @@ -18,7 +18,9 @@ import com.yahoo.language.simple.SimpleToken; import org.junit.Test; import org.mockito.Mockito; -import java.util.*; + +import java.util.List; +import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -90,7 +92,7 @@ public class LinguisticsAnnotatorTestCase { public void requireThatTermAnnotationsAreEmptyIfOrigIsLowerCase() { SpanTree expected = new SpanTree(SpanTrees.LINGUISTICS); expected.spanList().span(0, 3).annotate(new Annotation(AnnotationTypes.TERM)); - for (boolean specialToken : Arrays.asList(true, false)) { + for (boolean specialToken : List.of(true, false)) { for (TokenType type : TokenType.values()) { if (!specialToken && !type.isIndexable()) { continue; @@ -104,7 +106,7 @@ public class LinguisticsAnnotatorTestCase { public void requireThatTermAnnotationsPreserveCasing() { SpanTree expected = new SpanTree(SpanTrees.LINGUISTICS); expected.spanList().span(0, 3).annotate(new Annotation(AnnotationTypes.TERM, new StringFieldValue("BaR"))); - for (boolean specialToken : Arrays.asList(true, false)) { + for (boolean specialToken : List.of(true, false)) { for (TokenType type : TokenType.values()) { if (!specialToken && !type.isIndexable()) { continue; @@ -153,7 +155,7 @@ public class LinguisticsAnnotatorTestCase { public void requireThatTermReplacementsAreApplied() { SpanTree expected = new SpanTree(SpanTrees.LINGUISTICS); expected.spanList().span(0, 3).annotate(new Annotation(AnnotationTypes.TERM, new StringFieldValue("bar"))); - for (boolean specialToken : Arrays.asList(true, false)) { + for (boolean specialToken : List.of(true, false)) { for (TokenType type : TokenType.values()) { if (!specialToken && !type.isIndexable()) { continue; @@ -161,7 +163,7 @@ public class LinguisticsAnnotatorTestCase { assertAnnotations(expected, "foo", new AnnotatorConfig(), newLinguistics(List.of(token("foo", "foo", type, specialToken)), - Collections.singletonMap("foo", "bar"))); + Map.of("foo", "bar"))); } } } @@ -175,7 +177,7 @@ public class LinguisticsAnnotatorTestCase { val.setSpanTree(spanTree); Linguistics linguistics = newLinguistics(List.of(token("foo", "bar", TokenType.ALPHABETIC, false)), - Collections.<String, String>emptyMap()); + Map.of()); assertTrue(new LinguisticsAnnotator(linguistics, new AnnotatorConfig()).annotate(val)); assertEquals(spanTree, val.getSpanTree(SpanTrees.LINGUISTICS)); } @@ -244,11 +246,11 @@ public class LinguisticsAnnotatorTestCase { } private static void assertAnnotations(SpanTree expected, String value, Token... tokens) { - assertAnnotations(expected, value, new AnnotatorConfig(), newLinguistics(Arrays.asList(tokens), Collections.emptyMap())); + assertAnnotations(expected, value, new AnnotatorConfig(), newLinguistics(List.of(tokens), Map.of())); } private static void assertAnnotations(SpanTree expected, String value, AnnotatorConfig config, Token... tokens) { - assertAnnotations(expected, value, config, newLinguistics(Arrays.asList(tokens), Collections.emptyMap())); + assertAnnotations(expected, value, config, newLinguistics(List.of(tokens), Map.of())); } private static void assertAnnotations(SpanTree expected, String str, AnnotatorConfig config, Linguistics linguistics) { @@ -272,9 +274,12 @@ public class LinguisticsAnnotatorTestCase { } private Token replace(Token token, Map<String, String> replacementTerms) { - var simpleToken = (SimpleToken)token; - simpleToken.setTokenString(replacementTerms.getOrDefault(token.getTokenString(), token.getTokenString())); - return simpleToken; + String tokenString = token.getTokenString(); + if (tokenString != null && !replacementTerms.isEmpty()) { + var simpleToken = (SimpleToken)token; + simpleToken.setTokenString(replacementTerms.getOrDefault(token.getTokenString(), token.getTokenString())); + } + return token; } @Override diff --git a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/parser/IdentifierTestCase.java b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/parser/IdentifierTestCase.java index 300ae330e11..4ac5c840536 100644 --- a/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/parser/IdentifierTestCase.java +++ b/indexinglanguage/src/test/java/com/yahoo/vespa/indexinglanguage/parser/IdentifierTestCase.java @@ -3,7 +3,6 @@ package com.yahoo.vespa.indexinglanguage.parser; import org.junit.Test; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; @@ -15,7 +14,7 @@ public class IdentifierTestCase { @Test public void requireThatThereAreNoReservedWords() throws ParseException { - List<String> tokens = Arrays.asList("attribute", + List<String> tokens = List.of("attribute", "base64decode", "base64encode", "clear_state", diff --git a/integration/intellij/build.gradle.kts b/integration/intellij/build.gradle.kts index 89101020920..6fff4e8f519 100644 --- a/integration/intellij/build.gradle.kts +++ b/integration/intellij/build.gradle.kts @@ -10,7 +10,7 @@ plugins { } group="ai.vespa" -version="1.6.0" // Also update pom.xml version AND the version below if this is changed +version="1.6.1" // Also update pom.xml version AND the version below if this is changed defaultTasks("buildPlugin") @@ -18,14 +18,13 @@ apply(plugin="org.jetbrains.grammarkit") task<GenerateLexerTask>("generateSdLexer") { sourceFile.set(file("src/main/jflex/ai/vespa/intellij/schema/lexer/sd.flex")) - targetDir.set("target/generated-sources/jflex/ai/vespa/intellij/schema/lexer/") - targetClass.set("SdLexer") + targetOutputDir.set(file("target/generated-sources/jflex/ai/vespa/intellij/schema/lexer/")) purgeOldFiles.set(true) } task<GenerateParserTask>("generateSdParser") { sourceFile.set(file("src/main/bnf/ai/vespa/intellij/schema/parser/sd.bnf")) - targetRoot.set("target/generated-sources/bnf/") + targetRootOutputDir.set(file("target/generated-sources/bnf/")) pathToParser.set("ai/vespa/intellij/schema/parser/SdParser.java") pathToPsiRoot.set("ai/vespa/intellij/schema/parser/psi/") purgeOldFiles.set(true) @@ -43,7 +42,7 @@ sourceSets { // See https://github.com/JetBrains/gradle-intellij-plugin/ intellij { - version.set("2023.3") + version.set("2024.1") } tasks { @@ -55,12 +54,10 @@ tasks { } patchPluginXml { - version.set("1.6.0") // Keep in sync with pom.xml TODO: Use one version property + version.set("1.6.1") // Keep in sync with pom.xml TODO: Use one version property // Appears on the plugin page in preferences/plugins changeNotes.set(""" - Updated Vespa icon - Support for IntelliJ 2023.3 - Compatibility with all JetBrains IDEs + Support for IntelliJ 2024.1 """) } diff --git a/integration/intellij/pom.xml b/integration/intellij/pom.xml index 8156ac8a142..4a82c73f98e 100644 --- a/integration/intellij/pom.xml +++ b/integration/intellij/pom.xml @@ -9,7 +9,7 @@ <relativePath>../parent/pom.xml</relativePath> </parent> <artifactId>vespa-intellij</artifactId> <!-- Not used - plugin is build by gradle --> - <version>1.6.0</version> <!-- See copy-zip below, which depends on this being the same as the v. in build.gradle.kts --> + <version>1.6.1</version> <!-- See copy-zip below, which depends on this being the same as the v. in build.gradle.kts --> <description> Maven wrapper for the gradle build of this IntelliJ plugin. </description> diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java index 96306f60d80..83e2a8ea4f0 100644 --- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java +++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java @@ -11,7 +11,8 @@ import com.yahoo.jdisc.http.filter.security.cors.CorsFilterConfig.Builder; import com.yahoo.jdisc.http.filter.util.FilterTestUtils; import org.junit.jupiter.api.Test; -import java.util.Arrays; + +import java.util.List; import static com.yahoo.jdisc.http.HttpRequest.Method.OPTIONS; import static com.yahoo.jdisc.http.filter.security.cors.CorsLogic.ACCESS_CONTROL_HEADERS; @@ -75,7 +76,7 @@ public class CorsPreflightRequestFilterTest { private static CorsPreflightRequestFilter newRequestFilter(String... allowedOriginUrls) { Builder builder = new Builder(); - Arrays.asList(allowedOriginUrls).forEach(builder::allowedUrls); + List.of(allowedOriginUrls).forEach(builder::allowedUrls); return new CorsPreflightRequestFilter(new CorsFilterConfig(builder)); } diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java index a8fb8c8d817..8c28e0c2a98 100644 --- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java +++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java @@ -8,9 +8,9 @@ import com.yahoo.jdisc.http.filter.SecurityResponseFilter; import com.yahoo.jdisc.http.filter.security.cors.CorsFilterConfig.Builder; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -68,7 +68,7 @@ public class CorsResponseFilterTest { private static CorsResponseFilter newResponseFilter(String... allowedOriginUrls) { Builder builder = new Builder(); - Arrays.asList(allowedOriginUrls).forEach(builder::allowedUrls); + List.of(allowedOriginUrls).forEach(builder::allowedUrls); return new CorsResponseFilter(new CorsFilterConfig(builder)); } diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java index 30af4a9ac23..1da5b1b39a3 100644 --- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java +++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java @@ -17,7 +17,6 @@ import java.math.BigInteger; import java.security.cert.X509Certificate; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -28,7 +27,7 @@ public class VespaTlsFilterTest { @Test void testFilter() { assertSuccess(createRequest(List.of(createCertificate()))); - assertForbidden(createRequest(Collections.emptyList())); + assertForbidden(createRequest(List.of())); } private static X509Certificate createCertificate() { diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/application/AbstractApplication.java b/jdisc_core/src/main/java/com/yahoo/jdisc/application/AbstractApplication.java index 71956691623..3485c07c74e 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/application/AbstractApplication.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/application/AbstractApplication.java @@ -6,7 +6,6 @@ import com.yahoo.jdisc.service.CurrentContainer; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; -import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -67,7 +66,7 @@ public abstract class AbstractApplication implements Application { } public final List<Bundle> installAndStartBundle(String... locations) throws BundleException { - return installAndStartBundle(Arrays.asList(locations)); + return installAndStartBundle(List.of(locations)); } public final List<Bundle> installAndStartBundle(Iterable<String> locations) throws BundleException { @@ -75,7 +74,7 @@ public abstract class AbstractApplication implements Application { } public final void stopAndUninstallBundle(Bundle... bundles) throws BundleException { - stopAndUninstallBundle(Arrays.asList(bundles)); + stopAndUninstallBundle(List.of(bundles)); } public final void stopAndUninstallBundle(Iterable<Bundle> bundles) throws BundleException { diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/application/BundleInstaller.java b/jdisc_core/src/main/java/com/yahoo/jdisc/application/BundleInstaller.java index 60ca0851fd4..1e0050335dc 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/application/BundleInstaller.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/application/BundleInstaller.java @@ -5,11 +5,9 @@ import com.google.inject.Inject; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; -import static java.util.Collections.singletonList; /** * <p>This is a utility class to help with installing, starting, stopping and uninstalling OSGi Bundles. You can choose @@ -30,7 +28,7 @@ public final class BundleInstaller { } public List<Bundle> installAndStart(String... locations) throws BundleException { - return installAndStart(Arrays.asList(locations)); + return installAndStart(List.of(locations)); } public List<Bundle> installAndStart(Iterable<String> locations) throws BundleException { @@ -56,7 +54,7 @@ public final class BundleInstaller { } public void stopAndUninstall(Bundle... bundles) throws BundleException { - stopAndUninstall(Arrays.asList(bundles)); + stopAndUninstall(List.of(bundles)); } public void stopAndUninstall(Iterable<Bundle> bundles) throws BundleException { @@ -76,7 +74,7 @@ public final class BundleInstaller { throw new BundleException("OSGi header '" + OsgiHeader.APPLICATION + "' not allowed for " + "non-application bundle " + bundle.getSymbolicName() + "."); } - osgiFramework.startBundles(singletonList(bundle), false); + osgiFramework.startBundles(List.of(bundle), false); } private void stop(Bundle bundle) throws BundleException { diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/application/ContainerBuilder.java b/jdisc_core/src/main/java/com/yahoo/jdisc/application/ContainerBuilder.java index 6550d9b5386..8b3fe4c13aa 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/application/ContainerBuilder.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/application/ContainerBuilder.java @@ -8,7 +8,6 @@ import com.google.inject.Module; import com.yahoo.jdisc.Container; import com.yahoo.jdisc.handler.RequestHandler; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -107,7 +106,7 @@ public class ContainerBuilder { public static List<String> safeStringSplit(Object obj, String delim) { if (!(obj instanceof String)) { - return Collections.emptyList(); + return List.of(); } List<String> lst = new LinkedList<>(); for (String str : ((String)obj).split(delim)) { diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/application/GuiceRepository.java b/jdisc_core/src/main/java/com/yahoo/jdisc/application/GuiceRepository.java index fb3965108d8..5fc3b42055f 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/application/GuiceRepository.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/application/GuiceRepository.java @@ -13,7 +13,6 @@ import com.google.inject.spi.Elements; import com.yahoo.jdisc.Container; import org.osgi.framework.Bundle; -import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; @@ -38,7 +37,7 @@ public class GuiceRepository implements Iterable<Module> { private Injector injector; public GuiceRepository(Module... modules) { - installAll(Arrays.asList(modules)); + installAll(List.of(modules)); } public Injector activate() { diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/client/ClientDriver.java b/jdisc_core/src/main/java/com/yahoo/jdisc/client/ClientDriver.java index 8a5c8de92b9..beba03d7d84 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/client/ClientDriver.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/client/ClientDriver.java @@ -10,7 +10,6 @@ import com.yahoo.jdisc.core.FelixFramework; import com.yahoo.jdisc.core.FelixParams; import com.yahoo.jdisc.test.NonWorkingOsgiFramework; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; @@ -94,7 +93,7 @@ public abstract class ClientDriver { } private static List<Module> newModuleList(final ClientApplication appInstance, Module... guiceModules) { - List<Module> lst = new LinkedList<>(Arrays.asList(guiceModules)); + List<Module> lst = new LinkedList<>(List.of(guiceModules)); lst.add(new AbstractModule() { @Override @@ -108,7 +107,7 @@ public abstract class ClientDriver { private static List<Module> newModuleList(final Class<? extends ClientApplication> appClass, Module... guiceModules) { - List<Module> lst = new LinkedList<>(Arrays.asList(guiceModules)); + List<Module> lst = new LinkedList<>(List.of(guiceModules)); lst.add(new AbstractModule() { @Override diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/core/FelixFramework.java b/jdisc_core/src/main/java/com/yahoo/jdisc/core/FelixFramework.java index 80e531c90af..2bf3e05baed 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/core/FelixFramework.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/core/FelixFramework.java @@ -14,7 +14,6 @@ import org.osgi.framework.FrameworkEvent; import org.osgi.framework.wiring.FrameworkWiring; import java.io.File; -import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; @@ -150,14 +149,14 @@ public class FelixFramework implements OsgiFramework { @Override public List<Bundle> bundles() { - return Arrays.asList(felix.getBundleContext().getBundles()); + return List.of(felix.getBundleContext().getBundles()); } @Override public List<Bundle> getBundles(Bundle requestingBundle) { log.fine(() -> "All bundles: " + bundles()); log.fine(() -> "Getting visible bundles for bundle " + requestingBundle); - List<Bundle> visibleBundles = Arrays.asList(requestingBundle.getBundleContext().getBundles()); + List<Bundle> visibleBundles = List.of(requestingBundle.getBundleContext().getBundles()); log.fine(() -> "Visible bundles: " + visibleBundles); return visibleBundles; } diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/core/Main.java b/jdisc_core/src/main/java/com/yahoo/jdisc/core/Main.java index edd4dd40496..b2a8660e2a8 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/core/Main.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/core/Main.java @@ -6,8 +6,7 @@ import com.yahoo.jdisc.application.ContainerBuilder; import com.yahoo.jdisc.application.OsgiFramework; import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; /** * @author Simon Thoresen Hult @@ -31,7 +30,7 @@ public class Main { static Iterable<Module> newConfigModule() { String configFile = System.getProperty("jdisc.config.file"); if (configFile == null) { - return Collections.emptyList(); + return List.of(); } Module configModule; try { @@ -39,7 +38,7 @@ public class Main { } catch (IOException e) { throw new IllegalStateException("Exception thrown while reading config file '" + configFile + "'.", e); } - return Arrays.asList(configModule); + return List.of(configModule); } } diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/handler/RequestDispatch.java b/jdisc_core/src/main/java/com/yahoo/jdisc/handler/RequestDispatch.java index ef420d69f16..c39a70c7093 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/handler/RequestDispatch.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/handler/RequestDispatch.java @@ -8,7 +8,7 @@ import com.yahoo.jdisc.Response; import com.yahoo.jdisc.SharedResource; import java.nio.ByteBuffer; -import java.util.Collections; +import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; @@ -35,7 +35,7 @@ import java.util.concurrent.TimeoutException; * } * @Override * protected Iterable<ByteBuffer> requestContent() { - * return Collections.singleton(ByteBuffer.wrap(new byte[] { 6, 9 })); + * return Set.of(ByteBuffer.wrap(new byte[] { 6, 9 })); * } * @Override * public ContentChannel handleResponse(Response response) { @@ -69,7 +69,7 @@ public abstract class RequestDispatch implements Future<Response>, ResponseHandl * @return The ByteBuffers to write to the Request's ContentChannel. */ protected Iterable<ByteBuffer> requestContent() { - return Collections.emptyList(); + return List.of(); } /** diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/handler/ResponseDispatch.java b/jdisc_core/src/main/java/com/yahoo/jdisc/handler/ResponseDispatch.java index ff1f23917d7..0670aa5ea67 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/handler/ResponseDispatch.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/handler/ResponseDispatch.java @@ -5,8 +5,7 @@ import com.yahoo.jdisc.Response; import com.yahoo.jdisc.SharedResource; import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -28,7 +27,7 @@ import java.util.concurrent.TimeoutException; * } * @Override * protected Iterable<ByteBuffer> responseContent() { - * return Collections.singleton(ByteBuffer.wrap(new byte[] { 6, 9 })); + * return Set.of(ByteBuffer.wrap(new byte[] { 6, 9 })); * } * }.dispatch(handler); * } @@ -56,7 +55,7 @@ public abstract class ResponseDispatch implements Future<Boolean> { * @return The ByteBuffers to write to the Response's ContentChannel. */ protected Iterable<ByteBuffer> responseContent() { - return Collections.emptyList(); + return List.of(); } /** @@ -130,7 +129,7 @@ public abstract class ResponseDispatch implements Future<Boolean> { * @return The created ResponseDispatch. */ public static ResponseDispatch newInstance(int responseStatus, ByteBuffer... content) { - return newInstance(new Response(responseStatus), Arrays.asList(content)); + return newInstance(new Response(responseStatus), List.of(content)); } /** @@ -155,7 +154,7 @@ public abstract class ResponseDispatch implements Future<Boolean> { * @return The created ResponseDispatch. */ public static ResponseDispatch newInstance(Response response, ByteBuffer... content) { - return newInstance(response, Arrays.asList(content)); + return newInstance(response, List.of(content)); } /** diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/test/NonWorkingOsgiFramework.java b/jdisc_core/src/main/java/com/yahoo/jdisc/test/NonWorkingOsgiFramework.java index 1b90e8adcfe..3565a1ec4c5 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/test/NonWorkingOsgiFramework.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/test/NonWorkingOsgiFramework.java @@ -6,7 +6,6 @@ import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import java.util.Collection; -import java.util.Collections; import java.util.List; /** @@ -36,12 +35,12 @@ public class NonWorkingOsgiFramework implements OsgiFramework { @Override public List<Bundle> bundles() { - return Collections.emptyList(); + return List.of(); } @Override public List<Bundle> getBundles(Bundle requestingBundle) { - return Collections.emptyList(); + return List.of(); } @Override diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/test/TestDriver.java b/jdisc_core/src/main/java/com/yahoo/jdisc/test/TestDriver.java index 18449f207ee..64c690e89d4 100644 --- a/jdisc_core/src/main/java/com/yahoo/jdisc/test/TestDriver.java +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/test/TestDriver.java @@ -26,7 +26,6 @@ import com.yahoo.jdisc.handler.ResponseHandler; import com.yahoo.jdisc.service.CurrentContainer; import java.net.URI; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; @@ -311,7 +310,7 @@ public class TestDriver implements ContainerActivator, CurrentContainer { */ public static TestDriver newApplicationBundleInstance(String bundleLocation, boolean privileged, Module... guiceModules) { - return newInstance(newOsgiFramework(), bundleLocation, privileged, Arrays.asList(guiceModules)); + return newInstance(newOsgiFramework(), bundleLocation, privileged, List.of(guiceModules)); } /** @@ -326,7 +325,7 @@ public class TestDriver implements ContainerActivator, CurrentContainer { */ public static TestDriver newInstance(OsgiFramework osgiFramework, String bundleLocation, boolean privileged, Module... guiceModules) { - return newInstance(osgiFramework, bundleLocation, privileged, Arrays.asList(guiceModules)); + return newInstance(osgiFramework, bundleLocation, privileged, List.of(guiceModules)); } /** @@ -381,7 +380,7 @@ public class TestDriver implements ContainerActivator, CurrentContainer { private static List<Module> newModuleList(final Application app, final Class<? extends Application> appClass, Module... guiceModules) { List<Module> lst = new LinkedList<>(); - lst.addAll(Arrays.asList(guiceModules)); + lst.addAll(List.of(guiceModules)); lst.add(new AbstractModule() { @Override diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java index 7fe3c052566..acaed01a946 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java @@ -3,7 +3,6 @@ package com.yahoo.jdisc; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -64,9 +63,9 @@ public class HeaderFieldsTestCase { @Test void requireThatContainsValueWorksAsExpected() { HeaderFields headers = new HeaderFields(); - assertFalse(headers.containsValue(Arrays.asList("bar"))); + assertFalse(headers.containsValue(List.of("bar"))); headers.add("foo", "bar"); - assertTrue(headers.containsValue(Arrays.asList("bar"))); + assertTrue(headers.containsValue(List.of("bar"))); } @Test @@ -102,19 +101,19 @@ public class HeaderFieldsTestCase { HeaderFields headers = new HeaderFields(); assertNull(headers.get("foo")); headers.add("foo", "bar"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); + assertEquals(List.of("bar"), headers.get("foo")); headers.add("foo", "baz"); - assertEquals(Arrays.asList("bar", "baz"), headers.get("foo")); + assertEquals(List.of("bar", "baz"), headers.get("foo")); } @Test void requireThatAddListWorksAsExpected() { HeaderFields headers = new HeaderFields(); assertNull(headers.get("foo")); - headers.add("foo", Arrays.asList("bar")); - assertEquals(Arrays.asList("bar"), headers.get("foo")); - headers.add("foo", Arrays.asList("baz", "cox")); - assertEquals(Arrays.asList("bar", "baz", "cox"), headers.get("foo")); + headers.add("foo", List.of("bar")); + assertEquals(List.of("bar"), headers.get("foo")); + headers.add("foo", List.of("baz", "cox")); + assertEquals(List.of("bar", "baz", "cox"), headers.get("foo")); } @Test @@ -122,16 +121,16 @@ public class HeaderFieldsTestCase { HeaderFields headers = new HeaderFields(); headers.add("foo", "bar"); headers.add("bar", "baz"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); - assertEquals(Arrays.asList("baz"), headers.get("bar")); + assertEquals(List.of("bar"), headers.get("foo")); + assertEquals(List.of("baz"), headers.get("bar")); Map<String, List<String>> map = new HashMap<>(); - map.put("foo", Arrays.asList("baz", "cox")); - map.put("bar", Arrays.asList("cox")); + map.put("foo", List.of("baz", "cox")); + map.put("bar", List.of("cox")); headers.addAll(map); - assertEquals(Arrays.asList("bar", "baz", "cox"), headers.get("foo")); - assertEquals(Arrays.asList("baz", "cox"), headers.get("bar")); + assertEquals(List.of("bar", "baz", "cox"), headers.get("foo")); + assertEquals(List.of("baz", "cox"), headers.get("bar")); } @Test @@ -139,19 +138,19 @@ public class HeaderFieldsTestCase { HeaderFields headers = new HeaderFields(); assertNull(headers.get("foo")); headers.put("foo", "bar"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); + assertEquals(List.of("bar"), headers.get("foo")); headers.put("foo", "baz"); - assertEquals(Arrays.asList("baz"), headers.get("foo")); + assertEquals(List.of("baz"), headers.get("foo")); } @Test void requireThatPutListWorksAsExpected() { HeaderFields headers = new HeaderFields(); assertNull(headers.get("foo")); - headers.put("foo", Arrays.asList("bar")); - assertEquals(Arrays.asList("bar"), headers.get("foo")); - headers.put("foo", Arrays.asList("baz", "cox")); - assertEquals(Arrays.asList("baz", "cox"), headers.get("foo")); + headers.put("foo", List.of("bar")); + assertEquals(List.of("bar"), headers.get("foo")); + headers.put("foo", List.of("baz", "cox")); + assertEquals(List.of("baz", "cox"), headers.get("foo")); } @Test @@ -159,24 +158,24 @@ public class HeaderFieldsTestCase { HeaderFields headers = new HeaderFields(); headers.add("foo", "bar"); headers.add("bar", "baz"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); - assertEquals(Arrays.asList("baz"), headers.get("bar")); + assertEquals(List.of("bar"), headers.get("foo")); + assertEquals(List.of("baz"), headers.get("bar")); Map<String, List<String>> map = new HashMap<>(); - map.put("foo", Arrays.asList("baz", "cox")); - map.put("bar", Arrays.asList("cox")); + map.put("foo", List.of("baz", "cox")); + map.put("bar", List.of("cox")); headers.putAll(map); - assertEquals(Arrays.asList("baz", "cox"), headers.get("foo")); - assertEquals(Arrays.asList("cox"), headers.get("bar")); + assertEquals(List.of("baz", "cox"), headers.get("foo")); + assertEquals(List.of("cox"), headers.get("bar")); } @Test void requireThatRemoveWorksAsExpected() { HeaderFields headers = new HeaderFields(); - headers.put("foo", Arrays.asList("bar", "baz")); - assertEquals(Arrays.asList("bar", "baz"), headers.get("foo")); - assertEquals(Arrays.asList("bar", "baz"), headers.remove("foo")); + headers.put("foo", List.of("bar", "baz")); + assertEquals(List.of("bar", "baz"), headers.get("foo")); + assertEquals(List.of("bar", "baz"), headers.remove("foo")); assertNull(headers.get("foo")); assertNull(headers.remove("foo")); } @@ -184,11 +183,11 @@ public class HeaderFieldsTestCase { @Test void requireThatRemoveStringWorksAsExpected() { HeaderFields headers = new HeaderFields(); - headers.put("foo", Arrays.asList("bar", "baz")); - assertEquals(Arrays.asList("bar", "baz"), headers.get("foo")); + headers.put("foo", List.of("bar", "baz")); + assertEquals(List.of("bar", "baz"), headers.get("foo")); assertTrue(headers.remove("foo", "bar")); assertFalse(headers.remove("foo", "cox")); - assertEquals(Arrays.asList("baz"), headers.get("foo")); + assertEquals(List.of("baz"), headers.get("foo")); assertTrue(headers.remove("foo", "baz")); assertFalse(headers.remove("foo", "cox")); assertNull(headers.get("foo")); @@ -199,8 +198,8 @@ public class HeaderFieldsTestCase { HeaderFields headers = new HeaderFields(); headers.add("foo", "bar"); headers.add("bar", "baz"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); - assertEquals(Arrays.asList("baz"), headers.get("bar")); + assertEquals(List.of("bar"), headers.get("foo")); + assertEquals(List.of("baz"), headers.get("bar")); headers.clear(); assertNull(headers.get("foo")); assertNull(headers.get("bar")); @@ -211,14 +210,14 @@ public class HeaderFieldsTestCase { HeaderFields headers = new HeaderFields(); assertNull(headers.get("foo")); headers.add("foo", "bar"); - assertEquals(Arrays.asList("bar"), headers.get("foo")); + assertEquals(List.of("bar"), headers.get("foo")); } @Test void requireThatGetFirstWorksAsExpected() { HeaderFields headers = new HeaderFields(); assertNull(headers.getFirst("foo")); - headers.add("foo", Arrays.asList("bar", "baz")); + headers.add("foo", List.of("bar", "baz")); assertEquals("bar", headers.getFirst("foo")); } @@ -226,17 +225,17 @@ public class HeaderFieldsTestCase { void requireThatIsTrueWorksAsExpected() { HeaderFields headers = new HeaderFields(); assertFalse(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("true")); + headers.put("foo", List.of("true")); assertTrue(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("true", "true")); + headers.put("foo", List.of("true", "true")); assertTrue(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("true", "false")); + headers.put("foo", List.of("true", "false")); assertFalse(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("false", "true")); + headers.put("foo", List.of("false", "true")); assertFalse(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("false", "false")); + headers.put("foo", List.of("false", "false")); assertFalse(headers.isTrue("foo")); - headers.put("foo", Arrays.asList("false")); + headers.put("foo", List.of("false")); assertFalse(headers.isTrue("foo")); } @@ -245,9 +244,9 @@ public class HeaderFieldsTestCase { HeaderFields headers = new HeaderFields(); assertTrue(headers.keySet().isEmpty()); headers.add("foo", "bar"); - assertEquals(new HashSet<>(Arrays.asList("foo")), headers.keySet()); + assertEquals(new HashSet<>(List.of("foo")), headers.keySet()); headers.add("bar", "baz"); - assertEquals(new HashSet<>(Arrays.asList("foo", "bar")), headers.keySet()); + assertEquals(new HashSet<>(List.of("foo", "bar")), headers.keySet()); } @Test @@ -257,34 +256,34 @@ public class HeaderFieldsTestCase { headers.add("foo", "bar"); Collection<List<String>> values = headers.values(); assertEquals(1, values.size()); - assertTrue(values.contains(Arrays.asList("bar"))); + assertTrue(values.contains(List.of("bar"))); headers.add("bar", "baz"); values = headers.values(); assertEquals(2, values.size()); - assertTrue(values.contains(Arrays.asList("bar"))); - assertTrue(values.contains(Arrays.asList("baz"))); + assertTrue(values.contains(List.of("bar"))); + assertTrue(values.contains(List.of("baz"))); } @Test void requireThatEntrySetWorksAsExpected() { HeaderFields headers = new HeaderFields(); assertTrue(headers.entrySet().isEmpty()); - headers.put("foo", Arrays.asList("bar", "baz")); + headers.put("foo", List.of("bar", "baz")); Set<Map.Entry<String, List<String>>> entries = headers.entrySet(); assertEquals(1, entries.size()); Map.Entry<String, List<String>> entry = entries.iterator().next(); assertNotNull(entry); assertEquals("foo", entry.getKey()); - assertEquals(Arrays.asList("bar", "baz"), entry.getValue()); + assertEquals(List.of("bar", "baz"), entry.getValue()); } @Test void requireThatEntriesWorksAsExpected() { HeaderFields headers = new HeaderFields(); assertTrue(headers.entries().isEmpty()); - headers.put("foo", Arrays.asList("bar", "baz")); + headers.put("foo", List.of("bar", "baz")); List<Map.Entry<String, String>> entries = headers.entries(); assertEquals(2, entries.size()); diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java index e35f1c69073..133472f5678 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java @@ -8,7 +8,6 @@ import org.junit.jupiter.api.Test; import java.net.URI; import java.util.ArrayList; -import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; @@ -480,13 +479,13 @@ public class BindingSetTestCase { for (int i = 0; i < expected.length; ++i) { actual.add(expected[(off + i) % expected.length]); } - assertOrder(Arrays.asList(expected), actual); + assertOrder(List.of(expected), actual); actual = new ArrayList<>(); for (int i = expected.length; --i >= 0; ) { actual.add(expected[(off + i) % expected.length]); } - assertOrder(Arrays.asList(expected), actual); + assertOrder(List.of(expected), actual); } } diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java index 6a704b1aacc..34ac6603e62 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java @@ -5,9 +5,9 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.osgi.framework.Bundle; -import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; +import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; @@ -41,7 +41,7 @@ public class BundleInstallationExceptionTestCase { @Test void requireThatBundlesCollectionIsUnmodifiable() { - BundleInstallationException e = new BundleInstallationException(Arrays.asList(Mockito.mock(Bundle.class)), + BundleInstallationException e = new BundleInstallationException(List.of(Mockito.mock(Bundle.class)), new Throwable()); try { e.installedBundles().add(Mockito.mock(Bundle.class)); diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java index 9b3d61d7c89..3737647679d 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java @@ -8,7 +8,7 @@ import com.yahoo.jdisc.test.TestDriver; import org.junit.jupiter.api.Test; import java.net.URISyntaxException; -import java.util.Arrays; +import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; @@ -106,11 +106,11 @@ public class ContainerBuilderTestCase { assertTrue(ContainerBuilder.safeStringSplit(new Object(), ",").isEmpty()); assertTrue(ContainerBuilder.safeStringSplit("", ",").isEmpty()); assertTrue(ContainerBuilder.safeStringSplit(" \f\n\r\t", ",").isEmpty()); - assertEquals(Arrays.asList("foo"), ContainerBuilder.safeStringSplit("foo", ",")); - assertEquals(Arrays.asList("foo"), ContainerBuilder.safeStringSplit(" foo", ",")); - assertEquals(Arrays.asList("foo"), ContainerBuilder.safeStringSplit("foo ", ",")); - assertEquals(Arrays.asList("foo"), ContainerBuilder.safeStringSplit("foo, ", ",")); - assertEquals(Arrays.asList("foo"), ContainerBuilder.safeStringSplit("foo ,", ",")); - assertEquals(Arrays.asList("foo", "bar"), ContainerBuilder.safeStringSplit("foo, bar", ",")); + assertEquals(List.of("foo"), ContainerBuilder.safeStringSplit("foo", ",")); + assertEquals(List.of("foo"), ContainerBuilder.safeStringSplit(" foo", ",")); + assertEquals(List.of("foo"), ContainerBuilder.safeStringSplit("foo ", ",")); + assertEquals(List.of("foo"), ContainerBuilder.safeStringSplit("foo, ", ",")); + assertEquals(List.of("foo"), ContainerBuilder.safeStringSplit("foo ,", ",")); + assertEquals(List.of("foo", "bar"), ContainerBuilder.safeStringSplit("foo, bar", ",")); } } diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java index ef09c854f72..0e5df5656c4 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java @@ -4,7 +4,6 @@ package com.yahoo.jdisc.application; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -42,14 +41,14 @@ public class GlobPatternTestCase { assertMatch("foo", "foo", Collections.<String>emptyList()); assertNotMatch("foo", "bar"); - assertMatch("*", "foo", Arrays.asList("foo")); - assertMatch("*", "bar", Arrays.asList("bar")); + assertMatch("*", "foo", List.of("foo")); + assertMatch("*", "bar", List.of("bar")); - assertMatch("*foo", "foo", Arrays.asList("")); - assertMatch("*oo", "foo", Arrays.asList("f")); - assertMatch("f*o", "foo", Arrays.asList("o")); - assertMatch("fo*", "foo", Arrays.asList("o")); - assertMatch("foo*", "foo", Arrays.asList("")); + assertMatch("*foo", "foo", List.of("")); + assertMatch("*oo", "foo", List.of("f")); + assertMatch("f*o", "foo", List.of("o")); + assertMatch("fo*", "foo", List.of("o")); + assertMatch("foo*", "foo", List.of("")); assertNotMatch("*foo", "bar"); assertNotMatch("*oo", "bar"); @@ -57,11 +56,11 @@ public class GlobPatternTestCase { assertNotMatch("fo*", "bar"); assertNotMatch("foo*", "bar"); - assertMatch("**foo", "foo", Arrays.asList("", "")); - assertMatch("**oo", "foo", Arrays.asList("", "f")); - assertMatch("f**o", "foo", Arrays.asList("", "o")); - assertMatch("fo**", "foo", Arrays.asList("", "o")); - assertMatch("foo**", "foo", Arrays.asList("", "")); + assertMatch("**foo", "foo", List.of("", "")); + assertMatch("**oo", "foo", List.of("", "f")); + assertMatch("f**o", "foo", List.of("", "o")); + assertMatch("fo**", "foo", List.of("", "o")); + assertMatch("foo**", "foo", List.of("", "")); assertNotMatch("**foo", "bar"); assertNotMatch("**oo", "bar"); @@ -70,9 +69,9 @@ public class GlobPatternTestCase { assertNotMatch("foo**", "bar"); assertMatch("foo bar", "foo bar", Collections.<String>emptyList()); - assertMatch("*foo *bar", "foo bar", Arrays.asList("", "")); - assertMatch("foo* bar*", "foo bar", Arrays.asList("", "")); - assertMatch("f* *r", "foo bar", Arrays.asList("oo", "ba")); + assertMatch("*foo *bar", "foo bar", List.of("", "")); + assertMatch("foo* bar*", "foo bar", List.of("", "")); + assertMatch("f* *r", "foo bar", List.of("oo", "ba")); assertNotMatch("foo bar", "baz cox"); assertNotMatch("*foo *bar", "baz cox"); diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java index 7aa8a16d856..30c917f9150 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java @@ -12,7 +12,6 @@ import com.google.inject.name.Named; import com.google.inject.name.Names; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Iterator; import java.util.List; @@ -47,7 +46,7 @@ public class GuiceRepositoryTestCase { GuiceRepository guice = new GuiceRepository(); StringBinding foo = new StringBinding("fooKey", "fooVal"); StringBinding bar = new StringBinding("barKey", "barVal"); - guice.installAll(Arrays.asList(foo, bar)); + guice.installAll(List.of(foo, bar)); assertBinding(guice, "fooKey", "fooVal"); assertBinding(guice, "barKey", "barVal"); @@ -77,12 +76,12 @@ public class GuiceRepositoryTestCase { StringBinding foo = new StringBinding("fooKey", "fooVal"); StringBinding bar = new StringBinding("barKey", "barVal"); StringBinding baz = new StringBinding("bazKey", "bazVal"); - guice.installAll(Arrays.asList(foo, bar, baz)); + guice.installAll(List.of(foo, bar, baz)); assertBinding(guice, "fooKey", "fooVal"); assertBinding(guice, "barKey", "barVal"); assertBinding(guice, "bazKey", "bazVal"); - guice.uninstallAll(Arrays.asList(foo, baz)); + guice.uninstallAll(List.of(foo, baz)); assertNoBinding(guice, "fooKey"); assertBinding(guice, "barKey", "barVal"); assertNoBinding(guice, "bazKey"); @@ -122,7 +121,7 @@ public class GuiceRepositoryTestCase { void requireThatPrivateModulesWorks() { GuiceRepository guice = new GuiceRepository(); - List<Named> names = Arrays.asList(Names.named("A"), Names.named("B")); + List<Named> names = List.of(Names.named("A"), Names.named("B")); for (Named name : names) { guice.install(createPrivateInjectNameModule(name)); diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java index 3a2db7d1e75..a54a42228e4 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java @@ -5,8 +5,8 @@ import com.yahoo.jdisc.NoopSharedResource; import com.yahoo.jdisc.service.ServerProvider; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Iterator; +import java.util.List; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -35,7 +35,7 @@ public class ServerRepositoryTestCase { ServerRepository servers = newServerRepository(); ServerProvider foo = new MyServer(); ServerProvider bar = new MyServer(); - servers.installAll(Arrays.asList(foo, bar)); + servers.installAll(List.of(foo, bar)); Iterator<ServerProvider> it = servers.iterator(); assertTrue(it.hasNext()); @@ -60,8 +60,8 @@ public class ServerRepositoryTestCase { ServerProvider foo = new MyServer(); ServerProvider bar = new MyServer(); ServerProvider baz = new MyServer(); - servers.installAll(Arrays.asList(foo, bar, baz)); - servers.uninstallAll(Arrays.asList(foo, bar)); + servers.installAll(List.of(foo, bar, baz)); + servers.uninstallAll(List.of(foo, bar)); Iterator<ServerProvider> it = servers.iterator(); assertNotNull(it); assertTrue(it.hasNext()); diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java index fa949ccaabd..0f8016eba10 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java @@ -5,8 +5,6 @@ import org.junit.jupiter.api.Test; import java.net.URI; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -20,7 +18,7 @@ import static org.junit.jupiter.api.Assertions.fail; */ public class UriPatternTestCase { - private static final List<String> NO_GROUPS = Collections.emptyList(); + private static final List<String> NO_GROUPS = List.of(); @Test void requireThatIllegalPatternsAreDetected() { @@ -50,19 +48,19 @@ public class UriPatternTestCase { assertNotMatch(pattern, "barbaz://host:69/path"); pattern = new UriPattern("*://host:69/path"); - assertMatch(pattern, "foobar://host:69/path", Arrays.asList("foobar")); - assertMatch(pattern, "bar://host:69/path", Arrays.asList("bar")); - assertMatch(pattern, "barbaz://host:69/path", Arrays.asList("barbaz")); + assertMatch(pattern, "foobar://host:69/path", List.of("foobar")); + assertMatch(pattern, "bar://host:69/path", List.of("bar")); + assertMatch(pattern, "barbaz://host:69/path", List.of("barbaz")); pattern = new UriPattern("*bar://host:69/path"); - assertMatch(pattern, "foobar://host:69/path", Arrays.asList("foo")); - assertMatch(pattern, "bar://host:69/path", Arrays.asList("")); + assertMatch(pattern, "foobar://host:69/path", List.of("foo")); + assertMatch(pattern, "bar://host:69/path", List.of("")); assertNotMatch(pattern, "barbaz://host:69/path"); pattern = new UriPattern("bar*://host:69/path"); assertNotMatch(pattern, "foobar://host:69/path"); - assertMatch(pattern, "bar://host:69/path", Arrays.asList("")); - assertMatch(pattern, "barbaz://host:69/path", Arrays.asList("baz")); + assertMatch(pattern, "bar://host:69/path", List.of("")); + assertMatch(pattern, "barbaz://host:69/path", List.of("baz")); // host matching pattern = new UriPattern("scheme://bar:69/path"); @@ -71,19 +69,19 @@ public class UriPatternTestCase { assertNotMatch(pattern, "scheme://barbaz:69/path"); pattern = new UriPattern("scheme://*:69/path"); - assertMatch(pattern, "scheme://foobar:69/path", Arrays.asList("foobar")); - assertMatch(pattern, "scheme://bar:69/path", Arrays.asList("bar")); - assertMatch(pattern, "scheme://barbaz:69/path", Arrays.asList("barbaz")); + assertMatch(pattern, "scheme://foobar:69/path", List.of("foobar")); + assertMatch(pattern, "scheme://bar:69/path", List.of("bar")); + assertMatch(pattern, "scheme://barbaz:69/path", List.of("barbaz")); pattern = new UriPattern("scheme://*bar:69/path"); - assertMatch(pattern, "scheme://foobar:69/path", Arrays.asList("foo")); - assertMatch(pattern, "scheme://bar:69/path", Arrays.asList("")); + assertMatch(pattern, "scheme://foobar:69/path", List.of("foo")); + assertMatch(pattern, "scheme://bar:69/path", List.of("")); assertNotMatch(pattern, "scheme://barbaz:69/path"); pattern = new UriPattern("scheme://bar*:69/path"); assertNotMatch(pattern, "scheme://foobar:69/path"); - assertMatch(pattern, "scheme://bar:69/path", Arrays.asList("")); - assertMatch(pattern, "scheme://barbaz:69/path", Arrays.asList("baz")); + assertMatch(pattern, "scheme://bar:69/path", List.of("")); + assertMatch(pattern, "scheme://barbaz:69/path", List.of("baz")); // port matching pattern = new UriPattern("scheme://host:69/path"); @@ -92,9 +90,9 @@ public class UriPatternTestCase { assertNotMatch(pattern, "scheme://host:699/path"); pattern = new UriPattern("scheme://host:*/path"); - assertMatch(pattern, "scheme://host:669/path", Arrays.asList("669")); - assertMatch(pattern, "scheme://host:69/path", Arrays.asList("69")); - assertMatch(pattern, "scheme://host:699/path", Arrays.asList("699")); + assertMatch(pattern, "scheme://host:669/path", List.of("669")); + assertMatch(pattern, "scheme://host:69/path", List.of("69")); + assertMatch(pattern, "scheme://host:699/path", List.of("699")); // path matching pattern = new UriPattern("scheme://host:69/"); @@ -107,20 +105,20 @@ public class UriPatternTestCase { assertNotMatch(pattern, "scheme://host:69/barbaz"); pattern = new UriPattern("scheme://host:69/*"); - assertMatch(pattern, "scheme://host:69/", Arrays.asList("")); - assertMatch(pattern, "scheme://host:69/foobar", Arrays.asList("foobar")); - assertMatch(pattern, "scheme://host:69/bar", Arrays.asList("bar")); - assertMatch(pattern, "scheme://host:69/barbaz", Arrays.asList("barbaz")); + assertMatch(pattern, "scheme://host:69/", List.of("")); + assertMatch(pattern, "scheme://host:69/foobar", List.of("foobar")); + assertMatch(pattern, "scheme://host:69/bar", List.of("bar")); + assertMatch(pattern, "scheme://host:69/barbaz", List.of("barbaz")); pattern = new UriPattern("scheme://host:69/*bar"); - assertMatch(pattern, "scheme://host:69/foobar", Arrays.asList("foo")); - assertMatch(pattern, "scheme://host:69/bar", Arrays.asList("")); + assertMatch(pattern, "scheme://host:69/foobar", List.of("foo")); + assertMatch(pattern, "scheme://host:69/bar", List.of("")); assertNotMatch(pattern, "scheme://host:69/barbaz"); pattern = new UriPattern("scheme://host:69/bar*"); assertNotMatch(pattern, "scheme://host:69/foobar"); - assertMatch(pattern, "scheme://host:69/bar", Arrays.asList("")); - assertMatch(pattern, "scheme://host:69/barbaz", Arrays.asList("baz")); + assertMatch(pattern, "scheme://host:69/bar", List.of("")); + assertMatch(pattern, "scheme://host:69/barbaz", List.of("baz")); } @Test @@ -129,7 +127,7 @@ public class UriPatternTestCase { assertNotMatch(pattern, "scheme://host"); pattern = new UriPattern("scheme://host/*"); - assertMatch(pattern, "scheme://host", Arrays.asList("")); + assertMatch(pattern, "scheme://host", List.of("")); } @Test @@ -142,8 +140,8 @@ public class UriPatternTestCase { @Test void requireThatHostSupportsWildcard() { UriPattern pattern = new UriPattern("scheme://*.host/path"); - assertMatch(pattern, "scheme://a.host/path", Arrays.asList("a")); - assertMatch(pattern, "scheme://a.b.host/path", Arrays.asList("a.b")); + assertMatch(pattern, "scheme://a.host/path", List.of("a")); + assertMatch(pattern, "scheme://a.b.host/path", List.of("a.b")); } @Test diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java index 478f15f721d..53a29cf22c1 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java @@ -8,7 +8,6 @@ import org.junit.jupiter.api.Test; import java.net.URI; import java.util.ArrayList; -import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -36,7 +35,7 @@ public class BindingMatchingTestCase { void runThroughtputMeasurements() throws Exception { System.err.format("%15s%15s%15s%15s%15s%15s%15s%15s\n", "No. of Bindings", "1 thread", "2 thread", "4 thread", "8 thread", "16 thread", "32 thread", "64 thread"); - for (int numBindings : Arrays.asList(1, 10, 25, 50, 100, 250)) { + for (int numBindings : List.of(1, 10, 25, 50, 100, 250)) { BindingRepository<Object> repo = new BindingRepository<>(); for (int binding = 0; binding < numBindings; ++binding) { repo.bind("http://*/v" + binding + "/*/data/", new Object()); diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java index 5301eb297b4..cb9114f2981 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java @@ -6,7 +6,6 @@ import org.junit.jupiter.api.Test; import java.net.URI; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; @@ -20,7 +19,7 @@ public class UriMatchingTestCase { @Test void requireThatUriPatternMatchingIsFast() { - List<String> inputs = Arrays.asList( + List<String> inputs = List.of( "other://host/", "scheme://other/", "scheme://host/", diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java index dfc52b92583..af3fa418556 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java @@ -17,7 +17,6 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ThreadFactory; -import static java.util.Collections.emptyList; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -40,7 +39,7 @@ public class ApplicationEnvironmentModuleTestCase { expected.add(entry.getKey().getTypeLiteral().getRawType()); } - ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(), emptyList()); + ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(), List.of()); injector = Guice.createInjector(new ApplicationEnvironmentModule(loader)); for (Map.Entry<Key<?>, Binding<?>> entry : injector.getBindings().entrySet()) { assertNotNull(expected.remove(entry.getKey().getTypeLiteral().getRawType())); @@ -50,7 +49,7 @@ public class ApplicationEnvironmentModuleTestCase { @Test void requireThatContainerBuilderCanBeInjected() { - ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(), emptyList()); + ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(), List.of()); assertNotNull(new ApplicationEnvironmentModule(loader).containerBuilder()); assertNotNull(Guice.createInjector(new ApplicationEnvironmentModule(loader)) .getInstance(ContainerBuilder.class)); diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java index d8aa553b628..95511b3ed1c 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java @@ -15,7 +15,7 @@ import org.junit.jupiter.api.Test; import java.net.URI; import java.nio.ByteBuffer; -import java.util.Arrays; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -54,7 +54,7 @@ public class ApplicationRestartTestCase { private static ApplicationLoader newApplicationLoader() { return new ApplicationLoader(new NonWorkingOsgiFramework(), - Arrays.asList(new AbstractModule() { + List.of(new AbstractModule() { @Override public void configure() { bind(Application.class).to(SimpleApplication.class); diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java index 252b7074a2c..25399433e2e 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java @@ -4,7 +4,6 @@ package com.yahoo.jdisc.core; import org.junit.jupiter.api.Test; import org.osgi.framework.Constants; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -60,8 +59,8 @@ public class FelixParamsTestCase { assertEquals(prev.length + 2, next.length); List<String> diff = new LinkedList<>(); - diff.addAll(Arrays.asList(next)); - diff.removeAll(Arrays.asList(prev)); + diff.addAll(List.of(next)); + diff.removeAll(List.of(prev)); assertEquals(2, diff.size()); assertTrue(diff.contains("foo")); assertTrue(diff.contains("bar")); diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java index a9ac904c36c..c37b6ffe915 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java @@ -3,8 +3,8 @@ package com.yahoo.jdisc.core; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.LinkedList; +import java.util.List; import java.util.Queue; import static com.yahoo.jdisc.core.ScheduledQueue.MILLIS_PER_SLOT; @@ -123,6 +123,6 @@ public class ScheduledQueueTestCase { Queue<Object> expired = new LinkedList<>(); queue.drainTo(currentTimeMillis, expired); assertEquals(expected.length, expired.size()); - assertEquals(Arrays.asList(expected), expired); + assertEquals(List.of(expected), expired); } } diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java index c672b33ff2b..acfe8d32e61 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java @@ -12,7 +12,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.ByteBuffer; -import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; @@ -31,7 +30,7 @@ public class RequestDispatchTestCase { @Test void requireThatRequestCanBeDispatched() throws Exception { final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(); - final List<ByteBuffer> writtenContent = Arrays.asList(ByteBuffer.allocate(6), ByteBuffer.allocate(9)); + final List<ByteBuffer> writtenContent = List.of(ByteBuffer.allocate(6), ByteBuffer.allocate(9)); ReadableContentChannel receivedContent = new ReadableContentChannel(); ContainerBuilder builder = driver.newContainerBuilder(); Response response = new Response(Response.Status.OK); @@ -154,7 +153,7 @@ public class RequestDispatchTestCase { @Override protected Iterable<ByteBuffer> requestContent() { - return Arrays.asList(ByteBuffer.allocate(69)); + return List.of(ByteBuffer.allocate(69)); } }.dispatch(); fail(); @@ -192,7 +191,7 @@ public class RequestDispatchTestCase { @Override protected Iterable<ByteBuffer> requestContent() { - return Arrays.asList(ByteBuffer.allocate(69)); + return List.of(ByteBuffer.allocate(69)); } }.dispatch(); fail(); diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java index 84bdc07dd33..32481b4607e 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java @@ -8,7 +8,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; -import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -46,7 +45,7 @@ public class ResponseDispatchTestCase { ReadableContentChannel content = new ReadableContentChannel(); FutureResponse handler = new FutureResponse(content); ByteBuffer buf = ByteBuffer.allocate(69); - ResponseDispatch.newInstance(69, Arrays.asList(buf)).dispatch(handler); + ResponseDispatch.newInstance(69, List.of(buf)).dispatch(handler); Response response = handler.get(600, TimeUnit.SECONDS); assertNotNull(response); assertEquals(69, response.getStatus()); @@ -57,7 +56,7 @@ public class ResponseDispatchTestCase { ReadableContentChannel content = new ReadableContentChannel(); FutureResponse handler = new FutureResponse(content); ByteBuffer buf = ByteBuffer.allocate(69); - ResponseDispatch.newInstance(69, Arrays.asList(buf)).dispatch(handler); + ResponseDispatch.newInstance(69, List.of(buf)).dispatch(handler); Response response = handler.get(600, TimeUnit.SECONDS); assertNotNull(response); assertEquals(69, response.getStatus()); @@ -69,7 +68,7 @@ public class ResponseDispatchTestCase { FutureResponse handler = new FutureResponse(content); ByteBuffer buf = ByteBuffer.allocate(69); Response sentResponse = new Response(69); - ResponseDispatch.newInstance(sentResponse, Arrays.asList(buf)).dispatch(handler); + ResponseDispatch.newInstance(sentResponse, List.of(buf)).dispatch(handler); Response receivedResponse = handler.get(600, TimeUnit.SECONDS); assertSame(sentResponse, receivedResponse); assertSame(buf, content.read()); @@ -80,7 +79,7 @@ public class ResponseDispatchTestCase { @Test void requireThatResponseCanBeDispatched() throws Exception { final Response response = new Response(Response.Status.OK); - final List<ByteBuffer> writtenContent = Arrays.asList(ByteBuffer.allocate(6), ByteBuffer.allocate(9)); + final List<ByteBuffer> writtenContent = List.of(ByteBuffer.allocate(6), ByteBuffer.allocate(9)); ResponseDispatch dispatch = new ResponseDispatch() { @Override diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java index 84da19c221a..56d7d2959e8 100644 --- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java +++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java @@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test; import java.net.URI; import java.nio.ByteBuffer; -import java.util.Arrays; +import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; @@ -170,7 +170,7 @@ public class ThreadedRequestHandlerTestCase { @Override protected Iterable<ByteBuffer> requestContent() { - return Arrays.asList(content); + return List.of(content); } }.dispatch(); } diff --git a/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryIntegrationTest.java b/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryIntegrationTest.java index f3d936b20d0..9c37fc7e0de 100644 --- a/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryIntegrationTest.java +++ b/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryIntegrationTest.java @@ -10,7 +10,6 @@ import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; @@ -56,7 +55,7 @@ public class GuiceRepositoryIntegrationTest { BundleInstaller installer = new BundleInstaller(driver.osgiFramework()); Bundle bundle = installer.installAndStart("my-guice-module.jar").get(0); - builder.guiceModules().installAll(bundle, Arrays.asList("com.yahoo.jdisc.bundle.MyGuiceModule", + builder.guiceModules().installAll(bundle, List.of("com.yahoo.jdisc.bundle.MyGuiceModule", "com.yahoo.jdisc.bundle.MyGuiceModule")); List<Module> next = new LinkedList<>(builder.guiceModules().collection()); next.removeAll(prev); diff --git a/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/application/ServerRepositoryIntegrationTest.java b/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/application/ServerRepositoryIntegrationTest.java index 04b88654112..1232e0ecf0d 100644 --- a/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/application/ServerRepositoryIntegrationTest.java +++ b/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/application/ServerRepositoryIntegrationTest.java @@ -8,8 +8,8 @@ import com.yahoo.jdisc.test.TestDriver; import org.junit.Test; import org.osgi.framework.Bundle; -import java.util.Arrays; import java.util.Iterator; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -54,7 +54,7 @@ public class ServerRepositoryIntegrationTest { BundleInstaller installer = new BundleInstaller(driver.osgiFramework()); Bundle bundle = installer.installAndStart("my-server-provider.jar").get(0); ContainerBuilder builder = driver.newContainerBuilder(); - builder.serverProviders().installAll(bundle, Arrays.asList("com.yahoo.jdisc.bundle.MyServerProvider", + builder.serverProviders().installAll(bundle, List.of("com.yahoo.jdisc.bundle.MyServerProvider", "com.yahoo.jdisc.bundle.MyServerProvider")); Iterator<ServerProvider> it = builder.serverProviders().iterator(); assertTrue(it.hasNext()); diff --git a/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderIntegrationTest.java b/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderIntegrationTest.java index a0fde346901..cf8914ea39a 100644 --- a/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderIntegrationTest.java +++ b/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderIntegrationTest.java @@ -8,8 +8,8 @@ import org.apache.felix.framework.util.FelixConstants; import org.junit.Test; import org.osgi.framework.Bundle; -import java.util.Arrays; import java.util.Iterator; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -29,7 +29,7 @@ public class ApplicationLoaderIntegrationTest { public void requireThatLifecycleWorks() throws Exception { MyModule module = new MyModule(); ApplicationLoader loader = new ApplicationLoader(TestDriver.newOsgiFramework(), - Arrays.asList(module)); + List.of(module)); loader.init("app-a.jar", false); assertFalse(module.init.await(100, TimeUnit.MILLISECONDS)); diff --git a/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/core/FelixFrameworkIntegrationTest.java b/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/core/FelixFrameworkIntegrationTest.java index f91407326c5..53a2b20a0b1 100644 --- a/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/core/FelixFrameworkIntegrationTest.java +++ b/jdisc_core_test/integration_test/src/test/java/com/yahoo/jdisc/core/FelixFrameworkIntegrationTest.java @@ -8,7 +8,6 @@ import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; -import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -214,7 +213,7 @@ public class FelixFrameworkIntegrationTest { for (Bundle bundle : bundles) { actual.add(bundle.getSymbolicName()); } - assertEquals(Arrays.asList(expectedBundles), actual); + assertEquals(List.of(expectedBundles), actual); felix.startBundles(bundles, false); if (className != null) { assertNotNull(bundles.get(0).loadClass(className).getDeclaredConstructor().newInstance()); diff --git a/jrt/src/com/yahoo/jrt/tool/RpcInvoker.java b/jrt/src/com/yahoo/jrt/tool/RpcInvoker.java index 70beb291527..0de39cbbcd2 100644 --- a/jrt/src/com/yahoo/jrt/tool/RpcInvoker.java +++ b/jrt/src/com/yahoo/jrt/tool/RpcInvoker.java @@ -17,7 +17,6 @@ import com.yahoo.jrt.Value; import com.yahoo.jrt.Values; import java.time.Duration; -import java.util.Arrays; import java.util.List; import java.util.ArrayList; @@ -108,7 +107,7 @@ public class RpcInvoker { System.err.println(" supported types: {'b','h','i','l','f','d','s'}"); System.exit(0); } - List<String> arguments = new ArrayList<String>(Arrays.asList(args)); + List<String> arguments = new ArrayList<String>(List.of(args)); String connectSpec = "localhost:8086"; if ("-h".equals(arguments.get(0)) && arguments.size() >= 3) { arguments.remove(0); // Consume -h diff --git a/jrt/tests/com/yahoo/jrt/CryptoUtils.java b/jrt/tests/com/yahoo/jrt/CryptoUtils.java index 7bad0e64aa8..772e7722391 100644 --- a/jrt/tests/com/yahoo/jrt/CryptoUtils.java +++ b/jrt/tests/com/yahoo/jrt/CryptoUtils.java @@ -25,7 +25,6 @@ import static com.yahoo.security.X509CertificateBuilder.generateRandomSerialNumb import static java.time.Instant.EPOCH; import static java.time.temporal.ChronoUnit.DAYS; import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; /** * @author bjorncs @@ -42,8 +41,7 @@ class CryptoUtils { singleton( new PeerPolicy( "localhost-policy", - singletonList( - RequiredPeerCredential.of(Field.CN, "localhost"))))); + List.of(RequiredPeerCredential.of(Field.CN, "localhost"))))); static TlsContext createTestTlsContext() { return DefaultTlsContext.of( diff --git a/linguistics/src/test/java/com/yahoo/language/LanguageTestCase.java b/linguistics/src/test/java/com/yahoo/language/LanguageTestCase.java index 1b1c9eb21cb..3be57cb21cf 100644 --- a/linguistics/src/test/java/com/yahoo/language/LanguageTestCase.java +++ b/linguistics/src/test/java/com/yahoo/language/LanguageTestCase.java @@ -3,7 +3,6 @@ package com.yahoo.language; import org.junit.Test; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; @@ -15,7 +14,7 @@ public class LanguageTestCase { @Test public void requireThatSpecificLanguagesAreCjk() { - List<Language> cjk = Arrays.asList(Language.CHINESE_SIMPLIFIED, + List<Language> cjk = List.of(Language.CHINESE_SIMPLIFIED, Language.CHINESE_TRADITIONAL, Language.JAPANESE, Language.KOREAN, diff --git a/linguistics/src/test/java/com/yahoo/language/process/GramSplitterTestCase.java b/linguistics/src/test/java/com/yahoo/language/process/GramSplitterTestCase.java index b6e33d70ae6..69094cab8f2 100644 --- a/linguistics/src/test/java/com/yahoo/language/process/GramSplitterTestCase.java +++ b/linguistics/src/test/java/com/yahoo/language/process/GramSplitterTestCase.java @@ -6,8 +6,8 @@ import com.yahoo.language.process.GramSplitter.GramSplitterIterator; import com.yahoo.language.simple.SimpleLinguistics; import org.junit.Test; -import java.util.Arrays; import java.util.Iterator; +import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -220,7 +220,7 @@ public class GramSplitterTestCase { } private void assertGramSplits(String input, int gramSize, String ... expected) { - assertEquals(Arrays.asList(expected), gramSplitter.split(input, gramSize).toExtractedList()); + assertEquals(List.of(expected), gramSplitter.split(input, gramSize).toExtractedList()); } private void assertGramSplit(String input, int gramSize, String expected) { diff --git a/linguistics/src/test/java/com/yahoo/language/process/SegmenterImplTestCase.java b/linguistics/src/test/java/com/yahoo/language/process/SegmenterImplTestCase.java index f4ec53d1f38..7e097736abe 100644 --- a/linguistics/src/test/java/com/yahoo/language/process/SegmenterImplTestCase.java +++ b/linguistics/src/test/java/com/yahoo/language/process/SegmenterImplTestCase.java @@ -8,7 +8,6 @@ import com.yahoo.language.simple.SimpleTokenizer; import org.junit.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; @@ -22,25 +21,25 @@ public class SegmenterImplTestCase { @Test public void requireThatNonIndexableCharactersAreDelimiters() { - assertSegments("i've", Arrays.asList("i", "ve")); - assertSegments("foo bar. baz", Arrays.asList("foo", "bar", "baz")); - assertSegments("1,2, 3 4", Arrays.asList("1", "2", "3", "4")); + assertSegments("i've", List.of("i", "ve")); + assertSegments("foo bar. baz", List.of("foo", "bar", "baz")); + assertSegments("1,2, 3 4", List.of("1", "2", "3", "4")); } @Test public void requireThatAdjacentIndexableTokenTypesAreNotSplit() { - assertSegments("a1,2b,c3,4d", Arrays.asList("a1", "2b", "c3", "4d")); + assertSegments("a1,2b,c3,4d", List.of("a1", "2b", "c3", "4d")); } @Test public void requireThatSegmentationReturnsOriginalForm() { - assertSegments("a\u030A", Arrays.asList("a\u030A")); - assertSegments("FOO BAR", Arrays.asList("FOO", "BAR")); + assertSegments("a\u030A", List.of("a\u030A")); + assertSegments("FOO BAR", List.of("FOO", "BAR")); } @Test public void requireThatEmptyInputIsPreserved() { - assertSegments("", Arrays.asList("")); + assertSegments("", List.of("")); } private static void assertSegments(String input, List<String> expectedSegments) { @@ -51,7 +50,7 @@ public class SegmenterImplTestCase { public void requireThatEmptyStringsAreSuppressed() { Tokenizer fancyTokenizer = new FancyTokenizer(); Segmenter fancySegmenter = new SegmenterImpl(fancyTokenizer); - List<String> expectedSegments = Arrays.asList("juice", "\u00BD", "oz"); + List<String> expectedSegments = List.of("juice", "\u00BD", "oz"); String input = "juice \u00BD oz"; assertEquals(expectedSegments, fancySegmenter.segment(input, Language.ENGLISH)); } diff --git a/linguistics/src/test/java/com/yahoo/language/process/StemmerImplTestCase.java b/linguistics/src/test/java/com/yahoo/language/process/StemmerImplTestCase.java index 9c5914baeb9..785225a5096 100644 --- a/linguistics/src/test/java/com/yahoo/language/process/StemmerImplTestCase.java +++ b/linguistics/src/test/java/com/yahoo/language/process/StemmerImplTestCase.java @@ -8,7 +8,6 @@ import com.yahoo.language.simple.SimpleTokenizer; import org.junit.Test; import org.mockito.Mockito; -import java.util.Arrays; import java.util.List; import java.util.ArrayList; @@ -21,13 +20,13 @@ public class StemmerImplTestCase { @Test public void requireThatStemIsNormalizedAndLowerCased() { - assertStem("FOO", Arrays.asList("foo")); - assertStem("a\u030A", Arrays.asList("\u00E5")); + assertStem("FOO", List.of("foo")); + assertStem("a\u030A", List.of("\u00E5")); } @Test public void requireThatOnlyIndexableTokensAreReturned() { - assertStem("foo. (bar)!", Arrays.asList("foo", "bar")); + assertStem("foo. (bar)!", List.of("foo", "bar")); } @Test @@ -43,17 +42,17 @@ public class StemmerImplTestCase { Tokenizer tokenizer = Mockito.mock(Tokenizer.class); Mockito.when(tokenizer.tokenize(Mockito.anyString(), Mockito.<Language>any(), Mockito.<StemMode>any(), Mockito.anyBoolean())) - .thenReturn(Arrays.<Token>asList(token)); + .thenReturn(List.of(token)); Stemmer stemmer = new StemmerImpl(tokenizer); token.setSpecialToken(false); - assertEquals(Arrays.asList(new StemList("c"), + assertEquals(List.of(new StemList("c"), new StemList("p"), new StemList("p")), stemmer.stem("c++", StemMode.SHORTEST, Language.ENGLISH)); token.setSpecialToken(true); - assertEquals(Arrays.asList(new StemList("c++")), + assertEquals(List.of(new StemList("c++")), stemmer.stem("c++", StemMode.SHORTEST, Language.ENGLISH)); } diff --git a/linguistics/src/test/java/com/yahoo/language/process/TokenizationTestCase.java b/linguistics/src/test/java/com/yahoo/language/process/TokenizationTestCase.java index cf5a26c1f04..2cfb6c33b93 100644 --- a/linguistics/src/test/java/com/yahoo/language/process/TokenizationTestCase.java +++ b/linguistics/src/test/java/com/yahoo/language/process/TokenizationTestCase.java @@ -7,7 +7,6 @@ import org.junit.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; @@ -31,23 +30,23 @@ public class TokenizationTestCase { @Test public void testTokenizer() { assertTokenize("This is a test, 123", - Arrays.asList("this", "is", "a", "test", "123"), - Arrays.asList("This", " ", "is", " ", "a", " ", "test", ",", " ", "123")); + List.of("this", "is", "a", "test", "123"), + List.of("This", " ", "is", " ", "a", " ", "test", ",", " ", "123")); } @Test public void testUnderScoreTokenization() { - assertTokenize("ugcapi_1", Language.ENGLISH, StemMode.SHORTEST, true, Arrays.asList("ugcapi", "1"), null); + assertTokenize("ugcapi_1", Language.ENGLISH, StemMode.SHORTEST, true, List.of("ugcapi", "1"), null); } @Test public void testPhrasesWithPunctuation() { assertTokenize("PHY_101.html a space/time or space-time course", Language.ENGLISH, StemMode.NONE, false, - Arrays.asList("phy", "101", "html", "a", "space", "time", "or", "space", "time", "course"), + List.of("phy", "101", "html", "a", "space", "time", "or", "space", "time", "course"), null); - assertTokenize("PHY_101.", Language.ENGLISH, StemMode.NONE, false, Arrays.asList("phy", "101"), null); - assertTokenize("101.3", Language.ENGLISH, StemMode.NONE, false, Arrays.asList("101", "3"), null); + assertTokenize("PHY_101.", Language.ENGLISH, StemMode.NONE, false, List.of("phy", "101"), null); + assertTokenize("101.3", Language.ENGLISH, StemMode.NONE, false, List.of("101", "3"), null); } @Test diff --git a/linguistics/src/test/java/com/yahoo/language/simple/TokenizerTester.java b/linguistics/src/test/java/com/yahoo/language/simple/TokenizerTester.java index 401b89f0696..021f04b8b87 100644 --- a/linguistics/src/test/java/com/yahoo/language/simple/TokenizerTester.java +++ b/linguistics/src/test/java/com/yahoo/language/simple/TokenizerTester.java @@ -8,7 +8,6 @@ import com.yahoo.language.process.Token; import com.yahoo.language.process.TokenScript; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; @@ -28,7 +27,7 @@ public class TokenizerTester { for (Token token : tokenize(input)) { findTokenStrings(token, actual); } - assertEquals(Arrays.asList(expectedTokenStrings), actual); + assertEquals(List.of(expectedTokenStrings), actual); } public void assertTokenScripts(String input, TokenScript... expectedTokenScripts) { @@ -36,7 +35,7 @@ public class TokenizerTester { for (Token token : tokenize(input)) { findTokenScripts(token, actual); } - assertEquals(Arrays.asList(expectedTokenScripts), actual); + assertEquals(List.of(expectedTokenScripts), actual); } public List<String> findTokenStrings(Token token, List<String> out) { diff --git a/messagebus/src/main/java/com/yahoo/messagebus/RPCMessageBus.java b/messagebus/src/main/java/com/yahoo/messagebus/RPCMessageBus.java index 86504d3ad35..d4cec5de323 100644 --- a/messagebus/src/main/java/com/yahoo/messagebus/RPCMessageBus.java +++ b/messagebus/src/main/java/com/yahoo/messagebus/RPCMessageBus.java @@ -5,7 +5,6 @@ import com.yahoo.messagebus.network.Identity; import com.yahoo.messagebus.network.rpc.RPCNetwork; import com.yahoo.messagebus.network.rpc.RPCNetworkParams; -import java.util.Arrays; import java.util.List; /** @@ -76,7 +75,7 @@ public class RPCMessageBus extends NetworkMessageBus { * destination sessions to be routed to. */ public RPCMessageBus(Protocol protocol, String configId) { - this(Arrays.asList(protocol), new RPCNetworkParams().setIdentity(new Identity(configId)), null); + this(List.of(protocol), new RPCNetworkParams().setIdentity(new Identity(configId)), null); } /** diff --git a/messagebus/src/main/java/com/yahoo/messagebus/routing/test/CustomPolicyFactory.java b/messagebus/src/main/java/com/yahoo/messagebus/routing/test/CustomPolicyFactory.java index 2e568598a94..10a7089fd20 100755..100644 --- a/messagebus/src/main/java/com/yahoo/messagebus/routing/test/CustomPolicyFactory.java +++ b/messagebus/src/main/java/com/yahoo/messagebus/routing/test/CustomPolicyFactory.java @@ -6,7 +6,6 @@ import com.yahoo.messagebus.routing.RoutingPolicy; import com.yahoo.messagebus.test.SimpleProtocol; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -26,7 +25,7 @@ public class CustomPolicyFactory implements SimpleProtocol.PolicyFactory { } public CustomPolicyFactory(boolean selectOnRetry, int consumableError) { - this(selectOnRetry, Arrays.asList(consumableError)); + this(selectOnRetry, List.of(consumableError)); } public CustomPolicyFactory(boolean selectOnRetry, List<Integer> consumableErrors) { diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java index 5a3d96991bb..4d51d265cc0 100755..100644 --- a/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java +++ b/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java @@ -9,7 +9,8 @@ import com.yahoo.messagebus.test.SimpleMessage; import com.yahoo.messagebus.test.SimpleProtocol; import org.junit.jupiter.api.Test; -import java.util.Arrays; + +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -33,9 +34,9 @@ public class ErrorTestCase { @Test void requireThatErrorIsPropagated() throws Exception { RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME); - table.addHop("itr", "test/itr/session", Arrays.asList("test/itr/session")); - table.addHop("dst", "test/dst/session", Arrays.asList("test/dst/session")); - table.addRoute("test", Arrays.asList("itr", "dst")); + table.addHop("itr", "test/itr/session", List.of("test/itr/session")); + table.addHop("dst", "test/dst/session", List.of("test/dst/session")); + table.addRoute("test", List.of("itr", "dst")); Slobrok slobrok = new Slobrok(); TestServer src = new TestServer("test/src", table, slobrok, null); diff --git a/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java index 7d46add79c9..0aeeba68080 100755..100644 --- a/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java +++ b/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java @@ -12,8 +12,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.net.UnknownHostException; -import java.util.Arrays; +import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -31,9 +30,9 @@ public class TraceTripTestCase { @BeforeEach public void setUp() throws ListenFailedException { RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME) - .addHop("pxy", "test/pxy/session", Arrays.asList("test/pxy/session")) - .addHop("dst", "test/dst/session", Arrays.asList("test/dst/session")) - .addRoute("test", Arrays.asList("pxy", "dst")); + .addHop("pxy", "test/pxy/session", List.of("test/pxy/session")) + .addHop("dst", "test/dst/session", List.of("test/dst/session")) + .addRoute("test", List.of("pxy", "dst")); slobrok = new Slobrok(); src = new TestServer("test/src", table, slobrok, null); @@ -82,7 +81,7 @@ public class TraceTripTestCase { } private static class Proxy implements MessageHandler, ReplyHandler { - private IntermediateSession session; + private final IntermediateSession session; public Proxy(MessageBus bus) { session = bus.createIntermediateSession("session", true, this, this); @@ -102,7 +101,7 @@ public class TraceTripTestCase { } private static class Server implements MessageHandler { - private DestinationSession session; + private final DestinationSession session; public Server(MessageBus bus) { session = bus.createDestinationSession("session", true, this); diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java index 6612421e437..f62e586d1e2 100644 --- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java +++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java @@ -16,7 +16,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -36,7 +35,7 @@ public class BasicNetworkTestCase { RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME); table.addHop("pxy", "test/pxy/session", List.of("test/pxy/session")); table.addHop("dst", "test/dst/session", List.of("test/dst/session")); - table.addRoute("test", Arrays.asList("pxy", "dst")); + table.addRoute("test", List.of("pxy", "dst")); slobrok = new Slobrok(); src = new TestServer("test/src", table, slobrok, null); pxy = new TestServer("test/pxy", table, slobrok, null); diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java index 061416b9eed..c30b4e2aa03 100755..100644 --- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java +++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java @@ -26,7 +26,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.net.UnknownHostException; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -87,7 +86,7 @@ public class SendAdapterTestCase { @Test void requireThatMessagesCanBeSentAcrossAllSupportedVersions() { - List<Version> versions = Arrays.asList( + List<Version> versions = List.of( new Version(6, 149), new Version(9, 999) ); diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java index 37d0bbd4c92..ded431cd258 100755..100644 --- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java +++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java @@ -15,7 +15,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -62,8 +61,8 @@ public class RoutingContextTestCase { SimpleProtocol protocol = new SimpleProtocol(); protocol.addPolicyFactory("Custom", new CustomPolicyFactory( false, - Arrays.asList("foo", "bar", "baz/cox"), - Arrays.asList("foo", "bar"))); + List.of("foo", "bar", "baz/cox"), + List.of("foo", "bar"))); srcServer.mb.putProtocol(protocol); srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME) .addRoute(new RouteSpec("myroute").addHop("myhop")) @@ -83,8 +82,8 @@ public class RoutingContextTestCase { SimpleProtocol protocol = new SimpleProtocol(); protocol.addPolicyFactory("Custom", new CustomPolicyFactory( false, - Arrays.asList("foo", "foo/bar", "foo/bar0/baz", "foo/bar1/baz", "foo/bar/baz/cox"), - Arrays.asList("foo/bar0/baz", "foo/bar1/baz"))); + List.of("foo", "foo/bar", "foo/bar0/baz", "foo/bar1/baz", "foo/bar/baz/cox"), + List.of("foo/bar0/baz", "foo/bar1/baz"))); srcServer.mb.putProtocol(protocol); srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME) .addRoute(new RouteSpec("myroute").addHop("myhop")) diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java index 96250e77d06..992c3e99e87 100755..100644 --- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java +++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java @@ -6,7 +6,6 @@ import com.yahoo.messagebus.ConfigHandler; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -71,17 +70,17 @@ public class RoutingSpecTestCase { @Test void testApplicationSpec() { assertApplicationSpec(List.of("foo"), - Arrays.asList("foo", + List.of("foo", "*")); assertApplicationSpec(List.of("foo/bar"), - Arrays.asList("foo/bar", + List.of("foo/bar", "foo/*", "*/bar", "*/*")); - assertApplicationSpec(Arrays.asList("foo/0/baz", + assertApplicationSpec(List.of("foo/0/baz", "foo/1/baz", "foo/2/baz"), - Arrays.asList("foo/0/baz", + List.of("foo/0/baz", "foo/1/baz", "foo/2/baz", "foo/0/*", @@ -259,7 +258,7 @@ public class RoutingSpecTestCase { new ApplicationSpec() .addService("mytable", "bar") .addService("mytable", "baz"), - Arrays.asList("Routing table 'mytable' is defined 2 times.", + List.of("Routing table 'mytable' is defined 2 times.", "For hop 'hop2' in routing table 'mytable'; Failed to parse empty string.", "For hop 'hop3' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.", "For hop 1 in route 'route2' in routing table 'mytable'; Failed to parse empty string.", diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java index 5eac60f4eb2..ac8e1d74191 100644 --- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java +++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java @@ -31,7 +31,6 @@ import org.junit.jupiter.api.Test; import java.net.UnknownHostException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import java.util.logging.Level; @@ -270,7 +269,7 @@ public class RoutingTestCase { dstSession.acknowledge(msg); assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60)); assertFalse(reply.hasErrors()); - assertTrace(Arrays.asList("[APP_TRANSIENT_ERROR @ localhost]: err1", + assertTrace(List.of("[APP_TRANSIENT_ERROR @ localhost]: err1", "-[APP_TRANSIENT_ERROR @ localhost]: err1", "[APP_TRANSIENT_ERROR @ localhost]: err2", "-[APP_TRANSIENT_ERROR @ localhost]: err2"), @@ -298,7 +297,7 @@ public class RoutingTestCase { dstSession.acknowledge(msg); assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60)); assertFalse(reply.hasErrors()); - assertTrace(Arrays.asList("Source session accepted a 3 byte message. 1 message(s) now pending.", + assertTrace(List.of("Source session accepted a 3 byte message. 1 message(s) now pending.", "Running routing policy 'Custom'.", "Selecting [" + dstSessName + "].", "Component '" + dstSessName + "' selected by policy 'Custom'.", @@ -371,7 +370,7 @@ public class RoutingTestCase { dstSession.acknowledge(msg); assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60)); assertFalse(reply.hasErrors()); - assertTrace(Arrays.asList("Selecting [" + dstSessName + "].", + assertTrace(List.of("Selecting [" + dstSessName + "].", "[APP_TRANSIENT_ERROR @ localhost]", "-[APP_TRANSIENT_ERROR @ localhost]", "Merged [" + dstSessName + "].", @@ -397,7 +396,7 @@ public class RoutingTestCase { dstSession.acknowledge(msg); assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60)); assertFalse(reply.hasErrors()); - assertTrace(Arrays.asList("Selecting [" + dstSessName + "].", + assertTrace(List.of("Selecting [" + dstSessName + "].", "[APP_TRANSIENT_ERROR @ localhost]", "-[APP_TRANSIENT_ERROR @ localhost]", "Merged [" + dstSessName + "].", @@ -421,7 +420,7 @@ public class RoutingTestCase { assertNotNull(reply); assertEquals(1, reply.getNumErrors()); assertEquals(ErrorCode.NO_ADDRESS_FOR_SERVICE, reply.getError(0).getCode()); - assertTrace(Arrays.asList("Selecting [" + dstSessName + ", dst/unknown].", + assertTrace(List.of("Selecting [" + dstSessName + ", dst/unknown].", "[NO_ADDRESS_FOR_SERVICE @ localhost]", "Sending reply", "Merged [" + dstSessName + ", dst/unknown]."), @@ -439,7 +438,7 @@ public class RoutingTestCase { assertNotNull(reply); assertEquals(1, reply.getNumErrors()); assertEquals(ErrorCode.NO_ADDRESS_FOR_SERVICE, reply.getError(0).getCode()); - assertTrace(Arrays.asList("Selecting [dst/unknown].", + assertTrace(List.of("Selecting [dst/unknown].", "[NO_ADDRESS_FOR_SERVICE @ localhost]", "Merged [dst/unknown]."), reply.getTrace()); @@ -479,7 +478,7 @@ public class RoutingTestCase { Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60); assertNotNull(reply); assertFalse(reply.hasErrors()); - assertTrace(Arrays.asList("[NO_ADDRESS_FOR_SERVICE @ localhost]", + assertTrace(List.of("[NO_ADDRESS_FOR_SERVICE @ localhost]", "-[NO_ADDRESS_FOR_SERVICE @ localhost]", "Sending message", "-Sending message"), @@ -537,7 +536,7 @@ public class RoutingTestCase { CustomPolicyFactory.parseRoutes(param), 0)); protocol.addPolicyFactory("SetReply", param -> new SetReplyPolicy(false, - Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR, ErrorCode.APP_FATAL_ERROR), + List.of(ErrorCode.APP_TRANSIENT_ERROR, ErrorCode.APP_FATAL_ERROR), param)); srcServer.mb.putProtocol(protocol); assertTrue(srcSession @@ -550,7 +549,7 @@ public class RoutingTestCase { assertEquals(1, reply.getNumErrors()); assertEquals(ErrorCode.APP_FATAL_ERROR, reply.getError(0).getCode()); assertEquals("foo", reply.getError(0).getMessage()); - assertTrace(Arrays.asList("Resolving '[SetReply:foo]'.", + assertTrace(List.of("Resolving '[SetReply:foo]'.", "Resolving '" + dstSessName + "'.", "Resender resending message.", "Resolving '" + dstSessName + "'.", @@ -722,7 +721,7 @@ public class RoutingTestCase { SimpleProtocol protocol = new SimpleProtocol(); protocol.addPolicyFactory("Custom", new CustomPolicyFactory(false)); protocol.addPolicyFactory("SetReply", param -> new SetReplyPolicy(false, - Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR, + List.of(ErrorCode.APP_TRANSIENT_ERROR, ErrorCode.APP_TRANSIENT_ERROR, ErrorCode.APP_FATAL_ERROR), param)); @@ -870,7 +869,7 @@ public class RoutingTestCase { Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60); assertNotNull(reply); assertFalse(reply.hasErrors()); - assertTrace(Arrays.asList(expectedTrace), reply.getTrace()); + assertTrace(List.of(expectedTrace), reply.getTrace()); } public static void assertTrace(List<String> expected, Trace trace) { diff --git a/messagebus_test/src/tests/error/JavaClient.java b/messagebus_test/src/tests/error/JavaClient.java index 764cf4c1d86..3a420caa6ec 100644 --- a/messagebus_test/src/tests/error/JavaClient.java +++ b/messagebus_test/src/tests/error/JavaClient.java @@ -6,8 +6,8 @@ import com.yahoo.messagebus.routing.*; import com.yahoo.messagebus.network.*; import com.yahoo.messagebus.network.rpc.*; import com.yahoo.messagebus.network.rpc.test.*; -import java.util.Arrays; import java.util.logging.*; +import java.util.List; public class JavaClient { @@ -16,7 +16,7 @@ public class JavaClient { public static void main(String[] args) { try { RPCMessageBus mb = new RPCMessageBus( - Arrays.asList((Protocol)new SimpleProtocol()), + List.of(new SimpleProtocol()), new RPCNetworkParams() .setIdentity(new Identity("server/java")) .setSlobrokConfigId("file:slobrok.cfg"), diff --git a/messagebus_test/src/tests/error/JavaServer.java b/messagebus_test/src/tests/error/JavaServer.java index 7cc366fd7b4..1baa63b0b6e 100644 --- a/messagebus_test/src/tests/error/JavaServer.java +++ b/messagebus_test/src/tests/error/JavaServer.java @@ -5,8 +5,8 @@ import com.yahoo.config.*; import com.yahoo.messagebus.routing.*; import com.yahoo.messagebus.network.*; import com.yahoo.messagebus.network.rpc.*; -import java.util.Arrays; import java.util.logging.*; +import java.util.List; public class JavaServer implements MessageHandler { @@ -29,7 +29,7 @@ public class JavaServer implements MessageHandler { public static void main(String[] args) { try { RPCMessageBus mb = new RPCMessageBus( - Arrays.asList((Protocol)new SimpleProtocol()), + List.of(new SimpleProtocol()), new RPCNetworkParams() .setIdentity(new Identity("server/java")) .setSlobrokConfigId("file:slobrok.cfg"), diff --git a/messagebus_test/src/tests/speed/JavaServer.java b/messagebus_test/src/tests/speed/JavaServer.java index 256f6f00223..58f18237041 100644 --- a/messagebus_test/src/tests/speed/JavaServer.java +++ b/messagebus_test/src/tests/speed/JavaServer.java @@ -5,8 +5,8 @@ import com.yahoo.config.*; import com.yahoo.messagebus.routing.*; import com.yahoo.messagebus.network.*; import com.yahoo.messagebus.network.rpc.*; -import java.util.Arrays; import java.util.logging.*; +import java.util.List; public class JavaServer implements MessageHandler { @@ -36,7 +36,7 @@ public class JavaServer implements MessageHandler { public static void main(String[] args) { try { RPCMessageBus mb = new RPCMessageBus( - Arrays.asList((Protocol)new SimpleProtocol()), + List.of(new SimpleProtocol()), new RPCNetworkParams() .setIdentity(new Identity("server/java")) .setSlobrokConfigId("file:slobrok.cfg"), diff --git a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/core/MetricsManager.java b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/core/MetricsManager.java index b610c57cd99..60e85f3f9e4 100644 --- a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/core/MetricsManager.java +++ b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/core/MetricsManager.java @@ -13,7 +13,6 @@ import ai.vespa.metricsproxy.service.VespaServices; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -107,7 +106,7 @@ public class MetricsManager { * NOTE: Use {@link #getMetrics(List, Instant)} instead, unless further processing of the metrics is necessary. */ public List<MetricsPacket.Builder> getMetricsAsBuilders(List<VespaService> services, Instant startTime, ConsumerId consumerId) { - if (services.isEmpty()) return Collections.emptyList(); + if (services.isEmpty()) return List.of(); log.log(FINE, () -> "Updating services prior to fetching metrics, number of services= " + services.size()); vespaServices.updateServices(services); @@ -164,7 +163,7 @@ public class MetricsManager { * @return Health metrics for all matching services. */ public List<MetricsPacket> getHealthMetrics(List<VespaService> services) { - if (services.isEmpty()) return Collections.emptyList(); + if (services.isEmpty()) return List.of(); vespaServices.updateServices(services); // TODO: Add global dimensions to health metrics? @@ -190,7 +189,7 @@ public class MetricsManager { public void purgeExtraMetrics() { extraDimensions = new HashMap<>(); - externalMetrics.setExtraMetrics(Collections.emptyList()); + externalMetrics.setExtraMetrics(List.of()); } /** diff --git a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/core/VespaMetrics.java b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/core/VespaMetrics.java index 9fe5983d5b9..4dabc7a66d8 100644 --- a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/core/VespaMetrics.java +++ b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/core/VespaMetrics.java @@ -17,7 +17,6 @@ import ai.vespa.metricsproxy.service.VespaService; import java.time.Instant; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -140,7 +139,7 @@ public class VespaMetrics { if ( ! configuredDimensions.isEmpty()) { Map<DimensionId, String> dims = new HashMap<>(dimensions); configuredDimensions.forEach(d -> dims.put(d.key(), d.value())); - dimensions = Collections.unmodifiableMap(dims); + dimensions = Map.copyOf(dims); } return dimensions; } @@ -222,10 +221,10 @@ public class VespaMetrics { } private List<ConfiguredMetric> getMetricDefinitions(ConsumerId consumer) { - if (metricsConsumers == null) return Collections.emptyList(); + if (metricsConsumers == null) return List.of(); List<ConfiguredMetric> definitions = metricsConsumers.getMetricDefinitions(consumer); - return definitions == null ? Collections.emptyList() : definitions; + return definitions == null ? List.of() : definitions; } private static void setMetaInfo(MetricsPacket.Builder builder, Instant timestamp) { diff --git a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/MetricsPacket.java b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/MetricsPacket.java index 53c6c533518..fb08d78a975 100644 --- a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/MetricsPacket.java +++ b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/MetricsPacket.java @@ -14,7 +14,6 @@ import java.util.Objects; import java.util.Set; import java.util.function.Function; -import static java.util.Collections.unmodifiableMap; import static java.util.stream.Collectors.joining; /** @@ -42,13 +41,13 @@ public class MetricsPacket { this.statusMessage = statusMessage; this.timestamp = timestamp; this.service = service; - this.metrics = metrics; - this.dimensions = dimensions; + this.metrics = Collections.unmodifiableMap(metrics); // Retain order for tests + this.dimensions = Collections.unmodifiableMap(dimensions); // Retain order for tests this.consumers = Set.copyOf(consumers); } - public Map<MetricId, Number> metrics() { return unmodifiableMap(metrics); } - public Map<DimensionId, String> dimensions() { return unmodifiableMap(dimensions); } + public Map<MetricId, Number> metrics() { return metrics; } + public Map<DimensionId, String> dimensions() { return dimensions; } public Set<ConsumerId> consumers() { return consumers;} @Override @@ -80,7 +79,7 @@ public class MetricsPacket { private long timestamp = 0L; private Map<MetricId, Number> metrics = new LinkedHashMap<>(); private final Map<DimensionId, String> dimensions = new LinkedHashMap<>(); - private Set<ConsumerId> consumers = Collections.emptySet(); + private Set<ConsumerId> consumers = Set.of(); public Builder(ServiceId service) { Objects.requireNonNull(service, "Service cannot be null."); @@ -169,7 +168,7 @@ public class MetricsPacket { if ((extraConsumers != null) && !extraConsumers.isEmpty()) { if (consumers.isEmpty()) { if (extraConsumers.size() == 1) { - consumers = Collections.singleton(extraConsumers.iterator().next()); + consumers = Set.of(extraConsumers.iterator().next()); return this; } consumers = new LinkedHashSet<>(extraConsumers.size()); diff --git a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/GenericJsonUtil.java b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/GenericJsonUtil.java index c32e90ecc9f..3d2bf7aaecf 100644 --- a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/GenericJsonUtil.java +++ b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/GenericJsonUtil.java @@ -18,8 +18,7 @@ import static ai.vespa.metricsproxy.metric.ExternalMetrics.VESPA_NODE_SERVICE_ID import static ai.vespa.metricsproxy.metric.model.DimensionId.toDimensionId; import static ai.vespa.metricsproxy.metric.model.MetricId.toMetricId; import static ai.vespa.metricsproxy.metric.model.json.JacksonUtil.objectMapper; -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; + import static java.util.logging.Level.WARNING; import static java.util.stream.Collectors.toList; @@ -90,7 +89,7 @@ public class GenericJsonUtil { return toMetricsPackets(jsonModel); } catch (IOException e) { log.log(WARNING, "Could not create metrics packet from string:\n" + jsonString, e); - return emptyList(); + return List.of(); } } @@ -106,7 +105,7 @@ public class GenericJsonUtil { if (node == null) return packets; if (node.metrics == null || node.metrics.isEmpty()) { - return singletonList(new MetricsPacket.Builder(VESPA_NODE_SERVICE_ID) + return List.of(new MetricsPacket.Builder(VESPA_NODE_SERVICE_ID) .statusCode(StatusCode.UP.ordinal()) .timestamp(node.timestamp)); } @@ -124,7 +123,7 @@ public class GenericJsonUtil { private static List<MetricsPacket.Builder> toServicePackets(GenericService service) { List<MetricsPacket.Builder> packets = new ArrayList<>(); if (service.metrics == null || service.metrics.isEmpty()) - return singletonList(newServicePacket(service)); + return List.of(newServicePacket(service)); for (var genericMetrics : service.metrics) { var packet = newServicePacket(service); diff --git a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/YamasJsonModel.java b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/YamasJsonModel.java index 3fd95220aca..44f4efb41cc 100644 --- a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/YamasJsonModel.java +++ b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/YamasJsonModel.java @@ -19,9 +19,6 @@ import java.util.Set; import java.util.stream.Collectors; import static com.yahoo.stream.CustomCollectors.toLinkedMap; -import static java.util.Collections.emptyList; -import static java.util.Collections.emptyMap; -import static java.util.Collections.emptySet; /** * Datamodel for Yamas execute output @@ -80,7 +77,7 @@ public class YamasJsonModel { } List<Metric> getMetricsList() { - if (metrics == null) return emptyList(); + if (metrics == null) return List.of(); return metrics.keySet().stream() .map(name -> new Metric(MetricId.toMetricId(name), metrics.get(name))) @@ -88,14 +85,14 @@ public class YamasJsonModel { } Map<DimensionId, String> getDimensionsById() { - if (dimensions == null) return emptyMap(); + if (dimensions == null) return Map.of(); return dimensions.keySet().stream().collect(toLinkedMap(DimensionId::toDimensionId, name -> dimensions.get(name))); } Set<ConsumerId> getYamasConsumers() { - if (routing == null || routing.get("yamas") == null) return emptySet(); + if (routing == null || routing.get("yamas") == null) return Set.of(); return routing.get("yamas").namespaces.stream() .map(ConsumerId::toConsumerId) diff --git a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/YamasJsonUtil.java b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/YamasJsonUtil.java index 82049da5115..649a4978ed9 100644 --- a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/YamasJsonUtil.java +++ b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/json/YamasJsonUtil.java @@ -21,7 +21,6 @@ import java.util.stream.Collectors; import static ai.vespa.metricsproxy.http.ValuesFetcher.defaultMetricsConsumerId; import static ai.vespa.metricsproxy.metric.model.json.JacksonUtil.objectMapper; -import static java.util.Collections.emptyList; import static java.util.logging.Level.WARNING; /** @@ -65,7 +64,7 @@ public class YamasJsonUtil { return packets; } catch (IOException e) { log.log(WARNING, "Could not create metrics packet from string:\n" + jsonString, e); - return emptyList(); + return List.of(); } } diff --git a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/prometheus/PrometheusUtil.java b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/prometheus/PrometheusUtil.java index 973e1adb96d..d7436ccf404 100644 --- a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/prometheus/PrometheusUtil.java +++ b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/metric/model/prometheus/PrometheusUtil.java @@ -13,9 +13,6 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; - /** * @author yj-jtakagi * @author gjoranv @@ -62,7 +59,7 @@ public class PrometheusUtil { var statusMetricName = serviceName + "_status"; // MetricsPacket status 0 means OK, but it's the opposite in Prometheus. var statusMetricValue = (firstPacket.statusCode == 0) ? 1 : 0; - var sampleList = singletonList(new Sample(statusMetricName, emptyList(), emptyList(), + var sampleList = List.of(new Sample(statusMetricName, List.of(), List.of(), statusMetricValue, firstPacket.timestamp * 1000)); metricFamilySamples.add(new MetricFamilySamples(statusMetricName, Collector.Type.UNKNOWN, "status of service", sampleList)); } diff --git a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/service/VespaService.java b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/service/VespaService.java index a83a28ff9c6..573292a6592 100644 --- a/metrics-proxy/src/main/java/ai/vespa/metricsproxy/service/VespaService.java +++ b/metrics-proxy/src/main/java/ai/vespa/metricsproxy/service/VespaService.java @@ -7,7 +7,6 @@ import ai.vespa.metricsproxy.metric.Metrics; import ai.vespa.metricsproxy.metric.model.DimensionId; import ai.vespa.metricsproxy.metric.model.ServiceId; -import java.util.Collections; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -20,7 +19,7 @@ import java.util.concurrent.atomic.AtomicReference; */ public class VespaService implements Comparable<VespaService> { - private static final Map<DimensionId, String> EMPTY_DIMENSIONS = Collections.emptyMap(); + private static final Map<DimensionId, String> EMPTY_DIMENSIONS = Map.of(); private static final String DEFAULT_MONITORING_PREFIX = "vespa"; public static final String SEPARATOR = "."; diff --git a/metrics/src/test/java/ai/vespa/metrics/MetricSetTest.java b/metrics/src/test/java/ai/vespa/metrics/MetricSetTest.java index db6f5457b5b..962d3c1f1d6 100644 --- a/metrics/src/test/java/ai/vespa/metrics/MetricSetTest.java +++ b/metrics/src/test/java/ai/vespa/metrics/MetricSetTest.java @@ -10,7 +10,6 @@ import java.util.EnumSet; import java.util.List; import java.util.Map; -import static java.util.Collections.emptyList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -23,7 +22,7 @@ public class MetricSetTest { void metrics_from_children_are_added() { MetricSet child1 = new MetricSet("child1", List.of(new Metric("child1_metric"))); MetricSet child2 = new MetricSet("child2", List.of(new Metric("child2_metric"))); - MetricSet parent = new MetricSet("parent", emptyList(), List.of(child1, child2)); + MetricSet parent = new MetricSet("parent", List.of(), List.of(child1, child2)); Map<String, Metric> parentMetrics = parent.getMetrics(); assertEquals(2, parentMetrics.size()); @@ -34,7 +33,7 @@ public class MetricSetTest { @Test void adding_the_same_child_set_twice_has_no_effect() { MetricSet child = new MetricSet("child", List.of(new Metric("child_metric"))); - MetricSet parent = new MetricSet("parent", emptyList(), List.of(child, child)); + MetricSet parent = new MetricSet("parent", List.of(), List.of(child, child)); Map<String, Metric> parentMetrics = parent.getMetrics(); assertEquals(1, parentMetrics.size()); diff --git a/metrics/src/vespa/metrics/metrictimer.cpp b/metrics/src/vespa/metrics/metrictimer.cpp index 84d4844104d..a3b0f215d58 100644 --- a/metrics/src/vespa/metrics/metrictimer.cpp +++ b/metrics/src/vespa/metrics/metrictimer.cpp @@ -3,13 +3,18 @@ namespace metrics { -MetricTimer::MetricTimer() +MetricTimer::MetricTimer() noexcept + : _startTime(std::chrono::steady_clock::now()) { // Amusingly enough, steady_clock was not actually steady by default on // GCC < 4.8.1, so add a bit of compile-time paranoia just to make sure. static_assert(std::chrono::steady_clock::is_steady, "Old/broken STL implementation; steady_clock not steady"); - _startTime = std::chrono::steady_clock::now(); +} + +MetricTimer::MetricTimer(std::chrono::steady_clock::time_point start_time) noexcept + : _startTime(start_time) +{ } } // metrics diff --git a/metrics/src/vespa/metrics/metrictimer.h b/metrics/src/vespa/metrics/metrictimer.h index 8a338432362..133cd819489 100644 --- a/metrics/src/vespa/metrics/metrictimer.h +++ b/metrics/src/vespa/metrics/metrictimer.h @@ -15,7 +15,19 @@ namespace metrics { class MetricTimer { public: - MetricTimer(); + // Start time point set by system steady clock + MetricTimer() noexcept; + // Start time point explicitly given + explicit MetricTimer(std::chrono::steady_clock::time_point start_time) noexcept; + + template<typename AvgVal, typename TotVal, bool SumOnAdd> + AvgVal stop(std::chrono::steady_clock::time_point now, ValueMetric<AvgVal, TotVal, SumOnAdd>& metric) const { + const auto delta = now - _startTime; + using ToDuration = std::chrono::duration<AvgVal, std::milli>; + const auto deltaMs(std::chrono::duration_cast<ToDuration>(delta).count()); + metric.addValue(deltaMs); + return deltaMs; + } /** * Adds ms passed since this timer was constructed to given value metric. @@ -26,11 +38,11 @@ public: */ template<typename AvgVal, typename TotVal, bool SumOnAdd> AvgVal stop(ValueMetric<AvgVal, TotVal, SumOnAdd>& metric) const { - const auto delta = std::chrono::steady_clock::now() - _startTime; - using ToDuration = std::chrono::duration<AvgVal, std::milli>; - const auto deltaMs(std::chrono::duration_cast<ToDuration>(delta).count()); - metric.addValue(deltaMs); - return deltaMs; + return stop(std::chrono::steady_clock::now(), metric); + } + + [[nodiscard]] std::chrono::steady_clock::time_point start_time() const noexcept { + return _startTime; } private: diff --git a/model-evaluation/src/main/java/ai/vespa/models/evaluation/RankProfilesConfigImporter.java b/model-evaluation/src/main/java/ai/vespa/models/evaluation/RankProfilesConfigImporter.java index 0e2a27952ef..e396020ad7a 100644 --- a/model-evaluation/src/main/java/ai/vespa/models/evaluation/RankProfilesConfigImporter.java +++ b/model-evaluation/src/main/java/ai/vespa/models/evaluation/RankProfilesConfigImporter.java @@ -27,7 +27,6 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -104,7 +103,7 @@ public class RankProfilesConfigImporter { if (externalReference.isPresent()) { RankingExpression expression = largeExpressions.get(property.value()); ExpressionFunction function = new ExpressionFunction(externalReference.get().functionName(), - Collections.emptyList(), + List.of(), expression); if (externalReference.get().isFree()) // make available in model under configured name @@ -115,7 +114,7 @@ public class RankProfilesConfigImporter { else if (reference.isPresent()) { RankingExpression expression = new RankingExpression(reference.get().functionName(), property.value()); ExpressionFunction function = new ExpressionFunction(reference.get().functionName(), - Collections.emptyList(), + List.of(), expression); if (reference.get().isFree()) // make available in model under configured name diff --git a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/configmodelview/ImportedMlModels.java b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/configmodelview/ImportedMlModels.java index c97e4781889..9639d9598a8 100644 --- a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/configmodelview/ImportedMlModels.java +++ b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/configmodelview/ImportedMlModels.java @@ -7,7 +7,6 @@ import com.yahoo.yolean.Exceptions; import java.io.File; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; @@ -34,7 +33,7 @@ public class ImportedMlModels { /** Create a null imported models */ public ImportedMlModels() { - importedModels = Collections.emptyMap(); + importedModels = Map.of(); } public ImportedMlModels(File modelsDirectory, ExecutorService executor, Collection<MlModelImporter> importers) { @@ -53,7 +52,7 @@ public class ImportedMlModels { skippedModels.put(name, Exceptions.toMessageString(e)); } }); - importedModels = Collections.unmodifiableMap(models); + importedModels = Map.copyOf(models); } /** diff --git a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Argument.java b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Argument.java index e985b6d2956..dbd17d96d4f 100644 --- a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Argument.java +++ b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Argument.java @@ -8,7 +8,6 @@ import com.yahoo.tensor.evaluation.VariableTensor; import com.yahoo.tensor.functions.Rename; import com.yahoo.tensor.functions.TensorFunction; -import java.util.Collections; import java.util.List; public class Argument extends IntermediateOperation { @@ -16,7 +15,7 @@ public class Argument extends IntermediateOperation { private OrderedTensorType standardNamingType; // using standard naming convention: d0, d1, ... public Argument(String modelName, String nodeName, OrderedTensorType type) { - super(modelName, nodeName, Collections.emptyList()); + super(modelName, nodeName, List.of()); this.type = type.rename(vespaName() + "_"); standardNamingType = OrderedTensorType.standardType(type); } diff --git a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Constant.java b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Constant.java index 91c46d1232e..1d430611c49 100644 --- a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Constant.java +++ b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Constant.java @@ -7,14 +7,13 @@ import com.yahoo.searchlib.rankingexpression.Reference; import com.yahoo.searchlib.rankingexpression.evaluation.Value; import com.yahoo.tensor.functions.TensorFunction; -import java.util.Collections; import java.util.List; import java.util.Optional; public class Constant extends IntermediateOperation { public Constant(String modelName, String nodeName, OrderedTensorType type) { - super(modelName, nodeName, Collections.emptyList()); + super(modelName, nodeName, List.of()); this.type = type.rename(vespaName() + "_"); } diff --git a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/IntermediateOperation.java b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/IntermediateOperation.java index 52de27891cf..d9f4a4b7f4c 100644 --- a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/IntermediateOperation.java +++ b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/IntermediateOperation.java @@ -53,7 +53,7 @@ public abstract class IntermediateOperation { private final List<String> importWarnings = new ArrayList<>(); private Value constantValue = null; - private List<IntermediateOperation> controlInputs = Collections.emptyList(); + private List<IntermediateOperation> controlInputs = List.of(); protected Function<OrderedTensorType, Value> constantValueFunction = null; @@ -259,7 +259,7 @@ public abstract class IntermediateOperation { if (result == DoubleValue.NaN) { if (constantValue != null) { result = constantValue; - } else if (inputs.size() == 0) { + } else if (inputs.isEmpty()) { if (getConstantValue().isEmpty()) { throw new IllegalArgumentException("Error in evaluating constant for " + name); } @@ -278,7 +278,7 @@ public abstract class IntermediateOperation { /** Insert an operation between an input and this one */ public void insert(IntermediateOperation operationToInsert, int inputNumber) { - if ( operationToInsert.inputs.size() > 0 ) { + if (!operationToInsert.inputs.isEmpty()) { throw new IllegalArgumentException("Operation to insert to '" + name + "' has " + "existing inputs which is not supported."); } @@ -336,7 +336,7 @@ public abstract class IntermediateOperation { public abstract IntermediateOperation withInputs(List<IntermediateOperation> inputs); String asString(Optional<OrderedTensorType> type) { - return type.map(t -> t.toString()).orElse("(unknown)"); + return type.map(OrderedTensorType::toString).orElse("(unknown)"); } /** @@ -373,7 +373,7 @@ public abstract class IntermediateOperation { public String toFullString() { return "\t" + type + ":\t" + operationName() + "(" + - inputs().stream().map(input -> input.toFullString()).collect(Collectors.joining(", ")) + + inputs().stream().map(IntermediateOperation::toFullString).collect(Collectors.joining(", ")) + ")"; } diff --git a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/NoOp.java b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/NoOp.java index ba056d362ac..fa115d8af97 100644 --- a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/NoOp.java +++ b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/NoOp.java @@ -5,13 +5,12 @@ import ai.vespa.rankingexpression.importer.OrderedTensorType; import com.yahoo.searchlib.rankingexpression.Reference; import com.yahoo.tensor.functions.TensorFunction; -import java.util.Collections; import java.util.List; public class NoOp extends IntermediateOperation { public NoOp(String modelName, String nodeName, List<IntermediateOperation> inputs) { - super(modelName, nodeName, Collections.emptyList()); // don't propagate inputs + super(modelName, nodeName, List.of()); // don't propagate inputs } @Override diff --git a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/OnnxConstant.java b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/OnnxConstant.java index dff548cf319..2e48d65fce2 100644 --- a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/OnnxConstant.java +++ b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/OnnxConstant.java @@ -9,7 +9,6 @@ import com.yahoo.searchlib.rankingexpression.evaluation.Value; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.functions.TensorFunction; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -31,7 +30,7 @@ public class OnnxConstant extends IntermediateOperation { if (value instanceof TensorValue) { type = OrderedTensorType.fromSpec(value.type().toString()).rename(vespaName() + "_"); } else { - type = OrderedTensorType.fromDimensionList(TensorType.Value.DOUBLE, Collections.emptyList()); + type = OrderedTensorType.fromDimensionList(TensorType.Value.DOUBLE, List.of()); } return type; } diff --git a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Rename.java b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Rename.java index 5a7bbc95889..068c06acd8c 100644 --- a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Rename.java +++ b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Rename.java @@ -7,7 +7,6 @@ import com.yahoo.searchlib.rankingexpression.Reference; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.functions.TensorFunction; -import java.util.Collections; import java.util.List; /** @@ -20,7 +19,7 @@ public class Rename extends IntermediateOperation { private String from, to; public Rename(String modelName, String from, String to, IntermediateOperation input) { - super(modelName, "rename", input != null ? List.of(input) : Collections.emptyList()); + super(modelName, "rename", input != null ? List.of(input) : List.of()); this.from = from; this.to = to; } diff --git a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Softmax.java b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Softmax.java index c4d728e9661..6d0a6c3b04b 100644 --- a/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Softmax.java +++ b/model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/Softmax.java @@ -10,7 +10,6 @@ import com.yahoo.tensor.functions.ScalarFunctions; import com.yahoo.tensor.functions.TensorFunction; import java.util.ArrayList; -import java.util.Collections; import java.util.List; /** @@ -77,7 +76,7 @@ public class Softmax extends IntermediateOperation { private class SoftmaxPartialOperation extends IntermediateOperation { private SoftmaxPartialOperation(String modelName, String nodeName, List<IntermediateOperation> inputs) { - super(modelName, nodeName + "_partial" , inputs != null ? inputs : Collections.emptyList()); + super(modelName, nodeName + "_partial" , inputs != null ? inputs : List.of()); } @Override diff --git a/model-integration/src/test/java/ai/vespa/llm/clients/ConfigurableLanguageModelTest.java b/model-integration/src/test/java/ai/vespa/llm/clients/ConfigurableLanguageModelTest.java index a9f4c3dfac5..35d5cfd3855 100644 --- a/model-integration/src/test/java/ai/vespa/llm/clients/ConfigurableLanguageModelTest.java +++ b/model-integration/src/test/java/ai/vespa/llm/clients/ConfigurableLanguageModelTest.java @@ -11,7 +11,6 @@ import com.yahoo.container.jdisc.secretstore.SecretStore; import org.junit.jupiter.api.Test; import java.util.Arrays; -import java.util.Collections; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -85,7 +84,7 @@ public class ConfigurableLanguageModelTest { } private static InferenceParameters inferenceParams() { - return new InferenceParameters(s -> lookupParameter(s, Collections.emptyMap())); + return new InferenceParameters(s -> lookupParameter(s, Map.of())); } private static InferenceParameters inferenceParams(Map<String, String> params) { @@ -93,7 +92,7 @@ public class ConfigurableLanguageModelTest { } private static InferenceParameters inferenceParamsWithDefaultKey() { - return new InferenceParameters(MockLLMClient.ACCEPTED_API_KEY, s -> lookupParameter(s, Collections.emptyMap())); + return new InferenceParameters(MockLLMClient.ACCEPTED_API_KEY, s -> lookupParameter(s, Map.of())); } private LlmClientConfig modelParams(String apiKeySecretName, String endpoint) { diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/QuestMetricsDb.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/QuestMetricsDb.java index e9230d2c91a..057430b381f 100644 --- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/QuestMetricsDb.java +++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/autoscale/QuestMetricsDb.java @@ -296,6 +296,11 @@ public class QuestMetricsDb extends AbstractComponent implements MetricsDb { } } + private static String getStr(Record record, int col) { + CharSequence charSequence = record.getStrA(col); + return charSequence != null ? charSequence.toString() : ""; + } + private ListMap<String, NodeMetricSnapshot> getNodeSnapshots(Instant startTime, Set<String> hostnames, SqlExecutionContext context) throws SqlException { @@ -312,7 +317,7 @@ public class QuestMetricsDb extends AbstractComponent implements MetricsDb { try (RecordCursor cursor = factory.getCursor(context)) { Record record = cursor.getRecord(); while (cursor.hasNext()) { - String hostname = record.getStr(0).toString(); + String hostname = getStr(record, 0); if (hostnames.isEmpty() || hostnames.contains(hostname)) { snapshots.put(hostname, new NodeMetricSnapshot(Instant.ofEpochMilli(record.getTimestamp(1) / 1000), @@ -345,9 +350,9 @@ public class QuestMetricsDb extends AbstractComponent implements MetricsDb { try (RecordCursor cursor = factory.getCursor(context)) { Record record = cursor.getRecord(); while (cursor.hasNext()) { - String applicationIdString = record.getStr(0).toString(); + String applicationIdString = getStr(record, 0); if ( ! application.serializedForm().equals(applicationIdString)) continue; - String clusterId = record.getStr(1).toString(); + String clusterId = getStr(record, 1); if (cluster.value().equals(clusterId)) { snapshots.add(new ClusterMetricSnapshot(Instant.ofEpochMilli(record.getTimestamp(2) / 1000), record.getFloat(3), @@ -475,7 +480,7 @@ public class QuestMetricsDb extends AbstractComponent implements MetricsDb { try (RecordCursor cursor = factory.getCursor(context)) { Record record = cursor.getRecord(); while (cursor.hasNext()) { - columns.add(record.getStr(0).toString()); + columns.add(getStr(record, 0)); } } } diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/Reports.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/Reports.java index 8e82307deb1..e10a4e82a0c 100644 --- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/Reports.java +++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/node/Reports.java @@ -6,7 +6,6 @@ import com.yahoo.slime.Inspector; import com.yahoo.slime.ObjectTraverser; import com.yahoo.slime.Type; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; @@ -20,8 +19,8 @@ public class Reports { private final Map<String, Report> reports; - public Reports() { this(Collections.emptyMap()); } - private Reports(Map<String, Report> reports) { this.reports = Collections.unmodifiableMap(reports); } + public Reports() { this(Map.of()); } + private Reports(Map<String, Report> reports) { this.reports = Map.copyOf(reports); } public boolean isEmpty() { return reports.isEmpty(); } public Optional<Report> getReport(String id) { return Optional.ofNullable(reports.get(id)); } diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/persistence/ApplicationSerializer.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/persistence/ApplicationSerializer.java index 1315207efb8..0c3a1df0f27 100644 --- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/persistence/ApplicationSerializer.java +++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/persistence/ApplicationSerializer.java @@ -56,7 +56,6 @@ public class ApplicationSerializer { private static final String maxResourcesKey = "max"; private static final String groupSizeKey = "groupSize"; private static final String requiredKey = "required"; - private static final String suggestedKey = "suggested"; private static final String suggestionsKey = "suggestionsKey"; private static final String clusterInfoKey = "clusterInfo"; private static final String bcpDeadlineKey = "bcpDeadline"; @@ -141,8 +140,6 @@ public class ApplicationSerializer { toSlime(cluster.maxResources(), clusterObject.setObject(maxResourcesKey)); toSlime(cluster.groupSize(), clusterObject.setObject(groupSizeKey)); clusterObject.setBool(requiredKey, cluster.required()); - // TODO(olaa): Remove 'suggested' once all configservers have stopped reading entry - toSlime(Autoscaling.empty(), clusterObject.setObject(suggestedKey)); toSlime(cluster.suggestions(), clusterObject.setArray(suggestionsKey)); toSlime(cluster.target(), clusterObject.setObject(targetKey)); if (! cluster.clusterInfo().isEmpty()) diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/persistence/CuratorDb.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/persistence/CuratorDb.java index d511570881b..d2edaaf3737 100644 --- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/persistence/CuratorDb.java +++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/persistence/CuratorDb.java @@ -157,7 +157,7 @@ public class CuratorDb { * @return the nodes in their persisted state */ public List<Node> writeTo(List<Node> nodes, Agent agent, Optional<String> reason) { - if (nodes.isEmpty()) return Collections.emptyList(); + if (nodes.isEmpty()) return List.of(); List<Node> writtenNodes = new ArrayList<>(nodes.size()); @@ -191,7 +191,7 @@ public class CuratorDb { } public Node writeTo(Node.State toState, Node node, Agent agent, Optional<String> reason) { - return writeTo(toState, Collections.singletonList(node), agent, reason).get(0); + return writeTo(toState, List.of(node), agent, reason).get(0); } /** diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/HostCapacityResponse.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/HostCapacityResponse.java index 9f7c795cf48..9fbc096667e 100644 --- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/HostCapacityResponse.java +++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/HostCapacityResponse.java @@ -12,7 +12,6 @@ import com.yahoo.vespa.hosted.provision.maintenance.CapacityChecker; import java.io.IOException; import java.io.OutputStream; -import java.util.Arrays; import java.util.List; import java.util.Optional; @@ -46,7 +45,7 @@ public class HostCapacityResponse extends HttpResponse { } private List<Node> parseHostList(String hosts) { - List<String> hostNames = Arrays.asList(hosts.split(",")); + List<String> hostNames = List.of(hosts.split(",")); try { return capacityChecker.nodesFromHostnames(hostNames); } catch (IllegalArgumentException e) { diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesResponse.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesResponse.java index c518087f325..cfe4886c903 100644 --- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesResponse.java +++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/restapi/NodesResponse.java @@ -27,7 +27,6 @@ import com.yahoo.vespa.orchestrator.status.HostInfo; import com.yahoo.vespa.orchestrator.status.HostStatus; import java.net.URI; -import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; @@ -66,7 +65,7 @@ class NodesResponse extends SlimeJsonResponse { this.wantedDockerTagFlag = PermanentFlags.WANTED_DOCKER_TAG.bindTo(nodeRepository.flagSource()); // Cannot use Set.of() because the nodeRepository account can also be the empty account (at least in tests). - var nonEnclaveAccounts = new HashSet<>(Arrays.asList(CloudAccount.empty, nodeRepository.zone().cloud().account())); + var nonEnclaveAccounts = new HashSet<>(List.of(CloudAccount.empty, nodeRepository.zone().cloud().account())); this.filter = NodesV2ApiHandler.toNodeFilter(request, nonEnclaveAccounts); Cursor root = slime.setObject(); diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/testutils/MockNameResolver.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/testutils/MockNameResolver.java index 5f0ac4fbcdb..166fcb8edc7 100644 --- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/testutils/MockNameResolver.java +++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/testutils/MockNameResolver.java @@ -9,6 +9,7 @@ import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -37,7 +38,7 @@ public class MockNameResolver implements NameResolver { Objects.requireNonNull(hostname, "hostname must be non-null"); Arrays.stream(ipAddress).forEach(ip -> Objects.requireNonNull(ip, "ipAddress must be non-null")); records.computeIfAbsent(hostname, (k) -> new HashSet<>()) - .addAll(Arrays.asList(ipAddress)); + .addAll(List.of(ipAddress)); return this; } diff --git a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/testutils/ServiceMonitorStub.java b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/testutils/ServiceMonitorStub.java index 5409061c441..700a16577af 100644 --- a/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/testutils/ServiceMonitorStub.java +++ b/node-repository/src/main/java/com/yahoo/vespa/hosted/provision/testutils/ServiceMonitorStub.java @@ -19,7 +19,6 @@ import com.yahoo.vespa.hosted.provision.NodeRepository; import com.yahoo.vespa.service.monitor.ServiceModel; import com.yahoo.vespa.service.monitor.ServiceMonitor; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -38,7 +37,7 @@ public class ServiceMonitorStub implements ServiceMonitor { @Inject @SuppressWarnings("unused") public ServiceMonitorStub(NodeRepository nodeRepository) { - this(Collections.emptyMap(), nodeRepository); + this(Map.of(), nodeRepository); } /** Create a service monitor where all nodes are initially up */ diff --git a/orchestrator-restapi/src/main/java/com/yahoo/vespa/orchestrator/restapi/wire/ApplicationReferenceList.java b/orchestrator-restapi/src/main/java/com/yahoo/vespa/orchestrator/restapi/wire/ApplicationReferenceList.java index bcbd0d2f3b8..b91271c1adf 100644 --- a/orchestrator-restapi/src/main/java/com/yahoo/vespa/orchestrator/restapi/wire/ApplicationReferenceList.java +++ b/orchestrator-restapi/src/main/java/com/yahoo/vespa/orchestrator/restapi/wire/ApplicationReferenceList.java @@ -5,7 +5,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.Collections; import java.util.List; /** @@ -17,5 +16,5 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) public class ApplicationReferenceList { @JsonProperty("applications") - public List<UrlReference> applicationList = Collections.emptyList(); + public List<UrlReference> applicationList = List.of(); } diff --git a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/ClusterApiImpl.java b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/ClusterApiImpl.java index d2638345f29..bf0de161f73 100644 --- a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/ClusterApiImpl.java +++ b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/ClusterApiImpl.java @@ -18,7 +18,6 @@ import com.yahoo.vespa.orchestrator.status.HostStatus; import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Optional; @@ -83,8 +82,8 @@ class ClusterApiImpl implements ClusterApi { Collectors.groupingBy( instance -> nodeGroup.contains(instance.hostName()), Collectors.toSet())); - servicesInGroup = serviceInstancesByLocality.getOrDefault(true, Collections.emptySet()); - servicesNotInGroup = serviceInstancesByLocality.getOrDefault(false, Collections.emptySet()); + servicesInGroup = serviceInstancesByLocality.getOrDefault(true, Set.of()); + servicesNotInGroup = serviceInstancesByLocality.getOrDefault(false, Set.of()); int serviceInstances = serviceCluster.serviceInstances().size(); if (clusterParams.size().isPresent() && serviceInstances < clusterParams.size().getAsInt()) { diff --git a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/NodeGroup.java b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/NodeGroup.java index c61d5cab472..1b1c64c9d9a 100644 --- a/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/NodeGroup.java +++ b/orchestrator/src/main/java/com/yahoo/vespa/orchestrator/model/NodeGroup.java @@ -5,7 +5,6 @@ import com.yahoo.vespa.applicationmodel.ApplicationInstance; import com.yahoo.vespa.applicationmodel.ApplicationInstanceReference; import com.yahoo.vespa.applicationmodel.HostName; -import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Objects; @@ -21,7 +20,7 @@ public class NodeGroup { public NodeGroup(ApplicationInstance application, HostName... hostNames) { this.application = application; - this.hostNames.addAll(Arrays.asList(hostNames)); + this.hostNames.addAll(List.of(hostNames)); } public void addNode(HostName hostName) { diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorImplTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorImplTest.java index 354799507ab..fc9715dce5c 100644 --- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorImplTest.java +++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/OrchestratorImplTest.java @@ -42,7 +42,6 @@ import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -277,7 +276,7 @@ public class OrchestratorImplTest { orchestrator.suspendAll( new HostName("parentHostname"), - Arrays.asList( + List.of( DummyServiceMonitor.TEST1_HOST_NAME, DummyServiceMonitor.TEST3_HOST_NAME, DummyServiceMonitor.TEST6_HOST_NAME)); @@ -317,7 +316,7 @@ public class OrchestratorImplTest { try { orchestrator.suspendAll( new HostName("parentHostname"), - Arrays.asList( + List.of( DummyServiceMonitor.TEST1_HOST_NAME, DummyServiceMonitor.TEST3_HOST_NAME, DummyServiceMonitor.TEST6_HOST_NAME)); diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ApplicationApiImplTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ApplicationApiImplTest.java index c0d6e01104a..8618c6ada90 100644 --- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ApplicationApiImplTest.java +++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ApplicationApiImplTest.java @@ -33,11 +33,11 @@ public class ApplicationApiImplTest { HostName hostName4 = new HostName("host4"); ApplicationInstance applicationInstance = - modelUtils.createApplicationInstance(Arrays.asList( + modelUtils.createApplicationInstance(List.of( modelUtils.createServiceCluster( "cluster-3", new ServiceType("service-type-3"), - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-1", hostName1, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-2", hostName2, ServiceStatus.UP) ) @@ -45,7 +45,7 @@ public class ApplicationApiImplTest { modelUtils.createServiceCluster( "cluster-1", new ServiceType("service-type-1"), - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-3", hostName1, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-4", hostName3, ServiceStatus.UP) ) @@ -53,7 +53,7 @@ public class ApplicationApiImplTest { modelUtils.createServiceCluster( "cluster-2", new ServiceType("service-type-2"), - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-5", hostName1, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-6", hostName2, ServiceStatus.UP) ) @@ -71,7 +71,7 @@ public class ApplicationApiImplTest { try (scopedApi) { // Note: we require the clusters to be in order. List<ClusterApi> clusterApis = scopedApi.applicationApi().getClusters(); - String clusterInfos = clusterApis.stream().map(clusterApi -> clusterApi.clusterInfo()).collect(Collectors.joining(",")); + String clusterInfos = clusterApis.stream().map(ClusterApi::clusterInfo).collect(Collectors.joining(",")); String expectedClusterInfos = Arrays.stream(expectedClusterNumbers) .map(number -> "{ clusterId=cluster-" + number + ", serviceType=service-type-" + number + " }") @@ -92,11 +92,11 @@ public class ApplicationApiImplTest { HostName hostName7 = new HostName("host7"); ApplicationInstance applicationInstance = - modelUtils.createApplicationInstance(Arrays.asList( + modelUtils.createApplicationInstance(List.of( modelUtils.createServiceCluster( "cluster-3", ServiceType.STORAGE, - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-30", hostName1, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-31", hostName2, ServiceStatus.UP) ) @@ -104,7 +104,7 @@ public class ApplicationApiImplTest { modelUtils.createServiceCluster( "cluster-1", ServiceType.STORAGE, - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-10", hostName3, ServiceStatus.DOWN), modelUtils.createServiceInstance("config-id-11", hostName4, ServiceStatus.UP) ) @@ -112,7 +112,7 @@ public class ApplicationApiImplTest { modelUtils.createServiceCluster( "cluster-4", new ServiceType("service-type-4"), - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-40", hostName1, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-41", hostName2, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-42", hostName3, ServiceStatus.UP), @@ -122,7 +122,7 @@ public class ApplicationApiImplTest { modelUtils.createServiceCluster( "cluster-2", ServiceType.STORAGE, - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-20", hostName6, ServiceStatus.DOWN), modelUtils.createServiceInstance("config-id-21", hostName7, ServiceStatus.UP) ) @@ -154,9 +154,9 @@ public class ApplicationApiImplTest { HostName... expectedHostNames) { try (scopedApi) { List<HostName> upStorageNodes = scopedApi.applicationApi().getNoRemarksStorageNodesInGroupInClusterOrder().stream() - .map(storageNode -> storageNode.hostName()) + .map(StorageNode::hostName) .toList(); - assertEquals(Arrays.asList(expectedHostNames), upStorageNodes); + assertEquals(List.of(expectedHostNames), upStorageNodes); } } @@ -191,7 +191,7 @@ public class ApplicationApiImplTest { List<HostName> actualStorageNodes = scopedApi.applicationApi() .getNoRemarksStorageNodesInGroupInClusterOrder() .stream() - .map(storageNode -> storageNode.hostName()) + .map(StorageNode::hostName) .toList(); assertEquals(upStorageNodes, actualStorageNodes); } @@ -204,11 +204,11 @@ public class ApplicationApiImplTest { HostName hostName3 = new HostName("host3"); ApplicationInstance applicationInstance = - modelUtils.createApplicationInstance(Arrays.asList( + modelUtils.createApplicationInstance(List.of( modelUtils.createServiceCluster( "cluster-1", new ServiceType("service-type-1"), - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-10", hostName1, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-11", hostName2, ServiceStatus.UP) ) @@ -216,7 +216,7 @@ public class ApplicationApiImplTest { modelUtils.createServiceCluster( "cluster-2", new ServiceType("service-type-2"), - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-20", hostName1, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-21", hostName3, ServiceStatus.UP) ) @@ -233,11 +233,11 @@ public class ApplicationApiImplTest { List.of()); verifyNodesInGroupWithoutRemarks( modelUtils.createScopedApplicationApi(applicationInstance, hostName1, hostName2), - Arrays.asList(hostName1, hostName2), + List.of(hostName1, hostName2), List.of()); verifyNodesInGroupWithoutRemarks( modelUtils.createScopedApplicationApi(applicationInstance, hostName1, hostName2, hostName3), - Arrays.asList(hostName1, hostName2), + List.of(hostName1, hostName2), List.of(hostName3)); verifyNodesInGroupWithoutRemarks( modelUtils.createScopedApplicationApi(applicationInstance, hostName3), @@ -268,11 +268,11 @@ public class ApplicationApiImplTest { HostName allowedToBeDownHost7 = new HostName("host7"); ApplicationInstance applicationInstance = - modelUtils.createApplicationInstance(Arrays.asList( + modelUtils.createApplicationInstance(List.of( modelUtils.createServiceCluster( "cluster-4", ServiceType.STORAGE, - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-40", allowedToBeDownHost1, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-41", noRemarksHost2, ServiceStatus.DOWN) ) @@ -280,7 +280,7 @@ public class ApplicationApiImplTest { modelUtils.createServiceCluster( "cluster-1", new ServiceType("service-type-1"), - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-10", allowedToBeDownHost1, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-11", allowedToBeDownHost3, ServiceStatus.UP) ) @@ -288,7 +288,7 @@ public class ApplicationApiImplTest { modelUtils.createServiceCluster( "cluster-3", ServiceType.STORAGE, - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-30", allowedToBeDownHost4, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-31", noRemarksHost5, ServiceStatus.UP) ) @@ -296,7 +296,7 @@ public class ApplicationApiImplTest { modelUtils.createServiceCluster( "cluster-2", ServiceType.STORAGE, - Arrays.asList( + List.of( modelUtils.createServiceInstance("config-id-20", noRemarksHost6, ServiceStatus.UP), modelUtils.createServiceInstance("config-id-21", allowedToBeDownHost7, ServiceStatus.UP) ) @@ -343,9 +343,9 @@ public class ApplicationApiImplTest { .applicationApi() .getSuspendedStorageNodesInGroupInReverseClusterOrder() .stream() - .map(storageNode -> storageNode.hostName()) + .map(StorageNode::hostName) .toList(); - assertEquals(Arrays.asList(hostNames), actualStorageNodes); + assertEquals(List.of(hostNames), actualStorageNodes); } } } diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ClusterApiImplTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ClusterApiImplTest.java index 7dccaad1b1c..9f8f8a9dd44 100644 --- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ClusterApiImplTest.java +++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/ClusterApiImplTest.java @@ -27,8 +27,6 @@ import org.junit.Test; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Optional; @@ -65,7 +63,7 @@ public class ClusterApiImplTest { ServiceCluster serviceCluster = modelUtils.createServiceCluster( "cluster", new ServiceType("service-type"), - Arrays.asList( + List.of( modelUtils.createServiceInstance("service-1", hostName1, ServiceStatus.UP), modelUtils.createServiceInstance("service-2", hostName2, ServiceStatus.DOWN), modelUtils.createServiceInstance("service-3", hostName3, ServiceStatus.UP), @@ -73,7 +71,7 @@ public class ClusterApiImplTest { modelUtils.createServiceInstance("service-5", hostName5, ServiceStatus.UP) ) ); - modelUtils.createApplicationInstance(Collections.singletonList(serviceCluster)); + modelUtils.createApplicationInstance(List.of(serviceCluster)); modelUtils.createNode(hostName1, HostStatus.NO_REMARKS); modelUtils.createNode(hostName2, HostStatus.NO_REMARKS); @@ -269,7 +267,7 @@ public class ClusterApiImplTest { ServiceCluster serviceCluster = modelUtils.createServiceCluster( "cluster", new ServiceType("service-type"), - Arrays.asList( + List.of( modelUtils.createServiceInstance("service-1", hostName1, ServiceStatus.UP), service2, modelUtils.createServiceInstance("service-3", hostName3, ServiceStatus.UP), @@ -278,7 +276,7 @@ public class ClusterApiImplTest { service6 ) ); - modelUtils.createApplicationInstance(Collections.singletonList(serviceCluster)); + modelUtils.createApplicationInstance(List.of(serviceCluster)); modelUtils.createNode(hostName1, HostStatus.NO_REMARKS); modelUtils.createNode(hostName2, HostStatus.NO_REMARKS); @@ -337,7 +335,7 @@ public class ClusterApiImplTest { ServiceCluster serviceCluster = modelUtils.createServiceCluster( "cluster", ServiceType.STORAGE, - Arrays.asList( + List.of( modelUtils.createServiceInstance("storage-1", hostName1, ServiceStatus.UP), modelUtils.createServiceInstance("storage-2", hostName2, ServiceStatus.DOWN) ) diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/NodeGroupTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/NodeGroupTest.java index 373d512f811..b2802ad9924 100644 --- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/NodeGroupTest.java +++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/NodeGroupTest.java @@ -7,8 +7,8 @@ import com.yahoo.vespa.applicationmodel.HostName; import com.yahoo.vespa.applicationmodel.TenantId; import org.junit.Test; -import java.util.Arrays; import java.util.HashSet; +import java.util.List; import static org.junit.Assert.assertEquals; @@ -27,7 +27,7 @@ public class NodeGroupTest { nodeGroup.addNode(hostName2); // hostnames are sorted (for no good reason other than testability due to stability, readability) - assertEquals(Arrays.asList(hostName1, hostName2, hostName3), nodeGroup.getHostNames()); + assertEquals(List.of(hostName1, hostName2, hostName3), nodeGroup.getHostNames()); assertEquals("host1,host2,host3", nodeGroup.toCommaSeparatedString()); } } diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/VespaModelUtilTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/VespaModelUtilTest.java index 3b1bd7af525..33ec7a5c43f 100644 --- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/VespaModelUtilTest.java +++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/model/VespaModelUtilTest.java @@ -14,7 +14,6 @@ import com.yahoo.vespa.applicationmodel.TenantId; import com.yahoo.vespa.orchestrator.TestUtil; import org.junit.Test; -import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -172,7 +171,7 @@ public class VespaModelUtilTest { @Test public void testGettingClusterControllerInstances() { List<HostName> controllers = VespaModelUtil.getClusterControllerInstancesInOrder(application, CONTENT_CLUSTER_ID); - List<HostName> expectedControllers = Arrays.asList(controller0.hostName(), controller1.hostName()); + List<HostName> expectedControllers = List.of(controller0.hostName(), controller1.hostName()); assertEquals(expectedControllers, controllers); } diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicyTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicyTest.java index 14d5909522a..77fdbe4067d 100644 --- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicyTest.java +++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/policy/HostedVespaPolicyTest.java @@ -20,7 +20,6 @@ import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; -import java.util.Arrays; import java.util.List; import static org.mockito.ArgumentMatchers.any; @@ -56,7 +55,7 @@ public class HostedVespaPolicyTest { ClusterApi clusterApi1 = mock(ClusterApi.class); ClusterApi clusterApi2 = mock(ClusterApi.class); ClusterApi clusterApi3 = mock(ClusterApi.class); - List<ClusterApi> clusterApis = Arrays.asList(clusterApi1, clusterApi2, clusterApi3); + List<ClusterApi> clusterApis = List.of(clusterApi1, clusterApi2, clusterApi3); when(applicationApi.getClusters()).thenReturn(clusterApis); StorageNode storageNode1 = mock(StorageNode.class); @@ -69,11 +68,11 @@ public class HostedVespaPolicyTest { HostName hostName3 = new HostName("storage-3"); when(storageNode1.hostName()).thenReturn(hostName3); - List<StorageNode> upStorageNodes = Arrays.asList(storageNode1, storageNode3); + List<StorageNode> upStorageNodes = List.of(storageNode1, storageNode3); when(applicationApi.getNoRemarksStorageNodesInGroupInClusterOrder()).thenReturn(upStorageNodes); // setHostState - List<HostName> noRemarksHostNames = Arrays.asList(hostName1, hostName2, hostName3); + List<HostName> noRemarksHostNames = List.of(hostName1, hostName2, hostName3); when(applicationApi.getNodesInGroupWithStatus(HostStatus.NO_REMARKS)).thenReturn(noRemarksHostNames); InOrder order = inOrder(applicationApi, clusterPolicy, storageNode1, storageNode3); @@ -108,7 +107,7 @@ public class HostedVespaPolicyTest { ClusterApi clusterApi1 = mock(ClusterApi.class); ClusterApi clusterApi2 = mock(ClusterApi.class); ClusterApi clusterApi3 = mock(ClusterApi.class); - List<ClusterApi> clusterApis = Arrays.asList(clusterApi1, clusterApi2, clusterApi3); + List<ClusterApi> clusterApis = List.of(clusterApi1, clusterApi2, clusterApi3); when(applicationApi.getClusters()).thenReturn(clusterApis); StorageNode storageNode1 = mock(StorageNode.class); @@ -121,10 +120,10 @@ public class HostedVespaPolicyTest { HostName hostName3 = new HostName("storage-3"); when(storageNode1.hostName()).thenReturn(hostName3); - List<StorageNode> upStorageNodes = Arrays.asList(storageNode1, storageNode3); + List<StorageNode> upStorageNodes = List.of(storageNode1, storageNode3); when(applicationApi.getStorageNodesInGroupInClusterOrder()).thenReturn(upStorageNodes); - List<HostName> noRemarksHostNames = Arrays.asList(hostName1, hostName2, hostName3); + List<HostName> noRemarksHostNames = List.of(hostName1, hostName2, hostName3); when(applicationApi.getNodesInGroupWith(any())).thenReturn(noRemarksHostNames); InOrder order = inOrder(applicationApi, clusterPolicy, storageNode1, storageNode3); @@ -161,7 +160,7 @@ public class HostedVespaPolicyTest { ClusterApi clusterApi1 = mock(ClusterApi.class); ClusterApi clusterApi2 = mock(ClusterApi.class); ClusterApi clusterApi3 = mock(ClusterApi.class); - List<ClusterApi> clusterApis = Arrays.asList(clusterApi1, clusterApi2, clusterApi3); + List<ClusterApi> clusterApis = List.of(clusterApi1, clusterApi2, clusterApi3); when(applicationApi.getClusters()).thenReturn(clusterApis); StorageNode storageNode1 = mock(StorageNode.class); @@ -174,10 +173,10 @@ public class HostedVespaPolicyTest { HostName hostName3 = new HostName("storage-3"); when(storageNode1.hostName()).thenReturn(hostName3); - List<StorageNode> upStorageNodes = Arrays.asList(storageNode1, storageNode3); + List<StorageNode> upStorageNodes = List.of(storageNode1, storageNode3); when(applicationApi.getStorageNodesInGroupInClusterOrder()).thenReturn(upStorageNodes); - List<HostName> noRemarksHostNames = Arrays.asList(hostName1, hostName2, hostName3); + List<HostName> noRemarksHostNames = List.of(hostName1, hostName2, hostName3); when(applicationApi.getNodesInGroupWith(any())).thenReturn(noRemarksHostNames); InOrder order = inOrder(applicationApi, clusterPolicy, storageNode1, storageNode3); diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/resources/HostRequestHandlerTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/resources/HostRequestHandlerTest.java index 6a2783949d8..53192b1d40e 100644 --- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/resources/HostRequestHandlerTest.java +++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/resources/HostRequestHandlerTest.java @@ -53,7 +53,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.time.Clock; import java.time.Instant; -import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -278,7 +278,7 @@ class HostRequestHandlerTest { ServiceCluster serviceCluster = new ServiceCluster( new ClusterId("clusterId"), new ServiceType("serviceType"), - Collections.singleton(serviceInstance)); + Set.of(serviceInstance)); serviceInstance.setServiceCluster(serviceCluster); Host host = new Host( @@ -287,7 +287,7 @@ class HostRequestHandlerTest { new ApplicationInstanceReference( new TenantId("tenantId"), new ApplicationInstanceId("applicationId")), - Collections.singletonList(serviceInstance)); + List.of(serviceInstance)); when(orchestrator.getHost(hostName)).thenReturn(host); HttpResponse httpResponse = executeRequest(testDriver, Method.GET, "/orchestrator/v1/hosts/hostname", null); @@ -314,13 +314,14 @@ class HostRequestHandlerTest { assertEquals(409, httpResponse.getStatus()); ByteArrayOutputStream out = new ByteArrayOutputStream(); httpResponse.render(out); - JsonTestHelper.assertJsonEquals("{\n" + - " \"hostname\" : \"hostname\",\n" + - " \"reason\" : {\n" + - " \"constraint\" : \"deadline\",\n" + - " \"message\" : \"resume failed: Timeout Message\"\n" + - " }\n" + - "}", + JsonTestHelper.assertJsonEquals(""" + { + "hostname" : "hostname", + "reason" : { + "constraint" : "deadline", + "message" : "resume failed: Timeout Message" + } + }""", out.toString()); } diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/resources/InstanceRequestHandlerTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/resources/InstanceRequestHandlerTest.java index 9e5464f3e3a..41bcbb125ee 100644 --- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/resources/InstanceRequestHandlerTest.java +++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/resources/InstanceRequestHandlerTest.java @@ -17,7 +17,6 @@ import com.yahoo.vespa.orchestrator.restapi.wire.SlobrokEntryResponse; import com.yahoo.vespa.service.manager.UnionMonitorManager; import com.yahoo.vespa.service.monitor.SlobrokApi; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.List; import static com.yahoo.jdisc.http.HttpRequest.Method.GET; @@ -34,7 +33,7 @@ class InstanceRequestHandlerTest { private static final String APPLICATION_INSTANCE_REFERENCE = "tenant:app:prod:us-west-1:instance"; private static final ApplicationId APPLICATION_ID = ApplicationId.from( "tenant", "app", "instance"); - private static final List<Mirror.Entry> ENTRIES = Arrays.asList( + private static final List<Mirror.Entry> ENTRIES = List.of( new Mirror.Entry("name1", "tcp/spec:1"), new Mirror.Entry("name2", "tcp/spec:2")); private static final ClusterId CLUSTER_ID = new ClusterId("cluster-id"); diff --git a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/status/ZkStatusServiceTest.java b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/status/ZkStatusServiceTest.java index e0929090a19..d45dc17e84c 100644 --- a/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/status/ZkStatusServiceTest.java +++ b/orchestrator/src/test/java/com/yahoo/vespa/orchestrator/status/ZkStatusServiceTest.java @@ -34,7 +34,6 @@ import org.mockito.junit.MockitoJUnitRunner; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; @@ -393,7 +392,7 @@ public class ZkStatusServiceTest { @SuppressWarnings("varargs") private static <T> List<T> shuffledList(T... values) { //new ArrayList necessary to avoid "write through" behaviour - List<T> list = new ArrayList<>(Arrays.asList(values)); + List<T> list = new ArrayList<>(List.of(values)); Collections.shuffle(list); return list; } diff --git a/persistence/src/vespa/persistence/spi/context.cpp b/persistence/src/vespa/persistence/spi/context.cpp index deed8d451bd..4cd016215d2 100644 --- a/persistence/src/vespa/persistence/spi/context.cpp +++ b/persistence/src/vespa/persistence/spi/context.cpp @@ -4,7 +4,7 @@ namespace storage::spi { -Context::Context(Priority pri, int maxTraceLevel) noexcept +Context::Context(Priority pri, uint32_t maxTraceLevel) noexcept : _priority(pri), _trace(maxTraceLevel), _readConsistency(ReadConsistency::STRONG) diff --git a/persistence/src/vespa/persistence/spi/context.h b/persistence/src/vespa/persistence/spi/context.h index 590acd1c549..2b35d5f3a8d 100644 --- a/persistence/src/vespa/persistence/spi/context.h +++ b/persistence/src/vespa/persistence/spi/context.h @@ -38,7 +38,7 @@ using Priority = uint16_t; // 0 - max pri, 255 - min pri // Define this type just because a ton of tests currently use it. struct Trace { - using TraceLevel = int; + using TraceLevel = uint32_t; }; class Context { @@ -48,10 +48,10 @@ class Context { public: Context(Context &&) noexcept = default; Context & operator = (Context &&) noexcept = default; - Context(Priority pri, int maxTraceLevel) noexcept; + Context(Priority pri, uint32_t maxTraceLevel) noexcept; ~Context(); - Priority getPriority() const noexcept { return _priority; } + [[nodiscard]] Priority getPriority() const noexcept { return _priority; } /** * A read operation might choose to relax its consistency requirements, @@ -65,16 +65,16 @@ public: void setReadConsistency(ReadConsistency consistency) noexcept { _readConsistency = consistency; } - ReadConsistency getReadConsistency() const noexcept { + [[nodiscard]] ReadConsistency getReadConsistency() const noexcept { return _readConsistency; } - vespalib::Trace && steal_trace() noexcept { return std::move(_trace); } - vespalib::Trace& getTrace() noexcept { return _trace; } - const vespalib::Trace& getTrace() const noexcept { return _trace; } + [[nodiscard]] vespalib::Trace && steal_trace() noexcept { return std::move(_trace); } + [[nodiscard]] vespalib::Trace& getTrace() noexcept { return _trace; } + [[nodiscard]] const vespalib::Trace& getTrace() const noexcept { return _trace; } - bool shouldTrace(int level) noexcept { return _trace.shouldTrace(level); } - void trace(int level, vespalib::stringref msg, bool addTime = true) { + [[nodiscard]] bool shouldTrace(uint32_t level) const noexcept { return _trace.shouldTrace(level); } + void trace(uint32_t level, vespalib::stringref msg, bool addTime = true) { _trace.trace(level, msg, addTime); } }; diff --git a/predicate-search-core/src/main/java/com/yahoo/document/predicate/Conjunction.java b/predicate-search-core/src/main/java/com/yahoo/document/predicate/Conjunction.java index a5b190d95ab..afe5ea29111 100644 --- a/predicate-search-core/src/main/java/com/yahoo/document/predicate/Conjunction.java +++ b/predicate-search-core/src/main/java/com/yahoo/document/predicate/Conjunction.java @@ -2,7 +2,6 @@ package com.yahoo.document.predicate; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -15,7 +14,7 @@ public class Conjunction extends PredicateOperator { private List<Predicate> operands; public Conjunction(Predicate... operands) { - this(Arrays.asList(operands)); + this(List.of(operands)); } public Conjunction(List<? extends Predicate> operands) { diff --git a/predicate-search-core/src/main/java/com/yahoo/document/predicate/Disjunction.java b/predicate-search-core/src/main/java/com/yahoo/document/predicate/Disjunction.java index 0b03f8afc40..db8392dcdb3 100644 --- a/predicate-search-core/src/main/java/com/yahoo/document/predicate/Disjunction.java +++ b/predicate-search-core/src/main/java/com/yahoo/document/predicate/Disjunction.java @@ -2,7 +2,6 @@ package com.yahoo.document.predicate; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -15,7 +14,7 @@ public class Disjunction extends PredicateOperator { private List<Predicate> operands; public Disjunction(Predicate... operands) { - this(Arrays.asList(operands)); + this(List.of(operands)); } public Disjunction(List<? extends Predicate> operands) { diff --git a/predicate-search-core/src/main/java/com/yahoo/document/predicate/FeatureSet.java b/predicate-search-core/src/main/java/com/yahoo/document/predicate/FeatureSet.java index d2486850f3a..bf1d006fda0 100644 --- a/predicate-search-core/src/main/java/com/yahoo/document/predicate/FeatureSet.java +++ b/predicate-search-core/src/main/java/com/yahoo/document/predicate/FeatureSet.java @@ -1,9 +1,9 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.document.predicate; -import java.util.Arrays; import java.util.Collection; import java.util.Iterator; +import java.util.List; import java.util.Objects; import java.util.Set; import java.util.TreeSet; @@ -17,7 +17,7 @@ public class FeatureSet extends PredicateValue { private String key; public FeatureSet(String key, String... values) { - this(key, Arrays.asList(values)); + this(key, List.of(values)); } public FeatureSet(String key, Collection<String> values) { @@ -83,10 +83,9 @@ public class FeatureSet extends PredicateValue { if (obj == this) { return true; } - if (!(obj instanceof FeatureSet)) { + if (!(obj instanceof FeatureSet rhs)) { return false; } - FeatureSet rhs = (FeatureSet)obj; if (!key.equals(rhs.key)) { return false; } diff --git a/predicate-search-core/src/main/java/com/yahoo/document/predicate/Negation.java b/predicate-search-core/src/main/java/com/yahoo/document/predicate/Negation.java index 62ad522e655..5e138fe8909 100644 --- a/predicate-search-core/src/main/java/com/yahoo/document/predicate/Negation.java +++ b/predicate-search-core/src/main/java/com/yahoo/document/predicate/Negation.java @@ -28,7 +28,7 @@ public class Negation extends PredicateOperator { @Override public List<Predicate> getOperands() { - return java.util.Arrays.asList(operand); + return java.util.List.of(operand); } @Override diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java index 56b338453d2..a698248ab6b 100644 --- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java +++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java @@ -3,7 +3,7 @@ package com.yahoo.document.predicate; import org.junit.jupiter.api.Test; -import java.util.Arrays; +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -22,18 +22,18 @@ public class ConjunctionTest { Conjunction node = new Conjunction(); Predicate a = SimplePredicates.newString("a"); node.addOperand(a); - assertEquals(Arrays.asList(a), node.getOperands()); + assertEquals(List.of(a), node.getOperands()); Predicate b = SimplePredicates.newString("b"); node.addOperand(b); - assertEquals(Arrays.asList(a, b), node.getOperands()); + assertEquals(List.of(a, b), node.getOperands()); Predicate c = SimplePredicates.newString("c"); Predicate d = SimplePredicates.newString("d"); - node.addOperands(Arrays.asList(c, d)); - assertEquals(Arrays.asList(a, b, c, d), node.getOperands()); + node.addOperands(List.of(c, d)); + assertEquals(List.of(a, b, c, d), node.getOperands()); Predicate e = SimplePredicates.newString("e"); Predicate f = SimplePredicates.newString("f"); - node.setOperands(Arrays.asList(e, f)); - assertEquals(Arrays.asList(e, f), node.getOperands()); + node.setOperands(List.of(e, f)); + assertEquals(List.of(e, f), node.getOperands()); } @Test @@ -41,10 +41,10 @@ public class ConjunctionTest { Predicate foo = SimplePredicates.newString("foo"); Predicate bar = SimplePredicates.newString("bar"); Conjunction node = new Conjunction(foo, bar); - assertEquals(Arrays.asList(foo, bar), node.getOperands()); + assertEquals(List.of(foo, bar), node.getOperands()); - node = new Conjunction(Arrays.asList(foo, bar)); - assertEquals(Arrays.asList(foo, bar), node.getOperands()); + node = new Conjunction(List.of(foo, bar)); + assertEquals(List.of(foo, bar), node.getOperands()); } @Test diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java index efde8ec7532..fa1cde8fdd3 100644 --- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java +++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java @@ -3,7 +3,7 @@ package com.yahoo.document.predicate; import org.junit.jupiter.api.Test; -import java.util.Arrays; +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -22,18 +22,18 @@ public class DisjunctionTest { Disjunction node = new Disjunction(); Predicate a = SimplePredicates.newString("a"); node.addOperand(a); - assertEquals(Arrays.asList(a), node.getOperands()); + assertEquals(List.of(a), node.getOperands()); Predicate b = SimplePredicates.newString("b"); node.addOperand(b); - assertEquals(Arrays.asList(a, b), node.getOperands()); + assertEquals(List.of(a, b), node.getOperands()); Predicate c = SimplePredicates.newString("c"); Predicate d = SimplePredicates.newString("d"); - node.addOperands(Arrays.asList(c, d)); - assertEquals(Arrays.asList(a, b, c, d), node.getOperands()); + node.addOperands(List.of(c, d)); + assertEquals(List.of(a, b, c, d), node.getOperands()); Predicate e = SimplePredicates.newString("e"); Predicate f = SimplePredicates.newString("f"); - node.setOperands(Arrays.asList(e, f)); - assertEquals(Arrays.asList(e, f), node.getOperands()); + node.setOperands(List.of(e, f)); + assertEquals(List.of(e, f), node.getOperands()); } @Test @@ -41,10 +41,10 @@ public class DisjunctionTest { Predicate foo = SimplePredicates.newString("foo"); Predicate bar = SimplePredicates.newString("bar"); Disjunction node = new Disjunction(foo, bar); - assertEquals(Arrays.asList(foo, bar), node.getOperands()); + assertEquals(List.of(foo, bar), node.getOperands()); - node = new Disjunction(Arrays.asList(foo, bar)); - assertEquals(Arrays.asList(foo, bar), node.getOperands()); + node = new Disjunction(List.of(foo, bar)); + assertEquals(List.of(foo, bar), node.getOperands()); } @Test diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java index 38b8d668a18..35dab62925f 100644 --- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java +++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java @@ -3,8 +3,7 @@ package com.yahoo.document.predicate; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import static com.yahoo.document.predicate.Predicates.feature; import static com.yahoo.document.predicate.Predicates.not; @@ -17,7 +16,7 @@ public class FeatureConjunctionTest { @Test void require_that_featureconjunction_with_valid_operands_can_be_constructed() { - new FeatureConjunction(Arrays.asList( + new FeatureConjunction(List.of( not(feature("a").inSet("1")), feature("b").inSet("1"))); } @@ -25,7 +24,7 @@ public class FeatureConjunctionTest { @Test void require_that_constructor_throws_exception_if_all_operands_are_not_featuresets() { assertThrows(IllegalArgumentException.class, () -> { - new FeatureConjunction(Arrays.asList( + new FeatureConjunction(List.of( not(feature("a").inSet("1")), feature("b").inRange(1, 2))); }); @@ -34,28 +33,28 @@ public class FeatureConjunctionTest { @Test void require_that_constructor_throws_exception_if_single_operand() { assertThrows(IllegalArgumentException.class, () -> { - new FeatureConjunction(Arrays.asList(feature("a").inSet("1"))); + new FeatureConjunction(List.of(feature("a").inSet("1"))); }); } @Test void require_that_constructor_throws_exception_if_no_operands() { assertThrows(IllegalArgumentException.class, () -> { - new FeatureConjunction(Collections.emptyList()); + new FeatureConjunction(List.of()); }); } @Test void require_that_contructor_throws_exception_if_featuresets_contain_multiple_values() { assertThrows(IllegalArgumentException.class, () -> { - new FeatureConjunction(Arrays.asList(feature("a").inSet("1"), feature("b").inSet("2", "3"))); + new FeatureConjunction(List.of(feature("a").inSet("1"), feature("b").inSet("2", "3"))); }); } @Test void require_that_constructor_throws_exception_if_featureset_keys_are_not_unique() { assertThrows(IllegalArgumentException.class, () -> { - new FeatureConjunction(Arrays.asList( + new FeatureConjunction(List.of( not(feature("a").inSet("1")), feature("a").inSet("2"))); }); diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java index 06c1a445494..3977ad02999 100644 --- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java +++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java @@ -3,7 +3,7 @@ package com.yahoo.document.predicate; import org.junit.jupiter.api.Test; -import java.util.Arrays; +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -249,15 +249,15 @@ public class FeatureRangeTest { @Test void requireThatFeatureRangeCanBeBuiltFromMixedInNode() { assertEquals(new FeatureRange("foo", 10L, 19L), - FeatureRange.buildFromMixedIn("foo", Arrays.asList("foo=10-19"), 10)); + FeatureRange.buildFromMixedIn("foo", List.of("foo=10-19"), 10)); assertEquals(new FeatureRange("foo", -19L, -10L), - FeatureRange.buildFromMixedIn("foo", Arrays.asList("foo=-10-19"), 10)); + FeatureRange.buildFromMixedIn("foo", List.of("foo=-10-19"), 10)); assertEquals(new FeatureRange("foo", 10L, 19L), - FeatureRange.buildFromMixedIn("foo", Arrays.asList("foo=10,10,9"), 10)); + FeatureRange.buildFromMixedIn("foo", List.of("foo=10,10,9"), 10)); assertEquals(new FeatureRange("foo", 10L, 19L), - FeatureRange.buildFromMixedIn("foo", Arrays.asList("foo=10,10,1073741833"), 10)); + FeatureRange.buildFromMixedIn("foo", List.of("foo=10,10,1073741833"), 10)); assertEquals(new FeatureRange("foo", 10L, 19L), - FeatureRange.buildFromMixedIn("foo", Arrays.asList("foo=10,10,2147483648"), 10)); + FeatureRange.buildFromMixedIn("foo", List.of("foo=10,10,2147483648"), 10)); } } diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java index b61f843c10e..31cfe4318fb 100644 --- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java +++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java @@ -4,7 +4,6 @@ package com.yahoo.document.predicate; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -25,35 +24,35 @@ public class FeatureSetTest { void requireThatAccessorsWork() { FeatureSet node = new FeatureSet("key", "valueA", "valueB"); assertEquals("key", node.getKey()); - assertValues(Arrays.asList("valueA", "valueB"), node); + assertValues(List.of("valueA", "valueB"), node); node.addValue("valueC"); - assertValues(Arrays.asList("valueA", "valueB", "valueC"), node); - node.addValues(Arrays.asList("valueD", "valueE")); - assertValues(Arrays.asList("valueA", "valueB", "valueC", "valueD", "valueE"), node); - node.setValues(Arrays.asList("valueF", "valueG")); - assertValues(Arrays.asList("valueF", "valueG"), node); + assertValues(List.of("valueA", "valueB", "valueC"), node); + node.addValues(List.of("valueD", "valueE")); + assertValues(List.of("valueA", "valueB", "valueC", "valueD", "valueE"), node); + node.setValues(List.of("valueF", "valueG")); + assertValues(List.of("valueF", "valueG"), node); } @Test void requireThatValueSetIsMutable() { FeatureSet node = new FeatureSet("key"); node.getValues().add("valueA"); - assertValues(Arrays.asList("valueA"), node); + assertValues(List.of("valueA"), node); node = new FeatureSet("key", "valueA"); node.getValues().add("valueB"); - assertValues(Arrays.asList("valueA", "valueB"), node); + assertValues(List.of("valueA", "valueB"), node); } @Test void requireThatConstructorsWork() { FeatureSet node = new FeatureSet("key", "valueA", "valueB"); assertEquals("key", node.getKey()); - assertValues(Arrays.asList("valueA", "valueB"), node); + assertValues(List.of("valueA", "valueB"), node); - node = new FeatureSet("key", Arrays.asList("valueA", "valueB")); + node = new FeatureSet("key", List.of("valueA", "valueB")); assertEquals("key", node.getKey()); - assertValues(Arrays.asList("valueA", "valueB"), node); + assertValues(List.of("valueA", "valueB"), node); } @Test @@ -123,7 +122,7 @@ public class FeatureSetTest { } catch (NullPointerException e) { assertEquals("value", e.getMessage()); } - assertValues(Arrays.asList("bar"), node); + assertValues(List.of("bar"), node); } @Test diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java index 8bc434218b7..b8ec623410c 100644 --- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java +++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java @@ -4,7 +4,6 @@ package com.yahoo.search.predicate; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -34,7 +33,7 @@ public class PredicateQueryParserTest { (k, v, s) -> result.add(String.format("%s:%s:%#x", k, v, s)), (k, v, s) -> result.add(String.format("%s:%d:%#x", k, v, s))); - assertEquals(result, Arrays.asList( + assertEquals(result, List.of( "k1:value1:0x1", "k2:value2:0x3", "range1:123456789123:0xffff", "range2:0:0xffffffffffffffff")); } diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java index 401c006b273..bc330a7d1f3 100644 --- a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java +++ b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java @@ -6,7 +6,8 @@ import com.yahoo.document.predicate.Predicate; import com.yahoo.document.predicate.PredicateOperator; import org.junit.jupiter.api.Test; -import java.util.Arrays; + +import java.util.List; import static com.yahoo.document.predicate.Predicates.and; import static com.yahoo.document.predicate.Predicates.feature; @@ -208,7 +209,7 @@ public class PredicateTreeAnalyzerTest { } private static FeatureConjunction conj(Predicate... operands) { - return new FeatureConjunction(Arrays.asList(operands)); + return new FeatureConjunction(List.of(operands)); } private static void assertSizeMapContains(PredicateTreeAnalyzerResult r, PredicateSelector selector, int expectedValue) { @@ -217,18 +218,13 @@ public class PredicateTreeAnalyzerTest { assertEquals(expectedValue, actualValue.intValue()); } - private static class PredicateSelector { - public final Predicate predicate; - - public PredicateSelector(Predicate predicate) { - this.predicate = predicate; - } + private record PredicateSelector(Predicate predicate) { public PredicateSelector child(int index) { - PredicateOperator op = (PredicateOperator) predicate; - return new PredicateSelector(op.getOperands().get(index)); + PredicateOperator op = (PredicateOperator) predicate; + return new PredicateSelector(op.getOperands().get(index)); + } } - } private static PredicateSelector pred(Predicate p) { return new PredicateSelector(p); diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java index 18cdc4defff..237aeda4fb3 100644 --- a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java +++ b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java @@ -13,7 +13,6 @@ import com.yahoo.search.predicate.index.IntervalWithBounds; import com.yahoo.search.predicate.index.conjunction.IndexableFeatureConjunction; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -229,7 +228,7 @@ public class PredicateTreeAnnotatorTest { long hash = PredicateHash.hash64(feature); List<Integer> actualIntervals = r.intervalMap.get(hash); assertNotNull(actualIntervals); - assertArrayEquals(Ints.toArray(Arrays.asList(expectedIntervals)), Ints.toArray(actualIntervals)); + assertArrayEquals(Ints.toArray(List.of(expectedIntervals)), Ints.toArray(actualIntervals)); } private static void assertBoundsContains(PredicateTreeAnnotations r, String feature, IntervalWithBounds expectedBounds) { @@ -258,11 +257,11 @@ public class PredicateTreeAnnotatorTest { private static FeatureRange range(String key, Long lower, Long upper, RangePartition... partitions) { FeatureRange range = new FeatureRange(key, lower, upper); - Arrays.asList(partitions).forEach(range::addPartition); + List.of(partitions).forEach(range::addPartition); return range; } private static FeatureConjunction conj(Predicate... operands) { - return new FeatureConjunction(Arrays.asList(operands)); + return new FeatureConjunction(List.of(operands)); } } diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java index 68f692e3119..cf7e286f89f 100644 --- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java +++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java @@ -6,7 +6,6 @@ import org.eclipse.collections.impl.map.mutable.primitive.ObjectIntHashMap; import org.junit.jupiter.api.Test; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertArrayEquals; @@ -107,12 +106,12 @@ public class CachedPostingListCounterTest { } private static List<PostingList> list(PostingList... postingLists) { - return Arrays.asList(postingLists); + return List.of(postingLists); } private static PostingList postingList(Integer... docIds) { PostingList postingList = mock(PostingList.class); - when(postingList.getDocIds()).thenReturn(Ints.toArray(Arrays.asList((docIds)))); + when(postingList.getDocIds()).thenReturn(Ints.toArray(List.of((docIds)))); return postingList; } diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java index 8b2a5cc1d7e..26f191e13b6 100644 --- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java +++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java @@ -4,7 +4,8 @@ package com.yahoo.search.predicate.index; import com.yahoo.search.predicate.SubqueryBitmap; import org.junit.jupiter.api.Test; -import java.util.Arrays; + +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -13,9 +14,9 @@ public class IntervalPostingListTest { @Test void requireThatPostingListCanIterate() { PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder(); - int ref1 = builder.insert(Arrays.asList(0x1ffff)); - int ref2 = builder.insert(Arrays.asList(0x1ffff)); - int ref3 = builder.insert(Arrays.asList(0x10001, 0x2ffff)); + int ref1 = builder.insert(List.of(0x1ffff)); + int ref2 = builder.insert(List.of(0x1ffff)); + int ref3 = builder.insert(List.of(0x10001, 0x2ffff)); IntervalPostingList postingList = new IntervalPostingList( builder.build(), new int[]{2, 4, 6}, new int[]{ref1, ref2, ref3}, SubqueryBitmap.ALL_SUBQUERIES); assertEquals(-1, postingList.getDocId()); diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java index bfc4635aa51..c02c18ae1d7 100644 --- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java +++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java @@ -6,7 +6,6 @@ import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import static com.yahoo.search.predicate.serialization.SerializationTestHelper.assertSerializationDeserializationMatches; @@ -49,9 +48,9 @@ public class PredicateIntervalStoreTest { @Test void requireThatSerializationAndDeserializationRetainIntervals() throws IOException { PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder(); - builder.insert(Arrays.asList(0x00010001, 0x00020002)); - builder.insert(Arrays.asList(0x00010001, 0x00020002, 0x00030003)); - builder.insert(Arrays.asList(0x0fffffff, 0x00020002, 0x00030003)); + builder.insert(List.of(0x00010001, 0x00020002)); + builder.insert(List.of(0x00010001, 0x00020002, 0x00030003)); + builder.insert(List.of(0x0fffffff, 0x00020002, 0x00030003)); PredicateIntervalStore store = builder.build(); assertSerializationDeserializationMatches( store, PredicateIntervalStore::writeToOutputStream, PredicateIntervalStore::fromInputStream); @@ -60,8 +59,8 @@ public class PredicateIntervalStoreTest { @Test void requireThatEqualIntervalListsReturnsSameReference() { PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder(); - List<Integer> intervals1 = Arrays.asList(0x00010001, 0x00020002); - List<Integer> intervals2 = Arrays.asList(0x00010001, 0x00020002); + List<Integer> intervals1 = List.of(0x00010001, 0x00020002); + List<Integer> intervals2 = List.of(0x00010001, 0x00020002); int ref1 = builder.insert(intervals1); int ref2 = builder.insert(intervals2); PredicateIntervalStore store = builder.build(); diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java index 3c0a2290817..0b8076b310c 100644 --- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java +++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java @@ -4,8 +4,8 @@ package com.yahoo.search.predicate.index; import com.yahoo.document.predicate.PredicateHash; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.Iterator; +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -16,7 +16,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatSmallRangeIsExpanded() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=40-49", "key=0-99", "key=0-999", @@ -46,7 +46,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatLargeRangeIsExpanded() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=123456789012345670-123456789012345679", "key=123456789012345600-123456789012345699", "key=123456789012345000-123456789012345999", @@ -86,7 +86,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatSmallNegativeRangeIsExpanded() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=-49-40", "key=-99-0", "key=-999-0", @@ -126,7 +126,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatMinRangeMinus9IsExpanded() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=-9223372036854775799-9223372036854775790", "key=-9223372036854775799-9223372036854775700").iterator(); expander.expand("key", -9223372036854775799L, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range), @@ -150,7 +150,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatSmallRangeIsExpandedInArity2() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(2); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=42-43", "key=40-43", "key=40-47", @@ -225,7 +225,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatSmallNegativeRangeIsExpandedInArity2() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(2); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=-43-42", "key=-43-40", "key=-47-40", @@ -300,7 +300,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatUpperBoundIsUsed() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, -99, 9999); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=40-49", "key=0-99", "key=0-999", @@ -316,7 +316,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatLowerBoundIsUsed() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, -9999, 99); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=-49-40", "key=-99-0", "key=-999-0", @@ -339,7 +339,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatUpperAndLowerBoundGreaterThan0Works() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, 100, 9999); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=140-149", "key=100-199", "key=0-999", @@ -355,7 +355,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatSearchCloseToUnevenUpperBoundIsSensible() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, -99, 1234); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=40-49", "key=0-99", "key=0-999", @@ -371,7 +371,7 @@ public class PredicateRangeTermExpanderTest { @Test void requireThatSearchCloseToMaxUnevenUpperBoundIsSensible() { PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, 0, 9223372036854771234L); - Iterator<String> expectedLabels = Arrays.asList( + Iterator<String> expectedLabels = List.of( "key=9223372036854770000-9223372036854770009", "key=9223372036854770000-9223372036854770099", "key=9223372036854770000-9223372036854770999").iterator(); diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java index 62dde7ac585..d520980193e 100644 --- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java +++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java @@ -32,7 +32,7 @@ public class PredicateSearchTest { entry(0, 0x000100ff), entry(1, 0x00010001, 0x000200ff), entry(2, 0x00010042))); - assertEquals(Arrays.asList(new Hit(0), new Hit(1)).toString(), search.stream().toList().toString()); + assertEquals(List.of(new Hit(0), new Hit(1)).toString(), search.stream().toList().toString()); } @Test @@ -43,7 +43,7 @@ public class PredicateSearchTest { SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x000100ff), entry(1, 0x000100ff))); - assertEquals(Arrays.asList(new Hit(1)).toString(), search.stream().toList().toString()); + assertEquals(List.of(new Hit(1)).toString(), search.stream().toList().toString()); } @Test @@ -54,7 +54,7 @@ public class PredicateSearchTest { entry(0, 0x00010001)), postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x000200ff))); - assertEquals(Arrays.asList(new Hit(0)).toString(), search.stream().toList().toString()); + assertEquals(List.of(new Hit(0)).toString(), search.stream().toList().toString()); } @Test @@ -67,7 +67,7 @@ public class PredicateSearchTest { postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(1, 0x000100ff), entry(2, 0x000100ff))); - assertEquals(Arrays.asList(new Hit(1), new Hit(2), new Hit(3)).toString(), search.stream().toList().toString()); + assertEquals(List.of(new Hit(1), new Hit(2), new Hit(3)).toString(), search.stream().toList().toString()); } @Test @@ -75,7 +75,7 @@ public class PredicateSearchTest { PredicateSearch search = createPredicateSearch( new byte[0], postingList(SubqueryBitmap.ALL_SUBQUERIES)); - assertEquals(Arrays.asList().toString(), search.stream().toList().toString()); + assertEquals(List.of().toString(), search.stream().toList().toString()); } @Test @@ -87,7 +87,7 @@ public class PredicateSearchTest { entry(1, 0x000100ff)), postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(2, 0x000100ff))); - assertEquals(Arrays.asList(new Hit(0), new Hit(1), new Hit(2)).toString(), search.stream().toList().toString()); + assertEquals(List.of(new Hit(0), new Hit(1), new Hit(2)).toString(), search.stream().toList().toString()); } @Test @@ -110,7 +110,7 @@ public class PredicateSearchTest { entry(1, 0x000100ff), entry(3, 0x000100ff))); assertEquals( - Arrays.asList(new Hit(0), new Hit(1), new Hit(2), new Hit(3)).toString(), + List.of(new Hit(0), new Hit(1), new Hit(2), new Hit(3)).toString(), search.stream().toList().toString()); } @@ -121,7 +121,7 @@ public class PredicateSearchTest { postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00010001), entry(1, 0x000200ff))); - assertEquals(Arrays.asList().toString(), search.stream().toList().toString()); + assertEquals(List.of().toString(), search.stream().toList().toString()); } @Test @@ -134,7 +134,7 @@ public class PredicateSearchTest { entry(0, 0x000300ff)), postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00020002))); - assertEquals(Arrays.asList(new Hit(0)).toString(), search.stream().toList().toString()); + assertEquals(List.of(new Hit(0)).toString(), search.stream().toList().toString()); } @Test @@ -143,7 +143,7 @@ public class PredicateSearchTest { new byte[]{1}, postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00010001, 0x00020002, 0x00030003, 0x000100ff, 0x00040004, 0x00050005, 0x00060006))); - assertEquals(Arrays.asList(new Hit(0)).toString(), search.stream().toList().toString()); + assertEquals(List.of(new Hit(0)).toString(), search.stream().toList().toString()); } @Test @@ -154,7 +154,7 @@ public class PredicateSearchTest { entry(0, 0x00010001)), postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00010000, 0x00ff0001))); - assertEquals(Arrays.asList().toString(), search.stream().toList().toString()); + assertEquals(List.of().toString(), search.stream().toList().toString()); } @Test @@ -163,7 +163,7 @@ public class PredicateSearchTest { new byte[]{1}, postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00010000, 0x00ff0001))); - assertEquals(Arrays.asList(new Hit(0)).toString(), search.stream().toList().toString()); + assertEquals(List.of(new Hit(0)).toString(), search.stream().toList().toString()); } @Test @@ -172,7 +172,7 @@ public class PredicateSearchTest { new byte[]{1}, postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00020001, 0x00ff0001))); - assertEquals(Arrays.asList().toString(), search.stream().toList().toString()); + assertEquals(List.of().toString(), search.stream().toList().toString()); } @Test @@ -183,7 +183,7 @@ public class PredicateSearchTest { entry(0, 0x00010001)), postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00fe0001, 0x00ff00fe))); - assertEquals(Arrays.asList(new Hit(0)).toString(), search.stream().toList().toString()); + assertEquals(List.of(new Hit(0)).toString(), search.stream().toList().toString()); } @Test @@ -202,14 +202,14 @@ public class PredicateSearchTest { entry(0, 0x00010008, 0x00060006)), postingList(SubqueryBitmap.ALL_SUBQUERIES, entry(0, 0x00020002, 0x000700ff))); - assertEquals(Arrays.asList(new Hit(0)).toString(), search.stream().toList().toString()); + assertEquals(List.of(new Hit(0)).toString(), search.stream().toList().toString()); } private static PredicateSearch createPredicateSearch(byte[] minFeatures, PostingList... postingLists) { byte[] nPostingListsForDocument = new byte[minFeatures.length]; short[] intervalEnds = new short[minFeatures.length]; Arrays.fill(intervalEnds, (short) 0xFF); - List<PostingList> list = Arrays.asList(postingLists); + List<PostingList> list = List.of(postingLists); for (PostingList postingList : postingLists) { for (int id : postingList.getDocIds()) { nPostingListsForDocument[id]++; diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java index 408d4f43489..43fd35d8689 100644 --- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java +++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java @@ -3,7 +3,8 @@ package com.yahoo.search.predicate.index; import org.junit.jupiter.api.Test; -import java.util.Arrays; + +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -14,9 +15,9 @@ public class ZstarCompressedPostingListTest { @Test void requireThatPostingListCanIterate() { PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder(); - int ref1 = builder.insert(Arrays.asList(0x10000)); - int ref2 = builder.insert(Arrays.asList(0x10000, 0x0ffff)); - int ref3 = builder.insert(Arrays.asList(0x10000, 0x00003, 0x40003, 0x60005)); + int ref1 = builder.insert(List.of(0x10000)); + int ref2 = builder.insert(List.of(0x10000, 0x0ffff)); + int ref3 = builder.insert(List.of(0x10000, 0x00003, 0x40003, 0x60005)); ZstarCompressedPostingList postingList = new ZstarCompressedPostingList( builder.build(), new int[]{2, 4, 6}, new int[]{ref1, ref2, ref3}); assertEquals(-1, postingList.getDocId()); diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java index 33265d9bb61..c0334b81c59 100644 --- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java +++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java @@ -343,7 +343,7 @@ public class ConjunctionIndexTest { } private static List<ConjunctionHit> matchingConjunctionList(ConjunctionHit... conjunctionHits) { - return Arrays.asList(conjunctionHits); + return List.of(conjunctionHits); } private static void assertHitsEquals(List<ConjunctionHit> hits, IndexableFeatureConjunction... conjunctions) { @@ -356,15 +356,11 @@ public class ConjunctionIndexTest { } private static void assertHitsEquals(List<ConjunctionHit> expectedHits, List<ConjunctionHit> hits) { - Collections.sort(expectedHits); - Collections.sort(hits); - assertArrayEquals( - expectedHits.toArray(new ConjunctionHit[expectedHits.size()]), - hits.toArray(new ConjunctionHit[expectedHits.size()])); + assertEquals(expectedHits.stream().sorted().toList(), hits.stream().sorted().toList()); } private static FeatureConjunction conj(Predicate... operands) { - return new FeatureConjunction(Arrays.asList(operands)); + return new FeatureConjunction(List.of(operands)); } private static IndexableFeatureConjunction indexableConj(FeatureConjunction conjunction) { diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java index 2e9c9a32410..c8c4b1f1911 100644 --- a/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java +++ b/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java @@ -7,7 +7,8 @@ import com.yahoo.document.predicate.FeatureSet; import com.yahoo.document.predicate.Predicate; import org.junit.jupiter.api.Test; -import java.util.Arrays; + +import java.util.List; import static com.yahoo.document.predicate.Predicates.and; import static com.yahoo.document.predicate.Predicates.not; @@ -101,7 +102,7 @@ public class FeatureConjunctionTransformerTest { } private static FeatureConjunction conj(Predicate... operands) { - return new FeatureConjunction(Arrays.asList(operands)); + return new FeatureConjunction(List.of(operands)); } private static FeatureSet featureSet(int id, String... values) { diff --git a/screwdriver.yaml b/screwdriver.yaml index 32ad8288d70..4edef83b63b 100644 --- a/screwdriver.yaml +++ b/screwdriver.yaml @@ -111,6 +111,8 @@ jobs: - get-vespa-version: | if [[ -z "$SD_PULL_REQUEST" ]]; then VERSION_INFO=$(screwdriver/factory-command.sh create-build) + echo "Version information from Factory : $VERSION_INFO" + VESPA_VERSION=$(jq -re '.version' <<< "$VERSION_INFO") VESPA_REF=$(jq -re '.commits|.[]|select(.repo=="vespa")|.ref' <<< "$VERSION_INFO") SYSTEM_TEST_REF=$(jq -re '.commits|.[]|select(.repo=="system-test")|.ref' <<< "$VERSION_INFO") diff --git a/screwdriver/factory-command.sh b/screwdriver/factory-command.sh index 3b739b9f5c9..a09900ec0a0 100755 --- a/screwdriver/factory-command.sh +++ b/screwdriver/factory-command.sh @@ -12,7 +12,24 @@ FACTORY_API="https://factory.vespa.aws-us-east-1a.vespa.oath.cloud/api/factory/v COOKIEJAR=$(pwd)/jar.txt trap "rm -f $COOKIEJAR" EXIT -SESSION_TOKEN=$(curl -s -H 'Content-Type: application/json' -H 'Accept: application/json' -d "{ \"username\": \"svc-okta-vespa-factory\", \"password\": \"$SVC_OKTA_VESPA_FACTORY_TOKEN\" }" https://ouryahoo.okta.com/api/v1/authn | jq -re '.sessionToken') +SESSION_TOKEN=null +WAIT_UNTIL=$(( $(date +%s) + 120 )) +set +e +while [[ $SESSION_TOKEN == null ]]; do + SESSION_TOKEN=$(curl -s -H 'Content-Type: application/json' -H 'Accept: application/json' -d "{ \"username\": \"svc-okta-vespa-factory\", \"password\": \"$SVC_OKTA_VESPA_FACTORY_TOKEN\" }" https://ouryahoo.okta.com/api/v1/authn | jq -re '.sessionToken') + + if [[ $SESSION_TOKEN == null ]]; then + if [[ $(date +%s) -ge $WAIT_UNTIL ]]; then + echo "Could not fetch session token from Okta: SESSION_TOKEN=$SESSION_TOKEN" + exit 1 + else + echo "Invalid SESSION_TOKEN=$SESSION_TOKEN . Trying again ..." >&2 + sleep 3 + fi + fi +done +set -e + LOCATION=$(curl -s -i -c $COOKIEJAR "https://factory.vespa.aws-us-east-1a.vespa.oath.cloud/login" | grep location | awk '{print $2}' | tr -d '\r') curl -sL -b $COOKIEJAR -c $COOKIEJAR "$LOCATION&sessionToken=$SESSION_TOKEN" &> /dev/null diff --git a/searchcore/src/apps/proton/CMakeLists.txt b/searchcore/src/apps/proton/CMakeLists.txt index a26a9e463d6..40bdcbaf1b1 100644 --- a/searchcore/src/apps/proton/CMakeLists.txt +++ b/searchcore/src/apps/proton/CMakeLists.txt @@ -23,4 +23,5 @@ vespa_add_executable(searchcore_proton_app searchcore_grouping searchcore_proton_metrics storageserver_storageapp + absl::failure_signal_handler ) diff --git a/searchcore/src/apps/proton/proton.cpp b/searchcore/src/apps/proton/proton.cpp index e967c012bbe..de256ebf0d9 100644 --- a/searchcore/src/apps/proton/proton.cpp +++ b/searchcore/src/apps/proton/proton.cpp @@ -12,6 +12,7 @@ #include <vespa/config/common/configcontext.h> #include <vespa/fnet/transport.h> #include <vespa/fastos/file.h> +#include <absl/debugging/failure_signal_handler.h> #include <filesystem> #include <iostream> #include <thread> @@ -53,6 +54,20 @@ public: void App::setupSignals() { + absl::FailureSignalHandlerOptions opts; + // Sanitizers set up their own signal handler, so we must ensure that the failure signal + // handler calls this when it's done, or we won't get a proper report. + opts.call_previous_handler = true; + // Ideally we'd use an alternate stack to have well-defined reporting when a + // thread runs out of stack space (infinite recursion bug etc.), but for some + // reason this seems to negatively affect stack walking and give very incomplete + // traces. So until this is resolved, use the thread's own stack. + opts.use_alternate_stack = false; + absl::InstallFailureSignalHandler(opts); + + // Install our own signal handlers _after_ the failure handler, as the sentinel uses + // SIGTERM as a "friendly poke for shutdown" signal and the Abseil failure handler + // always dumps stack when intercepting this signal (since it's considered fatal). SIG::PIPE.ignore(); SIG::INT.hook(); SIG::TERM.hook(); diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/ExpressionFunction.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/ExpressionFunction.java index 093e65b2e4d..840eacd9dd9 100755..100644 --- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/ExpressionFunction.java +++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/ExpressionFunction.java @@ -15,7 +15,6 @@ import static com.yahoo.searchlib.rankingexpression.Reference.wrapInRankingExpre import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.List; @@ -50,7 +49,7 @@ public class ExpressionFunction { * @param body the ranking expression that defines this function */ public ExpressionFunction(String name, RankingExpression body) { - this(name, Collections.emptyList(), body); + this(name, List.of(), body); } /** diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/EmbracedNode.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/EmbracedNode.java index 1186541b9c0..c7231ecd800 100755..100644 --- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/EmbracedNode.java +++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/EmbracedNode.java @@ -7,7 +7,6 @@ import com.yahoo.searchlib.rankingexpression.evaluation.Value; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.TypeContext; -import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Objects; @@ -36,7 +35,7 @@ public final class EmbracedNode extends CompositeNode { @Override public List<ExpressionNode> children() { - return Collections.singletonList(value); + return List.of(value); } @Override diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/FunctionNode.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/FunctionNode.java index e7db8848be5..e93edb71ac6 100755..100644 --- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/FunctionNode.java +++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/FunctionNode.java @@ -11,7 +11,6 @@ import com.yahoo.tensor.evaluation.TypeContext; import com.yahoo.tensor.functions.Join; import java.util.ArrayList; -import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Objects; @@ -34,7 +33,7 @@ public final class FunctionNode extends CompositeNode { public FunctionNode(Function function, ExpressionNode argument) { if (function.arity() != 1) throw new IllegalArgumentException(function + " is not unary"); this.function = function; - this.arguments = new Arguments(Collections.singletonList(argument)); + this.arguments = new Arguments(List.of(argument)); } /** Creates a binary function node */ diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/FunctionReferenceContext.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/FunctionReferenceContext.java index a2cf662a255..be0a532128f 100644 --- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/FunctionReferenceContext.java +++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/FunctionReferenceContext.java @@ -4,8 +4,8 @@ package com.yahoo.searchlib.rankingexpression.rule; import com.yahoo.searchlib.rankingexpression.ExpressionFunction; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; /** @@ -23,12 +23,12 @@ public class FunctionReferenceContext { /** Create a context for a single serialization task */ public FunctionReferenceContext() { - this(Collections.emptyList()); + this(List.of()); } /** Create a context for a single serialization task */ public FunctionReferenceContext(Collection<ExpressionFunction> functions) { - this(toMap(functions), Collections.emptyMap()); + this(toMap(functions), Map.of()); } public FunctionReferenceContext(Collection<ExpressionFunction> functions, Map<String, String> bindings) { diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/GeneratorLambdaFunctionNode.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/GeneratorLambdaFunctionNode.java index bef19a656f8..49311b1553b 100644 --- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/GeneratorLambdaFunctionNode.java +++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/GeneratorLambdaFunctionNode.java @@ -8,7 +8,6 @@ import com.yahoo.searchlib.rankingexpression.evaluation.Value; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.TypeContext; -import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Objects; @@ -39,7 +38,7 @@ public class GeneratorLambdaFunctionNode extends CompositeNode { @Override public List<ExpressionNode> children() { - return Collections.singletonList(generator); + return List.of(generator); } @Override diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/LambdaFunctionNode.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/LambdaFunctionNode.java index 0f1331515cc..b84bb655140 100644 --- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/LambdaFunctionNode.java +++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/LambdaFunctionNode.java @@ -9,7 +9,6 @@ import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.TypeContext; import com.yahoo.tensor.functions.Generate; -import java.util.Collections; import java.util.Deque; import java.util.HashSet; import java.util.List; @@ -50,7 +49,7 @@ public class LambdaFunctionNode extends CompositeNode { @Override public List<ExpressionNode> children() { - return Collections.singletonList(functionExpression); + return List.of(functionExpression); } @Override diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/NotNode.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/NotNode.java index ba8fb10a1cd..dcf1f857832 100644 --- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/NotNode.java +++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/NotNode.java @@ -7,7 +7,6 @@ import com.yahoo.searchlib.rankingexpression.evaluation.Value; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.TypeContext; -import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Objects; @@ -31,7 +30,7 @@ public class NotNode extends BooleanNode { @Override public List<ExpressionNode> children() { - return Collections.singletonList(value); + return List.of(value); } @Override diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/SerializationContext.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/SerializationContext.java index d1cb77fb1b4..271e367c1f4 100644 --- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/SerializationContext.java +++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/SerializationContext.java @@ -9,9 +9,9 @@ import com.yahoo.tensor.evaluation.TypeContext; import static com.yahoo.searchlib.rankingexpression.Reference.wrapInRankingExpression; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -29,7 +29,7 @@ public class SerializationContext extends FunctionReferenceContext { /** Create a context for a single serialization task */ public SerializationContext() { - this(Collections.emptyList(), Collections.emptyMap(), Optional.empty(), new LinkedHashMap<>()); + this(List.of(), Map.of(), Optional.empty(), new LinkedHashMap<>()); } /** @@ -40,7 +40,7 @@ public class SerializationContext extends FunctionReferenceContext { */ public SerializationContext(Collection<ExpressionFunction> functions, Optional<TypeContext<Reference>> typeContext) { - this(functions, Collections.emptyMap(), typeContext, new LinkedHashMap<>()); + this(functions, Map.of(), typeContext, new LinkedHashMap<>()); } /** diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/TensorFunctionNode.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/TensorFunctionNode.java index b3f2f265900..202dbebc311 100644 --- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/TensorFunctionNode.java +++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/TensorFunctionNode.java @@ -19,7 +19,6 @@ import com.yahoo.tensor.functions.TensorFunction; import com.yahoo.tensor.functions.ToStringContext; import java.util.ArrayList; -import java.util.Collections; import java.util.Deque; import java.util.LinkedHashMap; import java.util.List; @@ -238,7 +237,7 @@ public class TensorFunctionNode extends CompositeNode { .map(ExpressionTensorFunction::new) .collect(Collectors.toList()); else - return Collections.emptyList(); + return List.of(); } @Override diff --git a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/UnpackBitsNode.java b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/UnpackBitsNode.java index 81ad09dd880..0a0f48df823 100644 --- a/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/UnpackBitsNode.java +++ b/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/UnpackBitsNode.java @@ -11,7 +11,6 @@ import com.yahoo.tensor.TensorAddress; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.TypeContext; -import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Objects; @@ -53,7 +52,7 @@ public class UnpackBitsNode extends CompositeNode { @Override public List<ExpressionNode> children() { - return Collections.singletonList(input); + return List.of(input); } private static record Meta(TensorType outputType, TensorType outputDenseType, String unpackDimension) {} diff --git a/searchlib/src/main/javacc/RankingExpressionParser.jj b/searchlib/src/main/javacc/RankingExpressionParser.jj index 97aa42f79c9..51f433bf67d 100755..100644 --- a/searchlib/src/main/javacc/RankingExpressionParser.jj +++ b/searchlib/src/main/javacc/RankingExpressionParser.jj @@ -24,7 +24,6 @@ import com.yahoo.searchlib.rankingexpression.evaluation.StringValue; import com.yahoo.searchlib.rankingexpression.evaluation.TensorValue; import com.yahoo.tensor.*; import com.yahoo.tensor.functions.*; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.Arrays; import java.util.ArrayList; @@ -893,7 +892,7 @@ List<String> bracedIdentifierList() : String element; } { - ( element = identifier() { return Collections.singletonList(element); } ) + ( element = identifier() { return List.of(element); } ) | ( <LBRACE> list = identifierList() <RBRACE> { return list; } ) } diff --git a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/GroupTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/GroupTestCase.java index e306d27b6ee..60309db9787 100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/GroupTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/GroupTestCase.java @@ -10,7 +10,6 @@ import com.yahoo.vespa.objects.BufferSerializer; import com.yahoo.vespa.objects.Identifiable; import org.junit.Test; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; @@ -56,7 +55,7 @@ public class GroupTestCase { group.addOrderBy(bar, false); assertEquals(2, group.getOrderByExpressions().size()); assertSame(bar, group.getOrderByExpressions().get(1)); - assertEquals(Arrays.asList(1, -2), group.getOrderByIndexes()); + assertEquals(List.of(1, -2), group.getOrderByIndexes()); } @Test diff --git a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/GroupingTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/GroupingTestCase.java index 66b8a07ac95..a0e6fd32ddc 100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/GroupingTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/GroupingTestCase.java @@ -1,14 +1,12 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.searchlib.aggregation; -import com.yahoo.searchlib.expression.FloatResultNode; import com.yahoo.searchlib.expression.NullResultNode; import com.yahoo.searchlib.expression.StringBucketResultNode; import com.yahoo.vespa.objects.BufferSerializer; import org.junit.Test; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import static org.junit.Assert.*; @@ -30,7 +28,7 @@ public class GroupingTestCase { assertEquals(9, grouping.getId()); Grouping other = new Grouping(6); - assertFalse(grouping.equals(other)); + assertNotEquals(grouping, other); other.setId(9); assertEquals(grouping, other); @@ -46,7 +44,7 @@ public class GroupingTestCase { assertTrue(grouping.getAll()); Grouping other = new Grouping(); - assertFalse(grouping.equals(other)); + assertNotEquals(grouping, other); other.setAll(true); assertEquals(grouping, other); @@ -62,7 +60,7 @@ public class GroupingTestCase { assertEquals(69, grouping.getTopN()); Grouping other = new Grouping(); - assertFalse(grouping.equals(other)); + assertNotEquals(grouping, other); other.setTopN(69); assertEquals(grouping, other); @@ -78,7 +76,7 @@ public class GroupingTestCase { assertEquals(69, grouping.getFirstLevel()); Grouping other = new Grouping(); - assertFalse(grouping.equals(other)); + assertNotEquals(grouping, other); other.setFirstLevel(69); assertEquals(grouping, other); @@ -94,7 +92,7 @@ public class GroupingTestCase { assertEquals(69, grouping.getLastLevel()); Grouping other = new Grouping(); - assertFalse(grouping.equals(other)); + assertNotEquals(grouping, other); other.setLastLevel(69); assertEquals(grouping, other); @@ -117,7 +115,7 @@ public class GroupingTestCase { assertEquals(root, grouping.getRoot()); Grouping other = new Grouping(); - assertFalse(grouping.equals(other)); + assertNotEquals(grouping, other); other.setRoot(root); assertEquals(grouping, other); @@ -128,7 +126,7 @@ public class GroupingTestCase { @Test public void requireThatLevelAccessorsWork() { Grouping grouping = new Grouping(); - assertEquals(Collections.emptyList(), grouping.getLevels()); + assertEquals(List.of(), grouping.getLevels()); try { grouping.addLevel(null); fail(); @@ -137,10 +135,10 @@ public class GroupingTestCase { } GroupingLevel level = new GroupingLevel(); grouping.addLevel(level); - assertEquals(Arrays.asList(level), grouping.getLevels()); + assertEquals(List.of(level), grouping.getLevels()); Grouping other = new Grouping(); - assertFalse(grouping.equals(other)); + assertNotEquals(grouping, other); other.addLevel(level); assertEquals(grouping, other); @@ -155,8 +153,8 @@ public class GroupingTestCase { @Test public void requireThatEqualsIsImplemented() { - assertFalse(new Grouping().equals(new Object())); - assertTrue(new Grouping().equals(new Grouping())); + assertNotEquals(new Grouping(), new Object()); + assertEquals(new Grouping(), new Grouping()); } @Test diff --git a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/MergeTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/MergeTestCase.java index 610352ff236..838a4d738ac 100755..100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/MergeTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/MergeTestCase.java @@ -13,7 +13,6 @@ import com.yahoo.searchlib.expression.MultiplyFunctionNode; import com.yahoo.searchlib.expression.StringResultNode; import org.junit.Test; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; @@ -725,20 +724,20 @@ public class MergeTestCase { } private static void assertMerge(Grouping request, Group lhs, Group rhs, Group expect) { - assertMerge(Arrays.asList(request.clone().setRoot(lhs.clone()), + assertMerge(List.of(request.clone().setRoot(lhs.clone()), request.clone().setRoot(rhs.clone())), expect); } private static void assertMerge(Grouping request, Group a, Group b, Group c, Group expect) { - assertMerge(Arrays.asList(request.clone().setRoot(a.clone()), + assertMerge(List.of(request.clone().setRoot(a.clone()), request.clone().setRoot(b.clone()), request.clone().setRoot(c.clone())), expect); } private static void assertMerge(Grouping lhs, Grouping rhs, Group expect) { - assertMerge(Arrays.asList(lhs, rhs), expect); + assertMerge(List.of(lhs, rhs), expect); } private static void assertMerge(List<Grouping> groupingList, Group expect) { diff --git a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/NormalSketchTest.java b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/NormalSketchTest.java index d5269611b53..8e54c4598a0 100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/NormalSketchTest.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/NormalSketchTest.java @@ -4,7 +4,6 @@ package com.yahoo.searchlib.aggregation.hll; import com.yahoo.vespa.objects.BufferSerializer; import org.junit.Test; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; @@ -98,7 +97,7 @@ public class NormalSketchTest { NormalSketch sketch = new NormalSketch(10); // Aggregate multiple values - sketch.aggregate(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); + sketch.aggregate(List.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); for (int i = 0; i < 10; i++) { assertBucketEquals(sketch, i, 23); } diff --git a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/SketchUtils.java b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/SketchUtils.java index 9bec86c928b..5bf5294a828 100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/SketchUtils.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/aggregation/hll/SketchUtils.java @@ -1,7 +1,7 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.searchlib.aggregation.hll; -import java.util.Arrays; +import java.util.List; import static org.junit.Assert.assertEquals; @@ -16,13 +16,13 @@ public class SketchUtils { public static SparseSketch createSparseSketch(Integer... values) { SparseSketch sketch = new SparseSketch(); - sketch.aggregate(Arrays.asList(values)); + sketch.aggregate(List.of(values)); return sketch; } public static NormalSketch createNormalSketch(Integer... values) { NormalSketch sketch = new NormalSketch(); - sketch.aggregate(Arrays.asList(values)); + sketch.aggregate(List.of(values)); return sketch; } diff --git a/searchlib/src/test/java/com/yahoo/searchlib/expression/IntegerResultNodeTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/expression/IntegerResultNodeTestCase.java index c765714a4ab..45d809dcd8a 100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/expression/IntegerResultNodeTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/expression/IntegerResultNodeTestCase.java @@ -4,7 +4,6 @@ package com.yahoo.searchlib.expression; import org.junit.Test; import java.lang.reflect.InvocationTargetException; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertArrayEquals; @@ -18,7 +17,7 @@ import static org.junit.Assert.assertTrue; public class IntegerResultNodeTestCase extends ResultNodeTest { List<NumericResultNode> getResultNodes(long startvalue) { - return Arrays.asList(new Int8ResultNode((byte)startvalue), + return List.of(new Int8ResultNode((byte)startvalue), new Int16ResultNode((short)startvalue), new Int32ResultNode((int)startvalue), new IntegerResultNode(startvalue)); diff --git a/searchlib/src/test/java/com/yahoo/searchlib/expression/ObjectVisitorTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/expression/ObjectVisitorTestCase.java index 3c224d06cc3..1346577569b 100755..100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/expression/ObjectVisitorTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/expression/ObjectVisitorTestCase.java @@ -4,6 +4,7 @@ package com.yahoo.searchlib.expression; import com.yahoo.vespa.objects.ObjectDumper; import org.junit.Test; + import java.util.Arrays; import static org.junit.Assert.assertEquals; @@ -18,38 +19,46 @@ public class ObjectVisitorTestCase { assertDump("test: <NULL>\n", null); assertDump("test: 1\n", 1); assertDump("test: 'foo'\n", "foo"); - assertDump("test: List {\n" + - " [0]: 'foo'\n" + - " [1]: 69\n" + - " [2]: <NULL>\n" + - "}\n", + assertDump(""" + test: List { + [0]: 'foo' + [1]: 69 + [2]: <NULL> + } + """, Arrays.asList("foo", 69, null)); - assertDump("test: String[] {\n" + - " [0]: 'foo'\n" + - " [1]: 'bar'\n" + - " [2]: 'baz'\n" + - "}\n", + assertDump(""" + test: String[] { + [0]: 'foo' + [1]: 'bar' + [2]: 'baz' + } + """, new String[] { "foo", "bar", "baz" }); - assertDump("test: IntegerResultNode {\n" + - " classId: 16491\n" + - " value: 5\n" + - "}\n", + assertDump(""" + test: IntegerResultNode { + classId: 16491 + value: 5 + } + """, new IntegerResultNode(5)); - assertDump("test: FixedWidthBucketFunctionNode {\n" + - " classId: 16461\n" + - " result: <NULL>\n" + - " args: List {\n" + - " [0]: AttributeNode {\n" + - " classId: 16439\n" + - " result: <NULL>\n" + - " attribute: 'foo'\n" + - " }\n" + - " }\n" + - " width: IntegerResultNode {\n" + - " classId: 16491\n" + - " value: 5\n" + - " }\n" + - "}\n", + assertDump(""" + test: FixedWidthBucketFunctionNode { + classId: 16461 + result: <NULL> + args: List { + [0]: AttributeNode { + classId: 16439 + result: <NULL> + attribute: 'foo' + } + } + width: IntegerResultNode { + classId: 16491 + value: 5 + } + } + """, new FixedWidthBucketFunctionNode(new IntegerResultNode(5), new AttributeNode("foo"))); } diff --git a/searchlib/src/test/java/com/yahoo/searchlib/expression/TimeStampFunctionTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/expression/TimeStampFunctionTestCase.java index 69cea09df81..188603749e2 100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/expression/TimeStampFunctionTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/expression/TimeStampFunctionTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.searchlib.expression; import org.junit.Test; -import java.util.Arrays; +import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -17,7 +17,7 @@ public class TimeStampFunctionTestCase { public void requireThatAccessorsWork() { ExpressionNode arg = new AttributeNode("foo"); for (TimeStampFunctionNode.TimePart part : TimeStampFunctionNode.TimePart.values()) { - for (Boolean gmt : Arrays.asList(true, false)) { + for (Boolean gmt : List.of(true, false)) { TimeStampFunctionNode node = new TimeStampFunctionNode(arg, part, gmt); assertSame(arg, node.getArg()); assertEquals(part, node.getTimePart()); diff --git a/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/FeatureListTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/FeatureListTestCase.java index 8de36ee1ec1..0af105885ec 100755..100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/FeatureListTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/FeatureListTestCase.java @@ -8,7 +8,6 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.Reader; import java.io.StringReader; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; @@ -22,37 +21,37 @@ public class FeatureListTestCase { @Test public void requireThatFeatureListFromStringWorks() throws ParseException { assertFromString("attribute(foo).out", - Arrays.asList("attribute(foo).out")); + List.of("attribute(foo).out")); assertFromString("attribute(foo).out attribute ( bar ) . out", - Arrays.asList("attribute(foo).out", "attribute(bar).out")); + List.of("attribute(foo).out", "attribute(bar).out")); assertFromString("foo\n bar\n \t \t \n baz \n", - Arrays.asList("foo", "bar", "baz")); + List.of("foo", "bar", "baz")); assertFromString("attribute attribute(foo) attribute(foo).out attribute(bar).out.out", - Arrays.asList("attribute", "attribute(foo)", "attribute(foo).out", "attribute(bar).out.out")); + List.of("attribute", "attribute(foo)", "attribute(foo).out", "attribute(bar).out.out")); } @Test public void requireThatFeatureListFromReaderWorks() throws ParseException { assertFromReader(new StringReader("attribute(foo).out"), - Arrays.asList("attribute(foo).out")); + List.of("attribute(foo).out")); assertFromReader(new StringReader("attribute(foo).out attribute ( bar ) . out"), - Arrays.asList("attribute(foo).out", "attribute(bar).out")); + List.of("attribute(foo).out", "attribute(bar).out")); assertFromReader(new StringReader("foo\n bar\n \t \t \n baz \n"), - Arrays.asList("foo", "bar", "baz")); + List.of("foo", "bar", "baz")); assertFromReader(new StringReader("attribute attribute(foo) attribute(foo).out attribute(bar).out.out"), - Arrays.asList("attribute", "attribute(foo)", "attribute(foo).out", "attribute(bar).out.out")); + List.of("attribute", "attribute(foo)", "attribute(foo).out", "attribute(bar).out.out")); } @Test public void requireThatFeatureListFromFileWorks() throws ParseException, FileNotFoundException { assertFromFile(new File("src/test/files/features01.expression"), - Arrays.asList("attribute(foo).out")); + List.of("attribute(foo).out")); assertFromFile(new File("src/test/files/features02.expression"), - Arrays.asList("attribute(foo).out", "attribute(bar).out")); + List.of("attribute(foo).out", "attribute(bar).out")); assertFromFile(new File("src/test/files/features03.expression"), - Arrays.asList("foo", "bar", "baz")); + List.of("foo", "bar", "baz")); assertFromFile(new File("src/test/files/features04.expression"), - Arrays.asList("attribute", "attribute(foo)", "attribute(foo).out", "attribute(bar).out.out")); + List.of("attribute", "attribute(foo)", "attribute(foo).out", "attribute(bar).out.out")); } public void assertFromString(String input, List<String> expected) throws ParseException { diff --git a/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/RankingExpressionTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/RankingExpressionTestCase.java index 8d60f893c7c..13714af8324 100755..100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/RankingExpressionTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/RankingExpressionTestCase.java @@ -23,7 +23,6 @@ import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; @@ -121,28 +120,28 @@ public class RankingExpressionTestCase { @Test public void testSerialization() throws ParseException { List<ExpressionFunction> functions = new ArrayList<>(); - functions.add(new ExpressionFunction("foo", Arrays.asList("arg1", "arg2"), new RankingExpression("min(arg1, pow(arg2, 2))"))); - functions.add(new ExpressionFunction("bar", Arrays.asList("arg1", "arg2"), new RankingExpression("arg1 * arg1 + 2 * arg1 * arg2 + arg2 * arg2"))); - functions.add(new ExpressionFunction("baz", Arrays.asList("arg1", "arg2"), new RankingExpression("foo(1, 2) / bar(arg1, arg2)"))); + functions.add(new ExpressionFunction("foo", List.of("arg1", "arg2"), new RankingExpression("min(arg1, pow(arg2, 2))"))); + functions.add(new ExpressionFunction("bar", List.of("arg1", "arg2"), new RankingExpression("arg1 * arg1 + 2 * arg1 * arg2 + arg2 * arg2"))); + functions.add(new ExpressionFunction("baz", List.of("arg1", "arg2"), new RankingExpression("foo(1, 2) / bar(arg1, arg2)"))); functions.add(new ExpressionFunction("cox", null, new RankingExpression("10 + 08 * 1977"))); - assertSerialization(Arrays.asList( + assertSerialization(List.of( "rankingExpression(foo@e2dc17a89864aed0.12232eb692c6c502) + rankingExpression(foo@af74e3fd9070bd18.a368ed0a5ba3a5d0) * rankingExpression(foo@dbab346efdad5362.e5c39e42ebd91c30)", "min(5,pow(rankingExpression(foo@d1d1417259cdc651.573bbcd4be18f379),2))", "min(6,pow(7,2))", "min(1,pow(2,2))", "min(3,pow(4,2))", "min(rankingExpression(foo@84951be88255b0ec.d0303e061b36fab8),pow(8,2))"), "foo(1,2) + foo(3,4) * foo(5, foo(foo(6, 7), 8))", functions); - assertSerialization(Arrays.asList( + assertSerialization(List.of( "rankingExpression(foo@e2dc17a89864aed0.12232eb692c6c502) + rankingExpression(bar@af74e3fd9070bd18.a368ed0a5ba3a5d0)", "min(1,pow(2,2))", "3 * 3 + 2 * 3 * 4 + 4 * 4"), "foo(1, 2) + bar(3, 4)", functions); - assertSerialization(Arrays.asList( + assertSerialization(List.of( "rankingExpression(baz@e2dc17a89864aed0.12232eb692c6c502)", "min(1,pow(2,2))", "rankingExpression(foo@e2dc17a89864aed0.12232eb692c6c502) / rankingExpression(bar@e2dc17a89864aed0.12232eb692c6c502)", "1 * 1 + 2 * 1 * 2 + 2 * 2"), "baz(1, 2)", functions); - assertSerialization(Arrays.asList( + assertSerialization(List.of( "rankingExpression(cox)", "10 + 8 * 1977"), "cox", functions ); @@ -237,8 +236,8 @@ public class RankingExpressionTestCase { String expRhs = "(rankingExpression(log10tweetage) * rankingExpression(log10tweetage) * " + "rankingExpression(log10tweetage)) + 5.0 * attribute(ythl)"; - assertSerialization(Arrays.asList(expLhs + " + " + expRhs, "69"), lhs + " + " + rhs, functions); - assertSerialization(Arrays.asList(expLhs + " - " + expRhs, "69"), lhs + " - " + rhs, functions); + assertSerialization(List.of(expLhs + " + " + expRhs, "69"), lhs + " + " + rhs, functions); + assertSerialization(List.of(expLhs + " - " + expRhs, "69"), lhs + " - " + rhs, functions); } @Test diff --git a/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/rule/ArgumentsTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/rule/ArgumentsTestCase.java index df91c78c1b4..af6e4f1b9a9 100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/rule/ArgumentsTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/rule/ArgumentsTestCase.java @@ -3,8 +3,8 @@ package com.yahoo.searchlib.rankingexpression.rule; import org.junit.Test; -import java.util.Arrays; import java.util.Collections; +import java.util.List; import static org.junit.Assert.*; @@ -23,7 +23,7 @@ public class ArgumentsTestCase { var foo = new ReferenceNode("foo"); var bar = new ReferenceNode("bar"); - args = new Arguments(Arrays.asList(foo, bar)); + args = new Arguments(List.of(foo, bar)); assertEquals(2, args.expressions().size()); assertSame(foo, args.expressions().get(0)); assertSame(bar, args.expressions().get(1)); @@ -31,12 +31,12 @@ public class ArgumentsTestCase { @Test public void requireThatHashCodeAndEqualsWork() { - Arguments arg1 = new Arguments(Arrays.asList(new ReferenceNode("foo"), new ReferenceNode("bar"))); - Arguments arg2 = new Arguments(Arrays.asList(new ReferenceNode("foo"), new ReferenceNode("bar"))); - Arguments arg3 = new Arguments(Arrays.asList(new ReferenceNode("foo"))); + Arguments arg1 = new Arguments(List.of(new ReferenceNode("foo"), new ReferenceNode("bar"))); + Arguments arg2 = new Arguments(List.of(new ReferenceNode("foo"), new ReferenceNode("bar"))); + Arguments arg3 = new Arguments(List.of(new ReferenceNode("foo"))); assertEquals(arg1.hashCode(), arg2.hashCode()); - assertTrue(arg1.equals(arg2)); - assertFalse(arg2.equals(arg3)); + assertEquals(arg1, arg2); + assertNotEquals(arg2, arg3); } } diff --git a/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/rule/ReferenceNodeTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/rule/ReferenceNodeTestCase.java index 7d0e0d6da84..10a37ff28df 100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/rule/ReferenceNodeTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/rule/ReferenceNodeTestCase.java @@ -3,7 +3,6 @@ package com.yahoo.searchlib.rankingexpression.rule; import org.junit.Test; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; @@ -15,7 +14,7 @@ public class ReferenceNodeTestCase { @Test public void requireThatAccessorsWork() { - ReferenceNode node = new ReferenceNode("foo", Arrays.asList(new ReferenceNode("bar"), new ReferenceNode("baz")), "cox"); + ReferenceNode node = new ReferenceNode("foo", List.of(new ReferenceNode("bar"), new ReferenceNode("baz")), "cox"); assertEquals("foo", node.getName()); List<ExpressionNode> args = node.getArguments().expressions(); assertEquals(2, args.size()); @@ -23,10 +22,10 @@ public class ReferenceNodeTestCase { assertEquals(new ReferenceNode("baz"), args.get(1)); assertEquals("cox", node.getOutput()); - node = node.setArguments(Arrays.<ExpressionNode>asList(new ReferenceNode("bar@"))); + node = node.setArguments(List.of(new ReferenceNode("bar@"))); assertEquals(new ReferenceNode("bar@"), node.getArguments().expressions().get(0)); - node = node.setArguments(Arrays.<ExpressionNode>asList(new ReferenceNode("baz$"))); + node = node.setArguments(List.of(new ReferenceNode("baz$"))); assertEquals(new ReferenceNode("baz$"), node.getArguments().expressions().get(0)); node = node.setOutput("cox'"); diff --git a/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/transform/SimplifierTestCase.java b/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/transform/SimplifierTestCase.java index 0f367bb5425..7736b0e9ac7 100644 --- a/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/transform/SimplifierTestCase.java +++ b/searchlib/src/test/java/com/yahoo/searchlib/rankingexpression/transform/SimplifierTestCase.java @@ -12,7 +12,7 @@ import com.yahoo.searchlib.rankingexpression.rule.ConstantNode; import com.yahoo.searchlib.rankingexpression.rule.NegativeNode; import org.junit.Test; -import java.util.Collections; +import java.util.Map; import static org.junit.Assert.*; @@ -24,7 +24,7 @@ public class SimplifierTestCase { @Test public void testSimplify() throws ParseException { Simplifier s = new Simplifier(); - TransformContext c = new TransformContext(Collections.emptyMap(), new MapTypeContext()); + TransformContext c = new TransformContext(Map.of(), new MapTypeContext()); assertEquals("a + b", s.transform(new RankingExpression("a + b"), c).toString()); assertEquals("6.5", s.transform(new RankingExpression("1.0 + 2.0 + 3.5"), c).toString()); assertEquals("6.5", s.transform(new RankingExpression("1.0 + ( 2.0 + 3.5 )"), c).toString()); @@ -48,7 +48,7 @@ public class SimplifierTestCase { @Test public void testNaNExpression() throws ParseException { Simplifier s = new Simplifier(); - TransformContext c = new TransformContext(Collections.emptyMap(), new MapTypeContext()); + TransformContext c = new TransformContext(Map.of(), new MapTypeContext()); assertEquals("0 / 0", s.transform(new RankingExpression("0/0"), c).toString()); assertEquals("1 + 0.0 / 0.0", s.transform(new RankingExpression("1 + (1-1)/(2-2)"), c).toString()); } @@ -56,7 +56,7 @@ public class SimplifierTestCase { @Test public void testSimplifyComplexExpression() throws ParseException { RankingExpression initial = new RankingExpression("sqrt(if (if (INFERRED * 0.9 < INFERRED, GMP, (1 + 1.1) * INFERRED) < INFERRED * INFERRED - INFERRED, if (GMP < 85.80799542793133 * GMP, INFERRED, if (GMP < GMP, tanh(INFERRED), log(76.89956221113943))), tanh(tanh(INFERRED))) * sqrt(sqrt(GMP + INFERRED)) * GMP ) + 13.5 * (1 - GMP) * pow(GMP * 0.1, 2 + 1.1 * 0)"); - TransformContext c = new TransformContext(Collections.emptyMap(), new MapTypeContext()); + TransformContext c = new TransformContext(Map.of(), new MapTypeContext()); RankingExpression simplified = new Simplifier().transform(initial, c); Context context = new MapContext(); @@ -81,7 +81,7 @@ public class SimplifierTestCase { @Test public void testParenthesisPreservation() throws ParseException { Simplifier s = new Simplifier(); - TransformContext c = new TransformContext(Collections.emptyMap(), new MapTypeContext()); + TransformContext c = new TransformContext(Map.of(), new MapTypeContext()); CompositeNode transformed = (CompositeNode)s.transform(new RankingExpression("a + (b + c) / 100000000.0"), c).getRoot(); assertEquals("a + (b + c) / 1.0E8", transformed.toString()); } @@ -89,7 +89,7 @@ public class SimplifierTestCase { @Test public void testOptimizingNegativeConstants() throws ParseException { Simplifier s = new Simplifier(); - TransformContext c = new TransformContext(Collections.emptyMap(), new MapTypeContext()); + TransformContext c = new TransformContext(Map.of(), new MapTypeContext()); assertEquals("-3", s.transform(new RankingExpression("-3"), c).toString()); assertEquals("-9.0", s.transform(new RankingExpression("-3 + -6"), c).toString()); assertEquals("-a", s.transform(new RankingExpression("-a"), c).toString()); diff --git a/searchlib/src/tests/queryeval/flow/queryeval_flow_test.cpp b/searchlib/src/tests/queryeval/flow/queryeval_flow_test.cpp index 181c591ab20..5eb3a2ebf47 100644 --- a/searchlib/src/tests/queryeval/flow/queryeval_flow_test.cpp +++ b/searchlib/src/tests/queryeval/flow/queryeval_flow_test.cpp @@ -7,6 +7,7 @@ constexpr size_t loop_cnt = 64; constexpr size_t max_work = 1; // 500'000'000; +constexpr bool dump_unexpected = false; constexpr bool verbose = false; using namespace search::queryeval; @@ -40,7 +41,7 @@ double dual_ordered_cost_of(const std::vector<FlowStats> &data, InFlow in_flow, any_flow.update_cost(total_cost, child_cost); any_flow.add(item.estimate); } - EXPECT_EQ(total_cost, result); + EXPECT_DOUBLE_EQ(total_cost, result); return result; } @@ -174,7 +175,7 @@ void verify_flow(auto flow, const std::vector<double> &est_list, const std::vect AnyFlow any_flow = AnyFlow::create<decltype(flow)>(InFlow(flow.strict(), flow.flow())); ASSERT_EQ(est_list.size() + 1, expect.size()); for (size_t i = 0; i < est_list.size(); ++i) { - EXPECT_EQ(any_flow.flow(), flow.flow()); + EXPECT_DOUBLE_EQ(any_flow.flow(), flow.flow()); EXPECT_EQ(any_flow.strict(), flow.strict()); EXPECT_DOUBLE_EQ(flow.flow(), expect[i].flow); EXPECT_EQ(flow.strict(), expect[i].strict); @@ -182,7 +183,7 @@ void verify_flow(auto flow, const std::vector<double> &est_list, const std::vect any_flow.add(est_list[i]); flow.add(est_list[i]); } - EXPECT_EQ(any_flow.flow(), flow.flow()); + EXPECT_DOUBLE_EQ(any_flow.flow(), flow.flow()); EXPECT_EQ(any_flow.strict(), flow.strict()); EXPECT_DOUBLE_EQ(flow.flow(), expect.back().flow); EXPECT_EQ(flow.strict(), expect.back().strict); @@ -356,10 +357,10 @@ TEST(FlowTest, optimal_and_flow) { double min_cost = AndFlow::cost_of(data, strict); double max_cost = 0.0; AndFlow::sort(data, strict); - EXPECT_EQ(ordered_cost_of<AndFlow>(data, strict, false), min_cost); + EXPECT_DOUBLE_EQ(ordered_cost_of<AndFlow>(data, strict, false), min_cost); auto check = [&](const std::vector<FlowStats> &my_data) noexcept { double my_cost = ordered_cost_of<AndFlow>(my_data, strict, false); - EXPECT_LE(min_cost, my_cost); + EXPECT_LE(min_cost, my_cost + 1e-9); max_cost = std::max(max_cost, my_cost); }; each_perm(data, check); @@ -379,7 +380,7 @@ TEST(FlowTest, optimal_or_flow) { double min_cost = OrFlow::cost_of(data, strict); double max_cost = 0.0; OrFlow::sort(data, strict); - EXPECT_EQ(ordered_cost_of<OrFlow>(data, strict, false), min_cost); + EXPECT_DOUBLE_EQ(ordered_cost_of<OrFlow>(data, strict, false), min_cost); auto check = [&](const std::vector<FlowStats> &my_data) noexcept { double my_cost = ordered_cost_of<OrFlow>(my_data, strict, false); EXPECT_LE(min_cost, my_cost + 1e-9); @@ -451,7 +452,7 @@ void test_strict_AND_sort_strategy(auto my_sort) { flow.add(item.estimate); total_cost += child_cost; } - EXPECT_EQ(total_cost, ordered_cost_of<AndFlow>(list, true, true)); + EXPECT_DOUBLE_EQ(total_cost, ordered_cost_of<AndFlow>(list, true, true)); fprintf(stderr, " total cost: %10f\n", total_cost); }; auto verify_order = [&](const std::vector<FlowStats> &list){ @@ -515,10 +516,7 @@ void test_strict_AND_sort_strategy(auto my_sort) { }; each_perm(data, check); double rel_err = 0.0; - double cost_range = (max_cost - min_cost); - if (cost_range > 1e-9) { - rel_err = (est_cost - min_cost) / cost_range; - } + rel_err = (est_cost - min_cost) / min_cost; if (rel_err > max_rel_err) { max_rel_err = rel_err; my_worst_order = my_order; @@ -526,7 +524,7 @@ void test_strict_AND_sort_strategy(auto my_sort) { } sum_rel_err += rel_err; errs.push_back(rel_err); - if (verbose && !verify_order(best_order)) { + if (dump_unexpected && !verify_order(best_order)) { fprintf(stderr, " BEST ORDER IS UNEXPECTED:\n"); dump_flow(best_order, best_order); fprintf(stderr, " UNEXPECTED case, my_order:\n"); @@ -551,60 +549,12 @@ TEST(FlowTest, strict_and_with_allow_force_strict_basic_order) { test_strict_AND_sort_strategy(my_sort); } -TEST(FlowTest, strict_and_with_allow_force_strict_incremental_strict_selection) { - auto my_sort = [](auto &data) { - AndFlow::sort(data, true); - for (size_t next = 1; (next + 1) < data.size(); ++next) { - auto [idx, score] = flow::select_forced_strict_and_child(flow::DirectAdapter(), data, next); - if (score >= 0.0) { - break; - } - auto pos = data.begin() + idx; - std::rotate(data.begin() + next, pos, pos + 1); - } - }; - test_strict_AND_sort_strategy(my_sort); -} - -TEST(FlowTest, strict_and_with_allow_force_strict_incremental_strict_selection_with_strict_re_sorting) { - auto my_sort = [](auto &data) { - AndFlow::sort(data, true); - size_t strict_cnt = 1; - for (; strict_cnt < data.size(); ++strict_cnt) { - auto [idx, score] = flow::select_forced_strict_and_child(flow::DirectAdapter(), data, strict_cnt); - if (score >= 0.0) { - break; - } - auto pos = data.begin() + idx; - std::rotate(data.begin() + strict_cnt, pos, pos + 1); - } - std::sort(data.begin(), data.begin() + strict_cnt, - [](const auto &a, const auto &b){ return (a.estimate < b.estimate); }); - }; - test_strict_AND_sort_strategy(my_sort); -} - -TEST(FlowTest, strict_and_with_allow_force_strict_incremental_strict_selection_with_order) { - auto my_sort = [](auto &data) { - AndFlow::sort(data, true); - for (size_t next = 1; next < data.size(); ++next) { - auto [idx, target, score] = flow::select_forced_strict_and_child_with_order(flow::DirectAdapter(), data, next); - if (score >= 0.0) { - break; - } - auto pos = data.begin() + idx; - std::rotate(data.begin() + target, pos, pos + 1); - } - }; - test_strict_AND_sort_strategy(my_sort); -} - -TEST(FlowTest, strict_and_with_allow_force_strict_incremental_strict_selection_with_destructive_order) { +TEST(FlowTest, strict_and_with_allow_force_strict_incremental_strict_selection_destructive_order_max_3_extra_strict) { auto my_sort = [](auto &data) { AndFlow::sort(data, true); - for (size_t next = 1; next < data.size(); ++next) { - auto [idx, target, score] = flow::select_forced_strict_and_child_with_destructive_order(flow::DirectAdapter(), data, next); - if (score >= 0.0) { + for (size_t next = 1; next <= 3 && next < data.size(); ++next) { + auto [idx, target, diff] = flow::select_forced_strict_and_child(flow::DirectAdapter(), data, next); + if (diff >= 0.0) { break; } auto pos = data.begin() + idx; diff --git a/searchlib/src/tests/queryeval/iterator_benchmark/attribute_ctx_builder.cpp b/searchlib/src/tests/queryeval/iterator_benchmark/attribute_ctx_builder.cpp index 6a2b306522d..5a0bda49b98 100644 --- a/searchlib/src/tests/queryeval/iterator_benchmark/attribute_ctx_builder.cpp +++ b/searchlib/src/tests/queryeval/iterator_benchmark/attribute_ctx_builder.cpp @@ -18,30 +18,71 @@ namespace { template <typename AttributeType, bool is_string, bool is_multivalue> void +update_attribute(AttributeType& attr, uint32_t docid, uint32_t value) +{ + if constexpr (is_string) { + if constexpr (is_multivalue) { + attr.append(docid, std::to_string(value), random_int(1, 100)); + } else { + attr.update(docid, std::to_string(value)); + } + } else { + if constexpr (is_multivalue) { + attr.append(docid, value, random_int(1, 100)); + } else { + attr.update(docid, value); + } + } +} + +template <typename AttributeType, bool is_string, bool is_multivalue> +void populate_attribute(AttributeType& attr, uint32_t docid_limit, const HitSpecs& hit_specs) { for (auto spec : hit_specs) { auto docids = random_docids(docid_limit, spec.num_hits); docids->foreach_truebit([&](uint32_t docid) { - if constexpr (is_string) { - if constexpr (is_multivalue) { - attr.append(docid, std::to_string(spec.term_value), random_int(1, 100)); - } else { - attr.update(docid, std::to_string(spec.term_value)); - } - } else { - if constexpr (is_multivalue) { - attr.append(docid, spec.term_value, random_int(1, 100)); - } else { - attr.update(docid, spec.term_value); - } - } + update_attribute<AttributeType, is_string, is_multivalue>(attr, docid, spec.term_value); }); } } +template <typename AttributeType, bool is_string, bool is_multivalue> +void +populate_attribute(AttributeType& attr, const std::vector<uint32_t>& values) +{ + for (uint32_t docid = 1; docid < values.size(); ++docid) { + uint32_t value = values[docid]; + if (value == 0) { + continue; + } + update_attribute<AttributeType, is_string, is_multivalue>(attr, docid, value); + } +} + +template <typename AttributeType, bool is_string, bool is_multivalue> +void +populate_attribute(AttributeType& attr, uint32_t docid_limit, const HitSpecs& hit_specs, bool disjunct_terms) +{ + if (disjunct_terms) { + // Ensure that each term in HitSpecs is matched by a disjunct (random) subset of docids. + std::vector<uint32_t> values(docid_limit, 0); + uint32_t docid = 1; + for (auto spec : hit_specs) { + assert((docid + spec.num_hits) <= docid_limit); + std::fill_n(values.begin() + docid, spec.num_hits, spec.term_value); + docid += spec.num_hits; + } + std::shuffle(values.begin() + 1, values.end(), get_gen()); + populate_attribute<AttributeType, is_string, is_multivalue>(attr, values); + } else { + // For each term in HitSpecs we draw a new random set of docids that will match this term value. + populate_attribute<AttributeType, is_string, is_multivalue>(attr, docid_limit, hit_specs); + } +} + AttributeVector::SP -make_attribute(const Config& cfg, vespalib::stringref field_name, uint32_t num_docs, const HitSpecs& hit_specs) +make_attribute(const Config& cfg, vespalib::stringref field_name, uint32_t num_docs, const HitSpecs& hit_specs, bool disjunct_terms) { auto attr = AttributeFactory::createAttribute(field_name, cfg); attr->addReservedDoc(); @@ -52,16 +93,16 @@ make_attribute(const Config& cfg, vespalib::stringref field_name, uint32_t num_d if (attr->isStringType()) { auto& real = dynamic_cast<StringAttribute&>(*attr); if (is_multivalue) { - populate_attribute<StringAttribute, true, true>(real, docid_limit, hit_specs); + populate_attribute<StringAttribute, true, true>(real, docid_limit, hit_specs, disjunct_terms); } else { - populate_attribute<StringAttribute, true, false>(real, docid_limit, hit_specs); + populate_attribute<StringAttribute, true, false>(real, docid_limit, hit_specs, disjunct_terms); } } else { auto& real = dynamic_cast<IntegerAttribute&>(*attr); if (is_multivalue) { - populate_attribute<IntegerAttribute, false, true>(real, docid_limit, hit_specs); + populate_attribute<IntegerAttribute, false, true>(real, docid_limit, hit_specs, disjunct_terms); } else { - populate_attribute<IntegerAttribute, false, false>(real, docid_limit, hit_specs); + populate_attribute<IntegerAttribute, false, false>(real, docid_limit, hit_specs, disjunct_terms); } } attr->commit(true); @@ -90,9 +131,9 @@ AttributeContextBuilder::AttributeContextBuilder() } void -AttributeContextBuilder::add(const search::attribute::Config& cfg, vespalib::stringref field_name, uint32_t num_docs, const HitSpecs& hit_specs) +AttributeContextBuilder::add(const search::attribute::Config& cfg, vespalib::stringref field_name, uint32_t num_docs, const HitSpecs& hit_specs, bool disjunct_terms) { - auto attr = make_attribute(cfg, field_name, num_docs, hit_specs); + auto attr = make_attribute(cfg, field_name, num_docs, hit_specs, disjunct_terms); _ctx->add(std::move(attr)); } diff --git a/searchlib/src/tests/queryeval/iterator_benchmark/attribute_ctx_builder.h b/searchlib/src/tests/queryeval/iterator_benchmark/attribute_ctx_builder.h index e4a58c91668..7e5236e43be 100644 --- a/searchlib/src/tests/queryeval/iterator_benchmark/attribute_ctx_builder.h +++ b/searchlib/src/tests/queryeval/iterator_benchmark/attribute_ctx_builder.h @@ -19,7 +19,7 @@ private: public: AttributeContextBuilder(); - void add(const search::attribute::Config& cfg, vespalib::stringref field_name, uint32_t num_docs, const HitSpecs& hit_specs); + void add(const search::attribute::Config& cfg, vespalib::stringref field_name, uint32_t num_docs, const HitSpecs& hit_specs, bool disjunct_terms); std::unique_ptr<BenchmarkSearchable> build(); }; diff --git a/searchlib/src/tests/queryeval/iterator_benchmark/benchmark_blueprint_factory.cpp b/searchlib/src/tests/queryeval/iterator_benchmark/benchmark_blueprint_factory.cpp index 516a819aae8..0496a0e6dc8 100644 --- a/searchlib/src/tests/queryeval/iterator_benchmark/benchmark_blueprint_factory.cpp +++ b/searchlib/src/tests/queryeval/iterator_benchmark/benchmark_blueprint_factory.cpp @@ -42,11 +42,11 @@ calc_hits_per_term(uint32_t num_docs, double op_hit_ratio, uint32_t children, Qu } std::unique_ptr<BenchmarkSearchable> -make_searchable(const FieldConfig& cfg, uint32_t num_docs, const HitSpecs& hit_specs) +make_searchable(const FieldConfig& cfg, uint32_t num_docs, const HitSpecs& hit_specs, bool disjunct_terms) { if (cfg.is_attr()) { AttributeContextBuilder builder; - builder.add(cfg.attr_cfg(), field_name, num_docs, hit_specs); + builder.add(cfg.attr_cfg(), field_name, num_docs, hit_specs, disjunct_terms); return builder.build(); } else { uint32_t docid_limit = num_docs + 1; @@ -159,14 +159,14 @@ private: public: MyFactory(const FieldConfig& field_cfg, QueryOperator query_op, uint32_t num_docs, uint32_t default_values_per_document, - double op_hit_ratio, uint32_t children); + double op_hit_ratio, uint32_t children, bool disjunct_children); std::unique_ptr<Blueprint> make_blueprint() override; }; MyFactory::MyFactory(const FieldConfig& field_cfg, QueryOperator query_op, uint32_t num_docs, uint32_t default_values_per_document, - double op_hit_ratio, uint32_t children) + double op_hit_ratio, uint32_t children, bool disjunct_children) : _query_op(query_op), _docid_limit(num_docs + 1), _terms(), @@ -174,9 +174,17 @@ MyFactory::MyFactory(const FieldConfig& field_cfg, QueryOperator query_op, { uint32_t hits_per_term = calc_hits_per_term(num_docs, op_hit_ratio, children, query_op); HitSpecs hit_specs(55555); - hit_specs.add(default_values_per_document, num_docs); + if (!disjunct_children) { + hit_specs.add(default_values_per_document, num_docs); + } _terms = hit_specs.add(children, hits_per_term); - _searchable = make_searchable(field_cfg, num_docs, hit_specs); + if (disjunct_children && default_values_per_document != 0) { + // This ensures that the remaining docids are populated with a "default value". + // Only a single default value is supported. + uint32_t op_num_hits = num_docs * op_hit_ratio; + hit_specs.add(1, num_docs - op_num_hits); + } + _searchable = make_searchable(field_cfg, num_docs, hit_specs, disjunct_children); } std::unique_ptr<Blueprint> @@ -190,9 +198,9 @@ MyFactory::make_blueprint() std::unique_ptr<BenchmarkBlueprintFactory> make_blueprint_factory(const FieldConfig& field_cfg, QueryOperator query_op, uint32_t num_docs, uint32_t default_values_per_document, - double op_hit_ratio, uint32_t children) + double op_hit_ratio, uint32_t children, bool disjunct_children) { - return std::make_unique<MyFactory>(field_cfg, query_op, num_docs, default_values_per_document, op_hit_ratio, children); + return std::make_unique<MyFactory>(field_cfg, query_op, num_docs, default_values_per_document, op_hit_ratio, children, disjunct_children); } } diff --git a/searchlib/src/tests/queryeval/iterator_benchmark/benchmark_blueprint_factory.h b/searchlib/src/tests/queryeval/iterator_benchmark/benchmark_blueprint_factory.h index d3e529fcd65..423f517ffb0 100644 --- a/searchlib/src/tests/queryeval/iterator_benchmark/benchmark_blueprint_factory.h +++ b/searchlib/src/tests/queryeval/iterator_benchmark/benchmark_blueprint_factory.h @@ -21,6 +21,6 @@ public: std::unique_ptr<BenchmarkBlueprintFactory> make_blueprint_factory(const FieldConfig& field_cfg, QueryOperator query_op, uint32_t num_docs, uint32_t default_values_per_document, - double op_hit_ratio, uint32_t children); + double op_hit_ratio, uint32_t children, bool disjunct_children); } diff --git a/searchlib/src/tests/queryeval/iterator_benchmark/common.cpp b/searchlib/src/tests/queryeval/iterator_benchmark/common.cpp index f17403bd33a..c67a5ee1074 100644 --- a/searchlib/src/tests/queryeval/iterator_benchmark/common.cpp +++ b/searchlib/src/tests/queryeval/iterator_benchmark/common.cpp @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "common.h" -#include <random> #include <sstream> using search::attribute::CollectionType; @@ -49,6 +48,8 @@ std::mt19937 gen(default_seed); } +std::mt19937& get_gen() { return gen; } + BitVector::UP random_docids(uint32_t docid_limit, uint32_t count) { diff --git a/searchlib/src/tests/queryeval/iterator_benchmark/common.h b/searchlib/src/tests/queryeval/iterator_benchmark/common.h index 45fd82b091c..bf16e6f51d7 100644 --- a/searchlib/src/tests/queryeval/iterator_benchmark/common.h +++ b/searchlib/src/tests/queryeval/iterator_benchmark/common.h @@ -5,6 +5,7 @@ #include <vespa/searchcommon/attribute/config.h> #include <vespa/searchcommon/common/schema.h> #include <vespa/searchlib/common/bitvector.h> +#include <random> #include <variant> namespace search::queryeval::test { @@ -78,6 +79,8 @@ public: auto end() const { return _specs.end(); } }; +std::mt19937& get_gen(); + BitVector::UP random_docids(uint32_t docid_limit, uint32_t count); int32_t random_int(int32_t a, int32_t b); diff --git a/searchlib/src/tests/queryeval/iterator_benchmark/iterator_benchmark_test.cpp b/searchlib/src/tests/queryeval/iterator_benchmark/iterator_benchmark_test.cpp index b08fde50d7c..c6dae52fd69 100644 --- a/searchlib/src/tests/queryeval/iterator_benchmark/iterator_benchmark_test.cpp +++ b/searchlib/src/tests/queryeval/iterator_benchmark/iterator_benchmark_test.cpp @@ -31,25 +31,22 @@ struct BenchmarkResult { uint32_t hits; FlowStats flow; double actual_cost; - double alt_cost; vespalib::string iterator_name; vespalib::string blueprint_name; - BenchmarkResult() : BenchmarkResult(0, 0, 0, {0, 0, 0}, 0, 0, "", "") {} - BenchmarkResult(double time_ms_in, uint32_t seeks_in, uint32_t hits_in, FlowStats flow_in, double actual_cost_in, double alt_cost_in, + BenchmarkResult() : BenchmarkResult(0, 0, 0, {0, 0, 0}, 0, "", "") {} + BenchmarkResult(double time_ms_in, uint32_t seeks_in, uint32_t hits_in, FlowStats flow_in, double actual_cost_in, const vespalib::string& iterator_name_in, const vespalib::string& blueprint_name_in) : time_ms(time_ms_in), seeks(seeks_in), hits(hits_in), flow(flow_in), actual_cost(actual_cost_in), - alt_cost(alt_cost_in), iterator_name(iterator_name_in), blueprint_name(blueprint_name_in) {} ~BenchmarkResult(); double ns_per_seek() const { return (time_ms / seeks) * 1000.0 * 1000.0; } double ms_per_actual_cost() const { return (time_ms / actual_cost); } - double ms_per_alt_cost() const { return (time_ms / alt_cost); } }; BenchmarkResult::~BenchmarkResult() = default; @@ -128,9 +125,6 @@ public: Stats ms_per_actual_cost_stats() const { return calc_stats([](const auto& res){ return res.ms_per_actual_cost(); }); } - Stats ms_per_alt_cost_stats() const { - return calc_stats([](const auto& res){ return res.ms_per_alt_cost(); }); - } }; std::string @@ -222,7 +216,7 @@ strict_search(BenchmarkBlueprintFactory& factory, uint32_t docid_limit) timer.after(); } FlowStats flow(ctx.blueprint->estimate(), ctx.blueprint->cost(), ctx.blueprint->strict_cost()); - return {timer.min_time() * 1000.0, hits + 1, hits, flow, flow.strict_cost, flow.strict_cost, get_class_name(*ctx.iterator), get_class_name(*ctx.blueprint)}; + return {timer.min_time() * 1000.0, hits + 1, hits, flow, flow.strict_cost, get_class_name(*ctx.iterator), get_class_name(*ctx.blueprint)}; } template <bool do_unpack> @@ -256,9 +250,7 @@ non_strict_search(BenchmarkBlueprintFactory& factory, uint32_t docid_limit, doub } FlowStats flow(ctx.blueprint->estimate(), ctx.blueprint->cost(), ctx.blueprint->strict_cost()); double actual_cost = flow.cost * filter_hit_ratio; - // This is an attempt to calculate an alternative actual cost for strict / posting list iterators that are used in a non-strict context. - double alt_cost = flow.strict_cost + 0.5 * filter_hit_ratio; - return {timer.min_time() * 1000.0, seeks, hits, flow, actual_cost, alt_cost, get_class_name(*ctx.iterator), get_class_name(*ctx.blueprint)}; + return {timer.min_time() * 1000.0, seeks, hits, flow, actual_cost, get_class_name(*ctx.iterator), get_class_name(*ctx.blueprint)}; } BenchmarkResult @@ -413,32 +405,30 @@ to_string(bool val) void print_result_header() { - std::cout << "| chn | f_ratio | o_ratio | a_ratio | f.est | f.cost | f.scost | hits | seeks | time_ms | act_cost | alt_cost | ns_per_seek | ms_per_act_cost | ms_per_alt_cost | iterator | blueprint |" << std::endl; + std::cout << "| chn | f_ratio | o_ratio | a_ratio | f.est | f.cost | f.scost | hits | seeks | time_ms | act_cost | ns_per_seek | ms_per_act_cost | iterator | blueprint |" << std::endl; } void print_result(const BenchmarkResult& res, uint32_t children, double op_hit_ratio, double filter_hit_ratio, uint32_t num_docs) { std::cout << std::fixed << std::setprecision(5) - << "| " << std::setw(4) << children + << "| " << std::setw(5) << children << " | " << std::setw(7) << filter_hit_ratio << " | " << std::setw(7) << op_hit_ratio << " | " << std::setw(7) << ((double) res.hits / (double) num_docs) << " | " << std::setw(6) << res.flow.estimate << std::setprecision(4) - << " | " << std::setw(7) << res.flow.cost + << " | " << std::setw(9) << res.flow.cost << " | " << std::setw(7) << res.flow.strict_cost << " | " << std::setw(8) << res.hits << " | " << std::setw(8) << res.seeks << std::setprecision(3) << " | " << std::setw(8) << res.time_ms << std::setprecision(4) - << " | " << std::setw(8) << res.actual_cost - << " | " << std::setw(8) << res.alt_cost + << " | " << std::setw(9) << res.actual_cost << std::setprecision(2) << " | " << std::setw(11) << res.ns_per_seek() << " | " << std::setw(15) << res.ms_per_actual_cost() - << " | " << std::setw(15) << res.ms_per_alt_cost() << " | " << res.iterator_name << " | " << res.blueprint_name << " |" << std::endl; } @@ -449,8 +439,7 @@ print_result(const BenchmarkCaseResult& result) std::cout << std::fixed << std::setprecision(3) << "summary: time_ms=" << result.time_ms_stats().to_string() << std::endl << " ns_per_seek=" << result.ns_per_seek_stats().to_string() << std::endl - << " ms_per_act_cost=" << result.ms_per_actual_cost_stats().to_string() << std::endl - << " ms_per_alt_cost=" << result.ms_per_alt_cost_stats().to_string() << std::endl << std::endl; + << " ms_per_act_cost=" << result.ms_per_actual_cost_stats().to_string() << std::endl << std::endl; } struct BenchmarkCase { @@ -534,6 +523,7 @@ struct BenchmarkCaseSetup { std::vector<uint32_t> child_counts; std::vector<double> filter_hit_ratios; uint32_t default_values_per_document; + bool disjunct_children; double filter_crossover_factor; BenchmarkCaseSetup(uint32_t num_docs_in, const BenchmarkCase& bcase_in, @@ -545,6 +535,7 @@ struct BenchmarkCaseSetup { child_counts(child_counts_in), filter_hit_ratios({1.0}), default_values_per_document(0), + disjunct_children(false), filter_crossover_factor(0.0) {} ~BenchmarkCaseSetup() {} @@ -561,6 +552,7 @@ struct BenchmarkSetup { bool force_strict; bool unpack_iterator; uint32_t default_values_per_document; + bool disjunct_children; double filter_crossover_factor; BenchmarkSetup(uint32_t num_docs_in, const std::vector<FieldConfig>& field_cfgs_in, @@ -578,6 +570,7 @@ struct BenchmarkSetup { force_strict(false), unpack_iterator(false), default_values_per_document(0), + disjunct_children(false), filter_crossover_factor(0.0) {} BenchmarkSetup(uint32_t num_docs_in, @@ -592,6 +585,7 @@ struct BenchmarkSetup { res.bcase.force_strict = force_strict; res.bcase.unpack_iterator = unpack_iterator; res.default_values_per_document = default_values_per_document; + res.disjunct_children = disjunct_children; if (!bcase.strict_context) { // Simulation of a filter is only relevant in a non-strict context. res.filter_hit_ratios = filter_hit_ratios; @@ -617,7 +611,7 @@ run_benchmark_case(const BenchmarkCaseSetup& setup) for (uint32_t children : setup.child_counts) { auto factory = make_blueprint_factory(setup.bcase.field_cfg, setup.bcase.query_op, setup.num_docs, setup.default_values_per_document, - op_hit_ratio, children); + op_hit_ratio, children, setup.disjunct_children); for (double filter_hit_ratio : setup.filter_hit_ratios) { if (filter_hit_ratio * setup.filter_crossover_factor <= op_hit_ratio) { auto res = benchmark_search(*factory, setup.num_docs + 1, @@ -726,6 +720,22 @@ TEST(IteratorBenchmark, analyze_term_search_in_fast_search_attributes) run_benchmarks(setup, global_summary); } +TEST(IteratorBenchmark, analyze_in_operator_non_strict) +{ + const std::vector<double> hit_ratios = {0.001, 0.01, 0.1, 0.2, 0.4, 0.6, 0.8}; + BenchmarkSetup setup(num_docs, {int32_fs}, {QueryOperator::In}, {false}, hit_ratios, {5, 9, 10, 100, 1000, 10000}); + setup.disjunct_children = true; + run_benchmarks(setup); +} + +TEST(IteratorBenchmark, analyze_in_operator_strict) +{ + const std::vector<double> hit_ratios = {0.001, 0.01, 0.1, 0.2, 0.4, 0.6, 0.8}; + BenchmarkSetup setup(num_docs, {int32_fs}, {QueryOperator::In}, {true}, hit_ratios, {5, 9, 10, 100, 1000, 10000}); + setup.disjunct_children = true; + run_benchmarks(setup); +} + TEST(IteratorBenchmark, analyze_complex_leaf_operators) { std::vector<FieldConfig> field_cfgs = {int32_array_fs}; @@ -764,18 +774,18 @@ TEST(IteratorBenchmark, or_benchmark) TEST(IteratorBenchmark, or_vs_filter_crossover) { - auto fixed_or = make_blueprint_factory(int32_array_fs, QueryOperator::Or, num_docs, 0, 0.1, 100); + auto fixed_or = make_blueprint_factory(int32_array_fs, QueryOperator::Or, num_docs, 0, 0.1, 100, false); auto variable_term = [](double rate) { - return make_blueprint_factory(int32_array_fs, QueryOperator::Term, num_docs, 0, rate, 1); + return make_blueprint_factory(int32_array_fs, QueryOperator::Term, num_docs, 0, rate, 1, false); }; analyze_crossover(*fixed_or, variable_term, num_docs + 1, false, 0.0001); } TEST(IteratorBenchmark, or_vs_filter_crossover_with_allow_force_strict) { - auto fixed_or = make_blueprint_factory(int32_array_fs, QueryOperator::Or, num_docs, 0, 0.1, 100); + auto fixed_or = make_blueprint_factory(int32_array_fs, QueryOperator::Or, num_docs, 0, 0.1, 100, false); auto variable_term = [](double rate) { - return make_blueprint_factory(int32_array_fs, QueryOperator::Term, num_docs, 0, rate, 1); + return make_blueprint_factory(int32_array_fs, QueryOperator::Term, num_docs, 0, rate, 1, false); }; analyze_crossover(*fixed_or, variable_term, num_docs + 1, true, 0.0001); } diff --git a/searchlib/src/vespa/searchlib/queryeval/flow.h b/searchlib/src/vespa/searchlib/queryeval/flow.h index b57e823f4d7..9ac79244755 100644 --- a/searchlib/src/vespa/searchlib/queryeval/flow.h +++ b/searchlib/src/vespa/searchlib/queryeval/flow.h @@ -214,44 +214,39 @@ size_t select_strict_and_child(auto adapter, const auto &children) { return best_idx; } -auto select_forced_strict_and_child_impl(auto adapter, const auto &children, size_t first, auto ordered, auto destructive) { - auto est_until = [&](size_t limit)noexcept{ - double my_est = 1.0; - for (size_t i = 0; i < limit; ++i) { - my_est *= adapter.estimate(children[i]); - } - return my_est; - }; - double est = est_until(first); +auto select_forced_strict_and_child(auto adapter, const auto &children, size_t first) { + double est = 1.0; double cost = 0.0; size_t best_idx = first; size_t best_target = first; double best_diff = std::numeric_limits<double>::max(); + for (size_t i = 0; i < first; ++i) { + est *= adapter.estimate(children[i]); + } for (size_t idx = first; idx < children.size(); ++idx) { auto child = FlowStats::from(adapter, children[idx]); double child_abs_cost = est * child.cost; double forced_cost = forced_strict_cost(child, est); double my_diff = (forced_cost + child.estimate * cost) - (cost + child_abs_cost); size_t target = first; - while (ordered && target > 0) { + while (target > 0) { size_t candidate = target - 1; auto other = FlowStats::from(adapter, children[candidate]); if (other.estimate < child.estimate) { // do not move past someone with lower estimate break; } - if (!destructive && !should_force_strict(other, (est_until(candidate) * child.estimate))) { - // no not move past someone who will lose strictness, - // unless it is explicitly allowed by enabling - // destructive (re-)ordering - break; - } target = candidate; my_diff += (0.2 * child.estimate - 0.2 * other.estimate); if (candidate == 0) { // the first iterator produces its own in-flow my_diff += (0.2 * child.estimate - 0.2 * other.estimate); } + // note that 'my_diff' might overestimate the cost + // (underestimate the benefit) of inserting 'child' before + // 'other' if it leads to 'other' becoming + // non-strict. This will also leave 'other' in a + // potentially unoptimal location. } if (my_diff < best_diff) { best_diff = my_diff; @@ -264,19 +259,6 @@ auto select_forced_strict_and_child_impl(auto adapter, const auto &children, siz return std::make_tuple(best_idx, best_target, best_diff); } -auto select_forced_strict_and_child(auto adapter, const auto &children, size_t first) { - auto [idx, target, diff] = select_forced_strict_and_child_impl(adapter, children, first, std::false_type{}, std::false_type{}); - return std::make_pair(idx, diff); -} - -auto select_forced_strict_and_child_with_order(auto adapter, const auto &children, size_t first) { - return select_forced_strict_and_child_impl(adapter, children, first, std::true_type{}, std::false_type{}); -} - -auto select_forced_strict_and_child_with_destructive_order(auto adapter, const auto &children, size_t first) { - return select_forced_strict_and_child_impl(adapter, children, first, std::true_type{}, std::true_type{}); -} - } // flow template <typename FLOW> diff --git a/security-utils/src/main/java/com/yahoo/security/AutoReloadingX509KeyManager.java b/security-utils/src/main/java/com/yahoo/security/AutoReloadingX509KeyManager.java index be1940441d4..c98e0791f2d 100644 --- a/security-utils/src/main/java/com/yahoo/security/AutoReloadingX509KeyManager.java +++ b/security-utils/src/main/java/com/yahoo/security/AutoReloadingX509KeyManager.java @@ -6,7 +6,6 @@ import javax.net.ssl.X509ExtendedKeyManager; import java.io.IOException; import java.io.UncheckedIOException; import java.net.Socket; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyStore; @@ -14,7 +13,7 @@ import java.security.Principal; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.time.Duration; -import java.util.Arrays; +import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -60,7 +59,7 @@ public class AutoReloadingX509KeyManager extends X509ExtendedKeyManager implemen X509ExtendedKeyManager manager = mutableX509KeyManager.currentManager(); X509Certificate[] certificateChain = manager.getCertificateChain(CERTIFICATE_ALIAS); PrivateKey privateKey = manager.getPrivateKey(CERTIFICATE_ALIAS); - return new X509CertificateWithKey(Arrays.asList(certificateChain), privateKey); + return new X509CertificateWithKey(List.of(certificateChain), privateKey); } private static KeyStore createKeystore(Path privateKey, Path certificateChain) { @@ -68,8 +67,8 @@ public class AutoReloadingX509KeyManager extends X509ExtendedKeyManager implemen return KeyStoreBuilder.withType(KeyStoreType.PKCS12) .withKeyEntry( CERTIFICATE_ALIAS, - KeyUtils.fromPemEncodedPrivateKey(new String(Files.readAllBytes(privateKey), StandardCharsets.UTF_8)), - X509CertificateUtils.certificateListFromPem(new String(Files.readAllBytes(certificateChain), StandardCharsets.UTF_8))) + KeyUtils.fromPemEncodedPrivateKey(Files.readString(privateKey)), + X509CertificateUtils.certificateListFromPem(Files.readString(certificateChain))) .build(); } catch (IOException e) { throw new UncheckedIOException(e); diff --git a/security-utils/src/main/java/com/yahoo/security/KeyManagerUtils.java b/security-utils/src/main/java/com/yahoo/security/KeyManagerUtils.java index ab584dbb48e..f25118029da 100644 --- a/security-utils/src/main/java/com/yahoo/security/KeyManagerUtils.java +++ b/security-utils/src/main/java/com/yahoo/security/KeyManagerUtils.java @@ -27,7 +27,7 @@ public class KeyManagerUtils { .filter(manager -> manager instanceof X509ExtendedKeyManager) .map(X509ExtendedKeyManager.class::cast) .findFirst() - .orElseThrow(() -> new RuntimeException("No X509ExtendedKeyManager in " + Arrays.asList(keyManagers))); + .orElseThrow(() -> new RuntimeException("No X509ExtendedKeyManager in " + List.of(keyManagers))); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } diff --git a/security-utils/src/main/java/com/yahoo/security/KeyStoreBuilder.java b/security-utils/src/main/java/com/yahoo/security/KeyStoreBuilder.java index c4c01ca130c..0901ea5931f 100644 --- a/security-utils/src/main/java/com/yahoo/security/KeyStoreBuilder.java +++ b/security-utils/src/main/java/com/yahoo/security/KeyStoreBuilder.java @@ -15,8 +15,6 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; -import static java.util.Collections.singletonList; - /** * @author bjorncs */ @@ -53,7 +51,7 @@ public class KeyStoreBuilder { } public KeyStoreBuilder withKeyEntry(String alias, PrivateKey privateKey, char[] password, X509Certificate certificate) { - return withKeyEntry(alias, privateKey, password, singletonList(certificate)); + return withKeyEntry(alias, privateKey, password, List.of(certificate)); } public KeyStoreBuilder withKeyEntry(String alias, PrivateKey privateKey, X509Certificate certificate) { diff --git a/security-utils/src/main/java/com/yahoo/security/Pkcs10Csr.java b/security-utils/src/main/java/com/yahoo/security/Pkcs10Csr.java index 78a00246d38..d1c9ae582b7 100644 --- a/security-utils/src/main/java/com/yahoo/security/Pkcs10Csr.java +++ b/security-utils/src/main/java/com/yahoo/security/Pkcs10Csr.java @@ -15,8 +15,6 @@ import java.util.List; import java.util.Objects; import java.util.Optional; -import static java.util.Collections.emptyList; - /** * @author bjorncs */ @@ -40,7 +38,7 @@ public class Pkcs10Csr { return getExtensions() .map(extensions -> GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName)) .map(SubjectAlternativeName::fromGeneralNames) - .orElse(emptyList()); + .orElse(List.of()); } /** @@ -57,7 +55,7 @@ public class Pkcs10Csr { .map(extensions -> Arrays.stream(extensions.getExtensionOIDs()) .map(ASN1ObjectIdentifier::getId) .toList()) - .orElse(emptyList()); + .orElse(List.of()); } diff --git a/security-utils/src/main/java/com/yahoo/security/SslContextBuilder.java b/security-utils/src/main/java/com/yahoo/security/SslContextBuilder.java index cedad3afc9b..8fecbb72a43 100644 --- a/security-utils/src/main/java/com/yahoo/security/SslContextBuilder.java +++ b/security-utils/src/main/java/com/yahoo/security/SslContextBuilder.java @@ -18,8 +18,6 @@ import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.List; -import static java.util.Collections.singletonList; - /** * A builder for {@link SSLContext}. * @@ -48,7 +46,7 @@ public class SslContextBuilder { } public SslContextBuilder withTrustStore(X509Certificate caCertificate) { - return withTrustStore(singletonList(caCertificate)); + return withTrustStore(List.of(caCertificate)); } public SslContextBuilder withTrustStore(List<X509Certificate> caCertificates) { @@ -66,7 +64,7 @@ public class SslContextBuilder { } public SslContextBuilder withKeyStore(PrivateKey privateKey, X509Certificate certificate) { - return withKeyStore(privateKey, singletonList(certificate)); + return withKeyStore(privateKey, List.of(certificate)); } public SslContextBuilder withKeyStore(PrivateKey privateKey, List<X509Certificate> certificates) { diff --git a/security-utils/src/main/java/com/yahoo/security/TrustManagerUtils.java b/security-utils/src/main/java/com/yahoo/security/TrustManagerUtils.java index 0b06584afb7..2d3adffea87 100644 --- a/security-utils/src/main/java/com/yahoo/security/TrustManagerUtils.java +++ b/security-utils/src/main/java/com/yahoo/security/TrustManagerUtils.java @@ -1,9 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.security; -import com.yahoo.security.KeyStoreBuilder; -import com.yahoo.security.KeyStoreType; - import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509ExtendedTrustManager; @@ -29,7 +26,7 @@ public class TrustManagerUtils { .filter(manager -> manager instanceof X509ExtendedTrustManager) .map(X509ExtendedTrustManager.class::cast) .findFirst() - .orElseThrow(() -> new RuntimeException("No X509ExtendedTrustManager in " + Arrays.asList(trustManagers))); + .orElseThrow(() -> new RuntimeException("No X509ExtendedTrustManager in " + List.of(trustManagers))); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } diff --git a/security-utils/src/main/java/com/yahoo/security/X509CertificateUtils.java b/security-utils/src/main/java/com/yahoo/security/X509CertificateUtils.java index 171a8e890d0..f615ff2e832 100644 --- a/security-utils/src/main/java/com/yahoo/security/X509CertificateUtils.java +++ b/security-utils/src/main/java/com/yahoo/security/X509CertificateUtils.java @@ -34,7 +34,6 @@ import java.security.cert.X509Certificate; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Random; @@ -150,7 +149,7 @@ public class X509CertificateUtils { public static List<SubjectAlternativeName> getSubjectAlternativeNames(X509Certificate certificate) { try { byte[] extensionValue = certificate.getExtensionValue(SUBJECT_ALTERNATIVE_NAMES.getOId()); - if (extensionValue == null) return Collections.emptyList(); + if (extensionValue == null) return List.of(); ASN1Encodable asn1Encodable = ASN1Primitive.fromByteArray(extensionValue); if (asn1Encodable instanceof ASN1OctetString) { asn1Encodable = ASN1Primitive.fromByteArray(((ASN1OctetString) asn1Encodable).getOctets()); diff --git a/security-utils/src/main/java/com/yahoo/security/X509CertificateWithKey.java b/security-utils/src/main/java/com/yahoo/security/X509CertificateWithKey.java index e80d3840bce..afd5fa315a6 100644 --- a/security-utils/src/main/java/com/yahoo/security/X509CertificateWithKey.java +++ b/security-utils/src/main/java/com/yahoo/security/X509CertificateWithKey.java @@ -3,7 +3,6 @@ package com.yahoo.security; import java.security.PrivateKey; import java.security.cert.X509Certificate; -import java.util.Collections; import java.util.List; /** @@ -18,7 +17,7 @@ public class X509CertificateWithKey { private final PrivateKey privateKey; public X509CertificateWithKey(X509Certificate certificate, PrivateKey privateKey) { - this(Collections.singletonList(certificate), privateKey); + this(List.of(certificate), privateKey); } public X509CertificateWithKey(List<X509Certificate> certificate, PrivateKey privateKey) { diff --git a/security-utils/src/main/java/com/yahoo/security/tls/DefaultTlsContext.java b/security-utils/src/main/java/com/yahoo/security/tls/DefaultTlsContext.java index 4e810c2d304..c2092d0c22b 100644 --- a/security-utils/src/main/java/com/yahoo/security/tls/DefaultTlsContext.java +++ b/security-utils/src/main/java/com/yahoo/security/tls/DefaultTlsContext.java @@ -64,7 +64,7 @@ public class DefaultTlsContext implements TlsContext { String.format("None of the accepted ciphers are supported (supported=%s, accepted=%s)", supportedCiphers, acceptedCiphers)); } - log.log(Level.FINE, () -> String.format("Allowed cipher suites that are supported: %s", Arrays.asList(allowedCiphers))); + log.log(Level.FINE, () -> String.format("Allowed cipher suites that are supported: %s", List.of(allowedCiphers))); return allowedCiphers; } diff --git a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java index 04282ceaac7..b78fa16ae56 100644 --- a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java +++ b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java @@ -5,7 +5,6 @@ import org.junit.jupiter.api.Test; import javax.security.auth.x500.X500Principal; import java.security.KeyPair; -import java.util.Arrays; import java.util.List; import static com.yahoo.security.SubjectAlternativeName.Type.DNS; @@ -27,7 +26,7 @@ public class Pkcs10CsrTest { .addSubjectAlternativeName(san1) .addSubjectAlternativeName(san2) .build(); - assertEquals(Arrays.asList(san1, san2), csr.getSubjectAlternativeNames()); + assertEquals(List.of(san1, san2), csr.getSubjectAlternativeNames()); } @Test @@ -49,7 +48,7 @@ public class Pkcs10CsrTest { .addSubjectAlternativeName("san") .setBasicConstraints(true, true) .build(); - List<String> expected = Arrays.asList(Extension.BASIC_CONSTRAINTS.getOId(), Extension.SUBJECT_ALTERNATIVE_NAMES.getOId()); + List<String> expected = List.of(Extension.BASIC_CONSTRAINTS.getOId(), Extension.SUBJECT_ALTERNATIVE_NAMES.getOId()); List<String> actual = csr.getExtensionOIds(); assertEquals(expected, actual); } diff --git a/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java b/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java index d91c9fc23f2..5d5cc7b7fa5 100644 --- a/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java +++ b/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java @@ -10,8 +10,8 @@ import java.security.KeyPair; import java.security.cert.X509Certificate; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.Arrays; import java.util.Collection; +import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -21,7 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; public class X509CertificateBuilderTest { public static Collection<Object[]> data() { - return Arrays.asList(new Object[][]{ + return List.of(new Object[][]{ {KeyAlgorithm.RSA, 2048, SignatureAlgorithm.SHA512_WITH_RSA}, {KeyAlgorithm.EC, 256, SignatureAlgorithm.SHA512_WITH_ECDSA}}); } diff --git a/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java b/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java index 6ac71a264b3..e67dce9fd8f 100644 --- a/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java +++ b/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java @@ -9,7 +9,6 @@ import java.security.KeyPair; import java.security.cert.X509Certificate; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.Arrays; import java.util.List; import static com.yahoo.security.SubjectAlternativeName.Type.DNS; @@ -42,7 +41,7 @@ public class X509CertificateUtilsTest { X509Certificate cert1 = TestUtils.createCertificate(keypair, subject1); X500Principal subject2 = new X500Principal("CN=myservice2"); X509Certificate cert2 = TestUtils.createCertificate(keypair, subject2); - List<X509Certificate> certificateList = Arrays.asList(cert1, cert2); + List<X509Certificate> certificateList = List.of(cert1, cert2); String pem = X509CertificateUtils.toPem(certificateList); List<X509Certificate> deserializedCertificateList = X509CertificateUtils.certificateListFromPem(pem); assertEquals(2, certificateList.size()); diff --git a/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java b/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java index e6f3450332d..ee54a80f732 100644 --- a/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java +++ b/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java @@ -3,11 +3,10 @@ package com.yahoo.security.tls; import org.junit.jupiter.api.Test; -import java.util.HashSet; +import java.util.List; +import java.util.Set; import static com.yahoo.security.tls.RequiredPeerCredential.Field.CN; -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertThrows; /** @@ -18,9 +17,9 @@ public class AuthorizedPeersTest { @Test void throws_exception_on_peer_policies_with_duplicate_names() { assertThrows(IllegalArgumentException.class, () -> { - PeerPolicy peerPolicy1 = new PeerPolicy("duplicate-name", singletonList(RequiredPeerCredential.of(CN, "mycfgserver"))); - PeerPolicy peerPolicy2 = new PeerPolicy("duplicate-name", singletonList(RequiredPeerCredential.of(CN, "myclient"))); - new AuthorizedPeers(new HashSet<>(asList(peerPolicy1, peerPolicy2))); + PeerPolicy peerPolicy1 = new PeerPolicy("duplicate-name", List.of(RequiredPeerCredential.of(CN, "mycfgserver"))); + PeerPolicy peerPolicy2 = new PeerPolicy("duplicate-name", List.of(RequiredPeerCredential.of(CN, "myclient"))); + new AuthorizedPeers(Set.of(peerPolicy1, peerPolicy2)); }); } diff --git a/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java b/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java index ec7d5b8ca05..267e770050d 100644 --- a/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java +++ b/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java @@ -18,7 +18,6 @@ import static com.yahoo.security.X509CertificateBuilder.generateRandomSerialNumb import static java.time.Instant.EPOCH; import static java.time.temporal.ChronoUnit.DAYS; import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; /** @@ -38,7 +37,7 @@ public class DefaultTlsContextTest { singleton( new PeerPolicy( "dummy-policy", - singletonList(RequiredPeerCredential.of(RequiredPeerCredential.Field.CN, "dummy"))))); + List.of(RequiredPeerCredential.of(RequiredPeerCredential.Field.CN, "dummy"))))); DefaultTlsContext tlsContext = DefaultTlsContext.of( diff --git a/security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java b/security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java index 112cfa75102..91ce19574fe 100644 --- a/security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java +++ b/security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java @@ -23,9 +23,6 @@ import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA; import static com.yahoo.security.tls.RequiredPeerCredential.Field.CN; import static com.yahoo.security.tls.RequiredPeerCredential.Field.SAN_DNS; import static com.yahoo.security.tls.RequiredPeerCredential.Field.SAN_URI; -import static java.util.Arrays.asList; -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -45,13 +42,13 @@ public class PeerAuthorizerTest { RequiredPeerCredential sanRequirement = createRequiredCredential(SAN_DNS, "*.matching.san"); PeerAuthorizer authorizer = createPeerAuthorizer(createPolicy(POLICY_1, cnRequirement, sanRequirement)); - ConnectionAuthContext result = authorizer.authorizePeer(createCertificate("foo.matching.cn", asList("foo.matching.san", "foo.invalid.san"), emptyList())); + ConnectionAuthContext result = authorizer.authorizePeer(createCertificate("foo.matching.cn", List.of("foo.matching.san", "foo.invalid.san"), List.of())); assertAuthorized(result); assertThat(result.matchedPolicies()).containsOnly(POLICY_1); - assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.invalid.cn", singletonList("foo.matching.san"), emptyList()))); - assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.invalid.cn", asList("foo.matching.san", "foo.invalid.san"), emptyList()))); - assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.matching.cn", singletonList("foo.invalid.san"), emptyList()))); + assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.invalid.cn", List.of("foo.matching.san"), List.of()))); + assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.invalid.cn", List.of("foo.matching.san", "foo.invalid.san"), List.of()))); + assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.matching.cn", List.of("foo.invalid.san"), List.of()))); } @Test @@ -64,7 +61,7 @@ public class PeerAuthorizerTest { createPolicy(POLICY_2, cnRequirement, sanRequirement)); ConnectionAuthContext result = peerAuthorizer - .authorizePeer(createCertificate("foo.matching.cn", singletonList("foo.matching.san"), emptyList())); + .authorizePeer(createCertificate("foo.matching.cn", List.of("foo.matching.san"), List.of())); assertAuthorized(result); assertThat(result.matchedPolicies()).containsOnly(POLICY_1, POLICY_2); } @@ -75,7 +72,7 @@ public class PeerAuthorizerTest { createPolicy(POLICY_1, createRequiredCredential(CN, "*.matching.cn")), createPolicy(POLICY_2, createRequiredCredential(SAN_DNS, "*.matching.san"))); - ConnectionAuthContext result = peerAuthorizer.authorizePeer(createCertificate("foo.invalid.cn", singletonList("foo.matching.san"), emptyList())); + ConnectionAuthContext result = peerAuthorizer.authorizePeer(createCertificate("foo.invalid.cn", List.of("foo.matching.san"), List.of())); assertAuthorized(result); assertThat(result.matchedPolicies()).containsOnly(POLICY_2); } @@ -89,9 +86,9 @@ public class PeerAuthorizerTest { PeerAuthorizer peerAuthorizer = createPeerAuthorizer( createPolicy(POLICY_1, cnSuffixRequirement, cnPrefixRequirement, sanPrefixRequirement, sanSuffixRequirement)); - assertAuthorized(peerAuthorizer.authorizePeer(createCertificate("matching.prefix.matching.suffix.cn", singletonList("matching.prefix.matching.suffix.san"), emptyList()))); - assertUnauthorized(peerAuthorizer.authorizePeer(createCertificate("matching.prefix.matching.suffix.cn", singletonList("matching.prefix.invalid.suffix.san"), emptyList()))); - assertUnauthorized(peerAuthorizer.authorizePeer(createCertificate("invalid.prefix.matching.suffix.cn", singletonList("matching.prefix.matching.suffix.san"), emptyList()))); + assertAuthorized(peerAuthorizer.authorizePeer(createCertificate("matching.prefix.matching.suffix.cn", List.of("matching.prefix.matching.suffix.san"), List.of()))); + assertUnauthorized(peerAuthorizer.authorizePeer(createCertificate("matching.prefix.matching.suffix.cn", List.of("matching.prefix.invalid.suffix.san"), List.of()))); + assertUnauthorized(peerAuthorizer.authorizePeer(createCertificate("invalid.prefix.matching.suffix.cn", List.of("matching.prefix.matching.suffix.san"), List.of()))); } @Test @@ -100,11 +97,11 @@ public class PeerAuthorizerTest { RequiredPeerCredential sanUriRequirement = createRequiredCredential(SAN_URI, "myscheme://my/*/uri"); PeerAuthorizer authorizer = createPeerAuthorizer(createPolicy(POLICY_1, cnRequirement, sanUriRequirement)); - ConnectionAuthContext result = authorizer.authorizePeer(createCertificate("foo.matching.cn", singletonList("foo.irrelevant.san"), singletonList("myscheme://my/matching/uri"))); + ConnectionAuthContext result = authorizer.authorizePeer(createCertificate("foo.matching.cn", List.of("foo.irrelevant.san"), List.of("myscheme://my/matching/uri"))); assertAuthorized(result); assertThat(result.matchedPolicies()).containsOnly(POLICY_1); - assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.matching.cn", emptyList(), singletonList("myscheme://my/nonmatching/url")))); + assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.matching.cn", List.of(), List.of("myscheme://my/nonmatching/url")))); } @Test @@ -145,7 +142,7 @@ public class PeerAuthorizerTest { } private static PeerPolicy createPolicy(String name, RequiredPeerCredential... requiredCredentials) { - return new PeerPolicy(name, asList(requiredCredentials)); + return new PeerPolicy(name, List.of(requiredCredentials)); } private static PeerPolicy createPolicy(String name, List<Capability> caps, List<RequiredPeerCredential> creds) { diff --git a/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java index 1871bb43569..e7254c12985 100644 --- a/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java +++ b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java @@ -14,9 +14,8 @@ import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Arrays; -import java.util.Collections; import java.util.LinkedHashSet; +import java.util.List; import java.util.Optional; import static com.yahoo.security.tls.RequiredPeerCredential.Field.CN; @@ -43,14 +42,14 @@ public class TransportSecurityOptionsJsonSerializerTest { .withHostnameValidationDisabled(false) .withAuthorizedPeers( new AuthorizedPeers( - new LinkedHashSet<>(Arrays.asList( - new PeerPolicy("cfgserver", "cfgserver policy description", Arrays.asList( + new LinkedHashSet<>(List.of( + new PeerPolicy("cfgserver", "cfgserver policy description", List.of( RequiredPeerCredential.of(CN, "mycfgserver"), RequiredPeerCredential.of(SAN_DNS, "*.suffix.com"), RequiredPeerCredential.of(SAN_URI, "myscheme://resource/path/"))), new PeerPolicy("node", Optional.empty(), CapabilitySet.of(Capability.SLOBROK__API), - Collections.singletonList(RequiredPeerCredential.of(CN, "hostname"))))))) + List.of(RequiredPeerCredential.of(CN, "hostname"))))))) .build(); ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -67,8 +66,8 @@ public class TransportSecurityOptionsJsonSerializerTest { TransportSecurityOptions options = new TransportSecurityOptions.Builder() .withCertificates(Paths.get("certs.pem"), Paths.get("myhost.key")) .withCaCertificates(Paths.get("my_cas.pem")) - .withAcceptedCiphers(Arrays.asList("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_AES_256_GCM_SHA384")) - .withAcceptedProtocols(Collections.singletonList("TLSv1.2")) + .withAcceptedCiphers(List.of("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_AES_256_GCM_SHA384")) + .withAcceptedProtocols(List.of("TLSv1.2")) .withHostnameValidationDisabled(true) .build(); File outputFile = File.createTempFile("junit", null, tempDirectory); diff --git a/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java index 08e573fed7e..188a6a1568a 100644 --- a/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java +++ b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java @@ -4,12 +4,10 @@ package com.yahoo.security.tls; import org.junit.jupiter.api.Test; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Arrays; -import java.util.Collections; +import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -22,8 +20,8 @@ public class TransportSecurityOptionsTest { private static final TransportSecurityOptions OPTIONS = new TransportSecurityOptions.Builder() .withCertificates(Paths.get("certs.pem"), Paths.get("myhost.key")) .withCaCertificates(Paths.get("my_cas.pem")) - .withAcceptedCiphers(Arrays.asList("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_AES_256_GCM_SHA384")) - .withAcceptedProtocols(Collections.singletonList("TLSv1.2")) + .withAcceptedCiphers(List.of("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_AES_256_GCM_SHA384")) + .withAcceptedProtocols(List.of("TLSv1.2")) .withHostnameValidationDisabled(true) .build(); @@ -35,7 +33,7 @@ public class TransportSecurityOptionsTest { @Test void can_read_options_from_json() throws IOException { - String tlsJson = new String(Files.readAllBytes(TEST_CONFIG_FILE), StandardCharsets.UTF_8); + String tlsJson = Files.readString(TEST_CONFIG_FILE); TransportSecurityOptions actualOptions = TransportSecurityOptions.fromJson(tlsJson); assertEquals(OPTIONS, actualOptions); } diff --git a/service-monitor/src/main/java/com/yahoo/vespa/service/duper/InfraApplication.java b/service-monitor/src/main/java/com/yahoo/vespa/service/duper/InfraApplication.java index 1c2c57e9a77..bd05b1ab509 100644 --- a/service-monitor/src/main/java/com/yahoo/vespa/service/duper/InfraApplication.java +++ b/service-monitor/src/main/java/com/yahoo/vespa/service/duper/InfraApplication.java @@ -22,7 +22,6 @@ import com.yahoo.vespa.service.model.ApplicationInstanceGenerator; import com.yahoo.vespa.service.model.ModelGenerator; import com.yahoo.vespa.service.monitor.InfraApplicationApi; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -107,12 +106,12 @@ public abstract class InfraApplication implements InfraApplicationApi { // service name == service type for the first service of each type on each host serviceType.s(), serviceType.s(), - Collections.singletonList(portInfo), + List.of(portInfo), properties, configIdFor(hostname).s(), hostname.value()); - return new HostInfo(hostname.value(), Collections.singletonList(serviceInfo)); + return new HostInfo(hostname.value(), List.of(serviceInfo)); } public ConfigId configIdFor(DomainName hostname) { diff --git a/service-monitor/src/main/java/com/yahoo/vespa/service/monitor/ServiceModel.java b/service-monitor/src/main/java/com/yahoo/vespa/service/monitor/ServiceModel.java index 5bafc7ac4bd..7d89b86c07b 100644 --- a/service-monitor/src/main/java/com/yahoo/vespa/service/monitor/ServiceModel.java +++ b/service-monitor/src/main/java/com/yahoo/vespa/service/monitor/ServiceModel.java @@ -9,7 +9,6 @@ import com.yahoo.vespa.applicationmodel.ServiceCluster; import com.yahoo.vespa.applicationmodel.ServiceInstance; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -74,7 +73,7 @@ public class ServiceModel { ApplicationInstance previous = applicationInstances.put(instance.hostName(), application); if (previous != null && !previous.equals(application)) { throw new IllegalStateException("Major assumption broken: Multiple application instances contain host " + - instance.hostName().s() + ": " + Arrays.asList(previous, application)); + instance.hostName().s() + ": " + List.of(previous, application)); } serviceInstances diff --git a/service-monitor/src/test/java/com/yahoo/vespa/service/duper/DuperModelTest.java b/service-monitor/src/test/java/com/yahoo/vespa/service/duper/DuperModelTest.java index a5b8054536b..00c15add762 100644 --- a/service-monitor/src/test/java/com/yahoo/vespa/service/duper/DuperModelTest.java +++ b/service-monitor/src/test/java/com/yahoo/vespa/service/duper/DuperModelTest.java @@ -66,7 +66,7 @@ public class DuperModelTest { duperModel.add(application1); assertEquals(Optional.of(application1), duperModel.getApplicationInfo(id1)); - assertEquals(Arrays.asList(application1), duperModel.getApplicationInfos()); + assertEquals(List.of(application1), duperModel.getApplicationInfos()); assertEquals(1, duperModel.numberOfApplications()); duperModel.registerListener(listener1); @@ -86,7 +86,7 @@ public class DuperModelTest { assertEquals(Optional.empty(), duperModel.getApplicationInfo(id1)); verify(listener1, times(1)).applicationRemoved(id1); verifyNoMoreInteractions(listener1); - assertEquals(Arrays.asList(application2), duperModel.getApplicationInfos()); + assertEquals(List.of(application2), duperModel.getApplicationInfos()); duperModel.remove(id1); verifyNoMoreInteractions(listener1); diff --git a/service-monitor/src/test/java/com/yahoo/vespa/service/model/ExampleModel.java b/service-monitor/src/test/java/com/yahoo/vespa/service/model/ExampleModel.java index bef87a627f5..9c0c94cef27 100644 --- a/service-monitor/src/test/java/com/yahoo/vespa/service/model/ExampleModel.java +++ b/service-monitor/src/test/java/com/yahoo/vespa/service/model/ExampleModel.java @@ -12,7 +12,6 @@ import com.yahoo.config.provision.InstanceName; import com.yahoo.vespa.service.slobrok.SlobrokMonitor; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -151,7 +150,7 @@ public class ExampleModel { * A bit unrealistic, but the port is the same on all hosts. */ ClusterBuilder addPort(int port, String... tags) { - portInfos.add(new PortInfo(port, Arrays.asList(tags))); + portInfos.add(new PortInfo(port, List.of(tags))); return this; } diff --git a/standalone-container/src/main/java/com/yahoo/application/container/impl/ClassLoaderOsgiFramework.java b/standalone-container/src/main/java/com/yahoo/application/container/impl/ClassLoaderOsgiFramework.java index 8da19fcb64b..5789a69a4db 100644 --- a/standalone-container/src/main/java/com/yahoo/application/container/impl/ClassLoaderOsgiFramework.java +++ b/standalone-container/src/main/java/com/yahoo/application/container/impl/ClassLoaderOsgiFramework.java @@ -32,7 +32,6 @@ import java.net.URLClassLoader; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.Dictionary; import java.util.Enumeration; import java.util.Hashtable; @@ -226,7 +225,7 @@ public final class ClassLoaderOsgiFramework implements OsgiFramework { @Override public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) { - return Collections.emptyMap(); + return Map.of(); } @Override diff --git a/standalone-container/src/test/java/com/yahoo/container/standalone/CloudConfigInstallVariablesTest.java b/standalone-container/src/test/java/com/yahoo/container/standalone/CloudConfigInstallVariablesTest.java index 72f32ac04b8..9cd48ac85a8 100644 --- a/standalone-container/src/test/java/com/yahoo/container/standalone/CloudConfigInstallVariablesTest.java +++ b/standalone-container/src/test/java/com/yahoo/container/standalone/CloudConfigInstallVariablesTest.java @@ -6,7 +6,6 @@ import org.junit.Test; import java.util.Arrays; import java.util.List; -import java.util.stream.Collectors; import static com.yahoo.container.standalone.CloudConfigInstallVariables.toConfigModelsPluginDir; import static com.yahoo.container.standalone.CloudConfigInstallVariables.toConfigServer; @@ -39,7 +38,7 @@ public class CloudConfigInstallVariablesTest { assertEquals(2, parsed.length); List<String> hostNames = Arrays.stream(parsed).map(cs -> cs.hostName).toList(); - assertTrue(hostNames.containsAll(Arrays.asList("test1", "test2"))); + assertTrue(hostNames.containsAll(List.of("test1", "test2"))); } @Test(expected = IllegalArgumentException.class) diff --git a/standalone-container/src/test/java/com/yahoo/container/standalone/StandaloneContainer.java b/standalone-container/src/test/java/com/yahoo/container/standalone/StandaloneContainer.java index 8d207388b42..00430e04858 100644 --- a/standalone-container/src/test/java/com/yahoo/container/standalone/StandaloneContainer.java +++ b/standalone-container/src/test/java/com/yahoo/container/standalone/StandaloneContainer.java @@ -11,7 +11,6 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Arrays; import java.util.List; /** @@ -51,7 +50,7 @@ public class StandaloneContainer { private static void writeServicesXml(Path applicationPath, String servicesXml) throws IOException { Path path = applicationPath.resolve("services.xml"); - List<String> output = Arrays.asList("<?xml version=\"1.0\" encoding=\"utf-8\"?>", servicesXml); + List<String> output = List.of("<?xml version=\"1.0\" encoding=\"utf-8\"?>", servicesXml); Files.write(path, output, StandardCharsets.UTF_8); } } diff --git a/storage/src/tests/persistence/active_operations_stats_test.cpp b/storage/src/tests/persistence/active_operations_stats_test.cpp index bf91a84235a..71be34e3f54 100644 --- a/storage/src/tests/persistence/active_operations_stats_test.cpp +++ b/storage/src/tests/persistence/active_operations_stats_test.cpp @@ -28,6 +28,8 @@ public: std::shared_ptr<api::StorageMessage> createPut(uint64_t bucket, uint64_t docIdx); std::shared_ptr<api::StorageMessage> createGet(uint64_t bucket) const; + void SetUp() override; + void TearDown() override; void assert_active_operations_stats(const ActiveOperationsStats &stats, uint32_t exp_active_size, uint32_t exp_size_samples, uint32_t exp_latency_samples); void update_metrics(); void test_active_operations_stats(); @@ -41,16 +43,30 @@ ActiveOperationsStatsTest::ActiveOperationsStatsTest() metrics(), stripeId(0) { + // Initialization of members must happen in SetUp() since this test transitively + // depends on components modified by the superclass' SetUp() method. +} + +void +ActiveOperationsStatsTest::SetUp() +{ + FileStorTestFixture::SetUp(); setupPersistenceThreads(1); _node->setPersistenceProvider(std::make_unique<spi::dummy::DummyPersistence>(_node->getTypeRepo())); top.push_back(std::move(dummyManager)); top.open(); metrics.initDiskMetrics(1, 1); - filestorHandler = std::make_unique<FileStorHandlerImpl>(messageSender, metrics, - _node->getComponentRegister()); + filestorHandler = std::make_unique<FileStorHandlerImpl>(messageSender, metrics, _node->getComponentRegister()); filestorHandler->setGetNextMessageTimeout(20ms); } +void +ActiveOperationsStatsTest::TearDown() +{ + filestorHandler.reset(); + FileStorTestFixture::TearDown(); +} + ActiveOperationsStatsTest::~ActiveOperationsStatsTest() = default; std::shared_ptr<api::StorageMessage> diff --git a/storage/src/tests/persistence/filestorage/CMakeLists.txt b/storage/src/tests/persistence/filestorage/CMakeLists.txt index f1a8a286bbd..aa7c9fe995c 100644 --- a/storage/src/tests/persistence/filestorage/CMakeLists.txt +++ b/storage/src/tests/persistence/filestorage/CMakeLists.txt @@ -4,6 +4,7 @@ vespa_add_executable(storage_filestorage_gtest_runner_app TEST SOURCES deactivatebucketstest.cpp deletebuckettest.cpp + feed_operation_batching_test.cpp filestormanagertest.cpp filestormodifiedbucketstest.cpp mergeblockingtest.cpp @@ -18,6 +19,7 @@ vespa_add_executable(storage_filestorage_gtest_runner_app TEST storage_testhostreporter storage_testpersistence_common GTest::GTest + absl::failure_signal_handler ) vespa_add_test( NAME storage_filestorage_gtest_runner_app COMMAND storage_filestorage_gtest_runner_app COST 50) diff --git a/storage/src/tests/persistence/filestorage/feed_operation_batching_test.cpp b/storage/src/tests/persistence/filestorage/feed_operation_batching_test.cpp new file mode 100644 index 00000000000..cf16123933b --- /dev/null +++ b/storage/src/tests/persistence/filestorage/feed_operation_batching_test.cpp @@ -0,0 +1,318 @@ +// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. + +#include <tests/common/dummystoragelink.h> +#include <tests/common/testhelper.h> +#include <tests/persistence/common/filestortestfixture.h> +#include <tests/persistence/filestorage/forwardingmessagesender.h> +#include <vespa/document/test/make_document_bucket.h> +#include <vespa/document/update/documentupdate.h> +#include <vespa/storage/persistence/filestorage/filestorhandlerimpl.h> +#include <vespa/storage/persistence/filestorage/filestormanager.h> +#include <vespa/storage/persistence/filestorage/filestormetrics.h> +#include <vespa/vespalib/util/stringfmt.h> +#include <gtest/gtest.h> + +using document::test::makeDocumentBucket; +using document::BucketId; +using document::DocumentId; +using namespace ::testing; + +namespace storage { + +struct FeedOperationBatchingTest : FileStorTestFixture { + DummyStorageLink _top; + std::unique_ptr<ForwardingMessageSender> _message_sender; + FileStorMetrics _metrics; + std::unique_ptr<FileStorHandler> _handler; + api::Timestamp _next_timestamp; + + FeedOperationBatchingTest(); + ~FeedOperationBatchingTest() override; + + void SetUp() override { + FileStorTestFixture::SetUp(); + // This silly little indirection is a work-around for the top-level link needing something + // below it to send _up_ into it, rather than directly receiving the messages itself. + auto message_receiver = std::make_unique<DummyStorageLink>(); + _message_sender = std::make_unique<ForwardingMessageSender>(*message_receiver); + _top.push_back(std::move(message_receiver)); + _top.open(); + _metrics.initDiskMetrics(1, 1); + // By default, sets up 1 thread with 1 stripe + _handler = std::make_unique<FileStorHandlerImpl>(*_message_sender, _metrics, _node->getComponentRegister()); + _handler->set_max_feed_op_batch_size(3); + } + + void TearDown() override { + _handler.reset(); + FileStorTestFixture::TearDown(); + } + + [[nodiscard]] static vespalib::string id_str_of(uint32_t bucket_idx, uint32_t doc_idx) { + return vespalib::make_string("id:foo:testdoctype1:n=%u:%u", bucket_idx, doc_idx); + } + + [[nodiscard]] static DocumentId id_of(uint32_t bucket_idx, uint32_t doc_idx) { + return DocumentId(id_str_of(bucket_idx, doc_idx)); + } + + void schedule_msg(const std::shared_ptr<api::StorageMessage>& msg) { + msg->setAddress(makeSelfAddress()); + _handler->schedule(msg); // takes shared_ptr by const ref, no point in moving + } + + void send_put(uint32_t bucket_idx, uint32_t doc_idx, uint32_t timestamp, vespalib::duration timeout) { + auto id = id_str_of(bucket_idx, doc_idx); + auto doc = _node->getTestDocMan().createDocument("foobar", id); + auto cmd = std::make_shared<api::PutCommand>(makeDocumentBucket({16, bucket_idx}), std::move(doc), timestamp); + cmd->setTimeout(timeout); + schedule_msg(cmd); + } + + void send_put(uint32_t bucket_idx, uint32_t doc_idx) { + send_put(bucket_idx, doc_idx, next_timestamp(), 60s); + } + + void send_puts(std::initializer_list<std::pair<uint32_t, uint32_t>> bucket_docs) { + for (const auto& bd : bucket_docs) { + send_put(bd.first, bd.second); + } + } + + void send_get(uint32_t bucket_idx, uint32_t doc_idx) { + auto id = id_of(bucket_idx, doc_idx); + auto cmd = std::make_shared<api::GetCommand>(makeDocumentBucket({16, bucket_idx}), id, document::AllFields::NAME); + schedule_msg(cmd); + } + + void send_remove(uint32_t bucket_idx, uint32_t doc_idx, uint32_t timestamp) { + auto id = id_of(bucket_idx, doc_idx); + auto cmd = std::make_shared<api::RemoveCommand>(makeDocumentBucket({16, bucket_idx}), id, timestamp); + schedule_msg(cmd); + } + + void send_remove(uint32_t bucket_idx, uint32_t doc_idx) { + send_remove(bucket_idx, doc_idx, next_timestamp()); + } + + void send_update(uint32_t bucket_idx, uint32_t doc_idx, uint32_t timestamp) { + auto id = id_of(bucket_idx, doc_idx); + auto update = std::make_shared<document::DocumentUpdate>( + _node->getTestDocMan().getTypeRepo(), + _node->getTestDocMan().createRandomDocument()->getType(), id); + auto cmd = std::make_shared<api::UpdateCommand>(makeDocumentBucket({16, bucket_idx}), std::move(update), timestamp); + schedule_msg(cmd); + } + + void send_update(uint32_t bucket_idx, uint32_t doc_idx) { + send_update(bucket_idx, doc_idx, next_timestamp()); + } + + [[nodiscard]] api::Timestamp next_timestamp() { + auto ret = _next_timestamp; + ++_next_timestamp; + return ret; + } + + [[nodiscard]] vespalib::steady_time fake_now() const { + return _node->getClock().getMonotonicTime(); + } + + [[nodiscard]] vespalib::steady_time fake_deadline() const { + return _node->getClock().getMonotonicTime() + 60s; + } + + [[nodiscard]] FileStorHandler::LockedMessageBatch next_batch() { + return _handler->next_message_batch(0, fake_now(), fake_deadline()); + } + + template <typename CmdType> + static void assert_batch_msg_is(const FileStorHandler::LockedMessageBatch& batch, uint32_t msg_idx, + uint32_t expected_bucket_idx, uint32_t expected_doc_idx) + { + ASSERT_LT(msg_idx, batch.size()); + auto msg = batch.messages[msg_idx].first; + auto* as_cmd = dynamic_cast<const CmdType*>(msg.get()); + ASSERT_TRUE(as_cmd) << msg->toString() << " does not have the expected type"; + EXPECT_EQ(as_cmd->getBucketId(), BucketId(16, expected_bucket_idx)); + + auto id = as_cmd->getDocumentId(); + ASSERT_TRUE(id.getScheme().hasNumber()); + EXPECT_EQ(id.getScheme().getNumber(), expected_bucket_idx) << id; + std::string actual_id_part = id.getScheme().getNamespaceSpecific(); + std::string expected_id_part = std::to_string(expected_doc_idx); + EXPECT_EQ(actual_id_part, expected_id_part) << id; + } + + static void assert_batch_msg_is_put(const FileStorHandler::LockedMessageBatch& batch, uint32_t msg_idx, + uint32_t expected_bucket_idx, uint32_t expected_doc_idx) + { + assert_batch_msg_is<api::PutCommand>(batch, msg_idx, expected_bucket_idx, expected_doc_idx); + } + + static void assert_batch_msg_is_remove(const FileStorHandler::LockedMessageBatch& batch, uint32_t msg_idx, + uint32_t expected_bucket_idx, uint32_t expected_doc_idx) + { + assert_batch_msg_is<api::RemoveCommand>(batch, msg_idx, expected_bucket_idx, expected_doc_idx); + } + + static void assert_batch_msg_is_update(const FileStorHandler::LockedMessageBatch& batch, uint32_t msg_idx, + uint32_t expected_bucket_idx, uint32_t expected_doc_idx) + { + assert_batch_msg_is<api::UpdateCommand>(batch, msg_idx, expected_bucket_idx, expected_doc_idx); + } + + static void assert_batch_msg_is_get(const FileStorHandler::LockedMessageBatch& batch, uint32_t msg_idx, + uint32_t expected_bucket_idx, uint32_t expected_doc_idx) + { + assert_batch_msg_is<api::GetCommand>(batch, msg_idx, expected_bucket_idx, expected_doc_idx); + } + + enum Type { + Put, + Update, + Remove, + Get + }; + + static void assert_empty_batch(const FileStorHandler::LockedMessageBatch& batch) { + ASSERT_TRUE(batch.empty()); + ASSERT_FALSE(batch.lock); + } + + static void assert_batch(const FileStorHandler::LockedMessageBatch& batch, + uint32_t expected_bucket_idx, + std::initializer_list<std::pair<Type, uint32_t>> expected_msgs) + { + ASSERT_TRUE(batch.lock); + ASSERT_EQ(batch.lock->getBucket().getBucketId(), BucketId(16, expected_bucket_idx)); + ASSERT_EQ(batch.size(), expected_msgs.size()); + + uint32_t idx = 0; + for (const auto& msg : expected_msgs) { + switch (msg.first) { + case Type::Put: assert_batch_msg_is_put(batch, idx, expected_bucket_idx, msg.second); break; + case Type::Update: assert_batch_msg_is_update(batch, idx, expected_bucket_idx, msg.second); break; + case Type::Remove: assert_batch_msg_is_remove(batch, idx, expected_bucket_idx, msg.second); break; + case Type::Get: assert_batch_msg_is_get(batch, idx, expected_bucket_idx, msg.second); break; + default: FAIL(); + } + ++idx; + } + } +}; + +FeedOperationBatchingTest::FeedOperationBatchingTest() + : FileStorTestFixture(), + _top(), + _message_sender(), + _metrics(), + _handler(), + _next_timestamp(1000) +{ +} + +FeedOperationBatchingTest::~FeedOperationBatchingTest() = default; + +// Note: unless explicitly set by the testcase, max batch size is 3 + +TEST_F(FeedOperationBatchingTest, batching_is_disabled_with_1_max_batch_size) { + _handler->set_max_feed_op_batch_size(1); + send_puts({{1, 1}, {1, 2}, {2, 3}, {2, 4}}); + // No batching; has the same behavior as current FIFO + assert_batch(next_batch(), 1, {{Put, 1}}); + assert_batch(next_batch(), 1, {{Put, 2}}); + assert_batch(next_batch(), 2, {{Put, 3}}); + assert_batch(next_batch(), 2, {{Put, 4}}); + assert_empty_batch(next_batch()); +} + +TEST_F(FeedOperationBatchingTest, batching_is_limited_to_configured_max_size) { + send_puts({{1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}}); + assert_batch(next_batch(), 1, {{Put, 1}, {Put, 2}, {Put, 3}}); + assert_batch(next_batch(), 1, {{Put, 4}, {Put, 5}}); + assert_empty_batch(next_batch()); +} + +TEST_F(FeedOperationBatchingTest, batching_can_consume_entire_queue) { + send_puts({{1, 1}, {1, 2}, {1, 3}}); + assert_batch(next_batch(), 1, {{Put, 1}, {Put, 2}, {Put, 3}}); + assert_empty_batch(next_batch()); +} + +TEST_F(FeedOperationBatchingTest, batching_is_only_done_for_single_bucket) { + send_puts({{1, 1}, {2, 2}, {2, 3}, {2, 4}, {3, 5}}); + assert_batch(next_batch(), 1, {{Put, 1}}); + assert_batch(next_batch(), 2, {{Put, 2}, {Put, 3}, {Put, 4}}); + assert_batch(next_batch(), 3, {{Put, 5}}); +} + +TEST_F(FeedOperationBatchingTest, batch_can_include_all_supported_feed_op_types) { + send_put(1, 1); + send_remove(1, 2); + send_update(1, 3); + assert_batch(next_batch(), 1, {{Put, 1}, {Remove, 2}, {Update, 3}}); +} + +TEST_F(FeedOperationBatchingTest, timed_out_reqeusts_are_ignored_by_batch) { + send_puts({{1, 1}}); + send_put(1, 2, next_timestamp(), 1s); + send_puts({{1, 3}}); + _node->getClock().addSecondsToTime(2); + // Put #2 with 1s timeout has expired in the queue and should not be returned as part of the batch + assert_batch(next_batch(), 1, {{Put, 1}, {Put, 3}}); + ASSERT_EQ(_top.getNumReplies(), 0); + // The actual timeout is handled by the next message fetch invocation + assert_empty_batch(next_batch()); + ASSERT_EQ(_top.getNumReplies(), 1); + EXPECT_EQ(dynamic_cast<api::StorageReply&>(*_top.getReply(0)).getResult().getResult(), api::ReturnCode::TIMEOUT); +} + +TEST_F(FeedOperationBatchingTest, non_feed_ops_are_not_batched) { + send_get(1, 2); + send_get(1, 3); + assert_batch(next_batch(), 1, {{Get, 2}}); + assert_batch(next_batch(), 1, {{Get, 3}}); +} + +TEST_F(FeedOperationBatchingTest, pipeline_stalled_by_non_feed_op) { + // It can reasonably be argued that we could batch _around_ a Get operation and still + // have correct behavior, but the Get here is just a stand-in for an arbitrary operation such + // as a Split (which changes the bucket set), which is rather more tricky to reason about. + // For simplicity and understandability, just stall the batch pipeline (at least for now). + send_get(1, 2); + send_puts({{1, 3}, {1, 4}}); + send_get(1, 5); + send_puts({{1, 6}, {1, 7}}); + + assert_batch(next_batch(), 1, {{Get, 2}}); // If first op is non-feed, only it should be returned + assert_batch(next_batch(), 1, {{Put, 3}, {Put, 4}}); + assert_batch(next_batch(), 1, {{Get, 5}}); + assert_batch(next_batch(), 1, {{Put, 6}, {Put, 7}}); +} + +TEST_F(FeedOperationBatchingTest, pipeline_stalled_by_concurrent_ops_to_same_document) { + // 2 ops to doc #2. Since this is expected to be a very rare edge case, just + // stop batching at that point and defer the concurrent op to the next batch. + send_puts({{1, 1}, {1, 2}, {1, 3}, {1, 2}, {1, 4}}); + assert_batch(next_batch(), 1, {{Put, 1}, {Put, 2}, {Put, 3}}); + assert_batch(next_batch(), 1, {{Put, 2}, {Put, 4}}); +} + +TEST_F(FeedOperationBatchingTest, batch_respects_persistence_throttling) { + vespalib::SharedOperationThrottler::DynamicThrottleParams params; + params.min_window_size = 3; + params.max_window_size = 3; + params.window_size_increment = 1; + _handler->use_dynamic_operation_throttling(true); + _handler->reconfigure_dynamic_throttler(params); + _handler->set_max_feed_op_batch_size(10); // > win size to make sure we test the right thing + + send_puts({{1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}}); + auto batch = next_batch(); // holds 3 throttle tokens + assert_batch(batch, 1, {{Put, 1}, {Put, 2}, {Put, 3}}); + // No more throttle tokens available + assert_empty_batch(next_batch()); +} + +} // storage diff --git a/storage/src/tests/persistence/filestorage/filestormanagertest.cpp b/storage/src/tests/persistence/filestorage/filestormanagertest.cpp index 1ccd51d3f06..f12b85eb2ea 100644 --- a/storage/src/tests/persistence/filestorage/filestormanagertest.cpp +++ b/storage/src/tests/persistence/filestorage/filestormanagertest.cpp @@ -43,6 +43,7 @@ LOG_SETUP(".filestormanagertest"); using std::unique_ptr; using document::Document; +using document::BucketId; using namespace storage::api; using storage::spi::test::makeSpiBucket; using document::test::makeDocumentBucket; @@ -405,6 +406,38 @@ TEST_F(FileStorManagerTest, put) { } } +TEST_F(FileStorManagerTest, feed_op_batch_updates_bucket_db_and_reply_bucket_info) { + PersistenceHandlerComponents c(*this); + c.filestorHandler->set_max_feed_op_batch_size(10); + BucketId bucket_id(16, 1); + createBucket(bucket_id); + constexpr uint32_t n = 10; + // No persistence thread started yet, so no chance of racing + for (uint32_t i = 0; i < n; ++i) { + auto put = make_put_command(120, vespalib::make_string("id:foo:testdoctype1:n=1:%u", i), Timestamp(1000) + i); + put->setAddress(_storage3); + c.filestorHandler->schedule(put); + } + auto pt = c.make_disk_thread(); + c.filestorHandler->flush(true); + c.top.waitForMessages(n, _waitTime); + c.executor.sync_all(); // Ensure all async reply processing tasks must have completed. + api::BucketInfo expected_bucket_info; + { + StorBucketDatabase::WrappedEntry entry(_node->getStorageBucketDatabase().get(bucket_id, "foo")); + ASSERT_TRUE(entry.exists()); + EXPECT_EQ(entry->getBucketInfo().getDocumentCount(), n); + expected_bucket_info = entry->getBucketInfo(); + } + // All replies should have the _same_ bucket info due to being processed in the same batch. + auto replies = c.top.getRepliesOnce(); + for (auto& reply : replies) { + auto actual_bucket_info = dynamic_cast<api::PutReply&>(*reply).getBucketInfo(); + EXPECT_EQ(actual_bucket_info, expected_bucket_info); + } + c.filestorHandler->close(); // Ensure persistence thread is no longer in message fetch code +} + TEST_F(FileStorManagerTest, running_task_against_unknown_bucket_fails) { TestFileStorComponents c(*this); @@ -726,7 +759,7 @@ TEST_F(FileStorManagerTest, handler_timeout) { filestorHandler.schedule(cmd); } - std::this_thread::sleep_for(51ms); + _node->getClock().addMilliSecondsToTime(51); for (;;) { auto lock = filestorHandler.getNextMessage(stripeId); if (lock.lock.get()) { diff --git a/storage/src/tests/persistence/filestorage/gtest_runner.cpp b/storage/src/tests/persistence/filestorage/gtest_runner.cpp index 5d1fde4130c..1ed7bc91843 100644 --- a/storage/src/tests/persistence/filestorage/gtest_runner.cpp +++ b/storage/src/tests/persistence/filestorage/gtest_runner.cpp @@ -1,8 +1,17 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/gtest/gtest.h> +#include <absl/debugging/failure_signal_handler.h> #include <vespa/log/log.h> LOG_SETUP("storage_filestorage_gtest_runner"); -GTEST_MAIN_RUN_ALL_TESTS() +int main(int argc, char* argv[]) { + absl::FailureSignalHandlerOptions opts; + opts.call_previous_handler = true; + opts.use_alternate_stack = false; // Suboptimal, but needed to get proper backtracing (for some reason...) + absl::InstallFailureSignalHandler(opts); + + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/storage/src/vespa/storage/persistence/asynchandler.cpp b/storage/src/vespa/storage/persistence/asynchandler.cpp index 59e0853cc21..ab176ebb9cb 100644 --- a/storage/src/vespa/storage/persistence/asynchandler.cpp +++ b/storage/src/vespa/storage/persistence/asynchandler.cpp @@ -143,7 +143,7 @@ AsyncHandler::AsyncHandler(const PersistenceUtil & env, spi::PersistenceProvider MessageTracker::UP AsyncHandler::handleRunTask(RunTaskCommand& cmd, MessageTracker::UP tracker) const { auto task = makeResultTask([tracker = std::move(tracker)](spi::Result::UP response) { - tracker->checkForError(*response); + (void)tracker->checkForError(*response); tracker->sendReply(); }); spi::Bucket bucket(cmd.getBucket()); @@ -169,7 +169,7 @@ AsyncHandler::handlePut(api::PutCommand& cmd, MessageTracker::UP trackerUP) cons spi::Bucket bucket = _env.getBucket(cmd.getDocumentId(), cmd.getBucket()); auto task = makeResultTask([tracker = std::move(trackerUP)](spi::Result::UP response) { - tracker->checkForError(*response); + (void)tracker->checkForError(*response); tracker->sendReply(); }); _spi.putAsync(bucket, spi::Timestamp(cmd.getTimestamp()), cmd.getDocument(), @@ -517,7 +517,7 @@ AsyncHandler::handleRemoveLocation(api::RemoveLocationCommand& cmd, MessageTrack } auto task = makeResultTask([&cmd, tracker = std::move(tracker), removed = to_remove.size()](spi::Result::UP response) { - tracker->checkForError(*response); + (void)tracker->checkForError(*response); tracker->setReply(std::make_shared<api::RemoveLocationReply>(cmd, removed)); tracker->sendReply(); }); diff --git a/storage/src/vespa/storage/persistence/batched_message.h b/storage/src/vespa/storage/persistence/batched_message.h new file mode 100644 index 00000000000..c23383edfde --- /dev/null +++ b/storage/src/vespa/storage/persistence/batched_message.h @@ -0,0 +1,14 @@ +// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.// +#pragma once + +#include "shared_operation_throttler.h" +#include <memory> +#include <utility> + +namespace storage { + +namespace api { class StorageMessage; } + +using BatchedMessage = std::pair<std::shared_ptr<api::StorageMessage>, ThrottleToken>; + +} diff --git a/storage/src/vespa/storage/persistence/filestorage/filestorhandler.cpp b/storage/src/vespa/storage/persistence/filestorage/filestorhandler.cpp index a89b705de1b..274d59899d9 100644 --- a/storage/src/vespa/storage/persistence/filestorage/filestorhandler.cpp +++ b/storage/src/vespa/storage/persistence/filestorage/filestorhandler.cpp @@ -5,4 +5,15 @@ namespace storage { FileStorHandler::LockedMessage::~LockedMessage() = default; +FileStorHandler::LockedMessageBatch::LockedMessageBatch(LockedMessage&& initial_msg) + : lock(std::move(initial_msg.lock)), + messages() +{ + if (lock) { + messages.emplace_back(std::move(initial_msg.msg), std::move(initial_msg.throttle_token)); + } +} + +FileStorHandler::LockedMessageBatch::~LockedMessageBatch() = default; + } diff --git a/storage/src/vespa/storage/persistence/filestorage/filestorhandler.h b/storage/src/vespa/storage/persistence/filestorage/filestorhandler.h index 68b8411c762..6a8b74baf1d 100644 --- a/storage/src/vespa/storage/persistence/filestorage/filestorhandler.h +++ b/storage/src/vespa/storage/persistence/filestorage/filestorhandler.h @@ -1,23 +1,13 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. - -/** - * \class storage::FileStorHandler - * \ingroup storage - * - * \brief Common resource for filestor threads - * - * Takes care of the interface between file stor threads and the file stor - * manager to avoid circular dependencies, and confine the implementation that - * needs to worry about locking between these components. - */ - #pragma once #include <vespa/document/bucket/bucket.h> #include <vespa/storage/storageutil/resumeguard.h> #include <vespa/storage/common/messagesender.h> +#include <vespa/storage/persistence/batched_message.h> #include <vespa/storage/persistence/shared_operation_throttler.h> #include <vespa/storageapi/messageapi/storagemessage.h> +#include <vespa/vespalib/util/small_vector.h> namespace storage { namespace api { @@ -80,13 +70,7 @@ public: std::shared_ptr<api::StorageMessage> msg; ThrottleToken throttle_token; - LockedMessage() noexcept = default; - LockedMessage(std::shared_ptr<BucketLockInterface> lock_, - std::shared_ptr<api::StorageMessage> msg_) noexcept - : lock(std::move(lock_)), - msg(std::move(msg_)), - throttle_token() - {} + constexpr LockedMessage() noexcept = default; LockedMessage(std::shared_ptr<BucketLockInterface> lock_, std::shared_ptr<api::StorageMessage> msg_, ThrottleToken token) noexcept @@ -98,27 +82,40 @@ public: ~LockedMessage(); }; + struct LockedMessageBatch { + std::shared_ptr<BucketLockInterface> lock; + vespalib::SmallVector<BatchedMessage, 1> messages; + + LockedMessageBatch() = default; + explicit LockedMessageBatch(LockedMessage&& initial_msg); + LockedMessageBatch(LockedMessageBatch&&) noexcept = default; + ~LockedMessageBatch(); + + [[nodiscard]] bool empty() const noexcept { return messages.empty(); } + [[nodiscard]] size_t size() const noexcept { return messages.size(); } + // Precondition: messages.size() == 1 + [[nodiscard]] LockedMessage release_as_single_msg() noexcept; + }; + class ScheduleAsyncResult { - private: - bool _was_scheduled; + bool _was_scheduled; LockedMessage _async_message; - public: - ScheduleAsyncResult() : _was_scheduled(false), _async_message() {} - explicit ScheduleAsyncResult(LockedMessage&& async_message_in) + constexpr ScheduleAsyncResult() noexcept : _was_scheduled(false), _async_message() {} + explicit ScheduleAsyncResult(LockedMessage&& async_message_in) noexcept : _was_scheduled(true), _async_message(std::move(async_message_in)) {} - bool was_scheduled() const { + [[nodiscard]] bool was_scheduled() const noexcept { return _was_scheduled; } - bool has_async_message() const { - return _async_message.lock.get() != nullptr; + [[nodiscard]] bool has_async_message() const noexcept { + return static_cast<bool>(_async_message.lock); } - const LockedMessage& async_message() const { + [[nodiscard]] const LockedMessage& async_message() const noexcept { return _async_message; } - LockedMessage&& release_async_message() { + [[nodiscard]] LockedMessage&& release_async_message() noexcept { return std::move(_async_message); } }; @@ -129,7 +126,7 @@ public: }; FileStorHandler() : _getNextMessageTimout(100ms) { } - virtual ~FileStorHandler() = default; + ~FileStorHandler() override = default; /** @@ -171,7 +168,9 @@ public: * * @param stripe The stripe to get messages for */ - virtual LockedMessage getNextMessage(uint32_t stripeId, vespalib::steady_time deadline) = 0; + [[nodiscard]] virtual LockedMessage getNextMessage(uint32_t stripeId, vespalib::steady_time deadline) = 0; + + [[nodiscard]] virtual LockedMessageBatch next_message_batch(uint32_t stripe, vespalib::steady_time now, vespalib::steady_time deadline) = 0; /** Only used for testing, should be removed */ LockedMessage getNextMessage(uint32_t stripeId) { @@ -189,8 +188,6 @@ public: * NB: As current operation can be a split or join operation, make sure that * you always wait for current to finish, if is a super or sub bucket of * the bucket we're locking. - * - * */ virtual BucketLockInterface::SP lock(const document::Bucket&, api::LockingRequirements lockReq) = 0; @@ -287,6 +284,8 @@ public: virtual void use_dynamic_operation_throttling(bool use_dynamic) noexcept = 0; virtual void set_throttle_apply_bucket_diff_ops(bool throttle_apply_bucket_diff) noexcept = 0; + + virtual void set_max_feed_op_batch_size(uint32_t max_batch) noexcept = 0; private: vespalib::duration _getNextMessageTimout; }; diff --git a/storage/src/vespa/storage/persistence/filestorage/filestorhandlerimpl.cpp b/storage/src/vespa/storage/persistence/filestorage/filestorhandlerimpl.cpp index 1984d44652a..7589fb3cdb3 100644 --- a/storage/src/vespa/storage/persistence/filestorage/filestorhandlerimpl.cpp +++ b/storage/src/vespa/storage/persistence/filestorage/filestorhandlerimpl.cpp @@ -12,6 +12,7 @@ #include <vespa/storage/persistence/messages.h> #include <vespa/storageapi/message/stat.h> #include <vespa/vespalib/stllike/hash_map.hpp> +#include <vespa/vespalib/stllike/hash_set.hpp> #include <vespa/vespalib/util/exceptions.h> #include <vespa/vespalib/util/string_escape.h> @@ -60,7 +61,8 @@ FileStorHandlerImpl::FileStorHandlerImpl(uint32_t numThreads, uint32_t numStripe _max_active_merges_per_stripe(per_stripe_merge_limit(numThreads, numStripes)), _paused(false), _throttle_apply_bucket_diff_ops(false), - _last_active_operations_stats() + _last_active_operations_stats(), + _max_feed_op_batch_size(1) { assert(numStripes > 0); _stripes.reserve(numStripes); @@ -241,8 +243,7 @@ FileStorHandlerImpl::schedule(const std::shared_ptr<api::StorageMessage>& msg) { if (getState() == FileStorHandler::AVAILABLE) { document::Bucket bucket = getStorageMessageBucket(*msg); - stripe(bucket).schedule(MessageEntry(msg, bucket)); - return true; + return stripe(bucket).schedule(MessageEntry(msg, bucket, _component.getClock().getMonotonicTime())); } return false; } @@ -252,7 +253,7 @@ FileStorHandlerImpl::schedule_and_get_next_async_message(const std::shared_ptr<a { if (getState() == FileStorHandler::AVAILABLE) { document::Bucket bucket = getStorageMessageBucket(*msg); - return ScheduleAsyncResult(stripe(bucket).schedule_and_get_next_async_message(MessageEntry(msg, bucket))); + return ScheduleAsyncResult(stripe(bucket).schedule_and_get_next_async_message(MessageEntry(msg, bucket, _component.getClock().getMonotonicTime()))); } return {}; } @@ -403,10 +404,25 @@ FileStorHandlerImpl::getNextMessage(uint32_t stripeId, vespalib::steady_time dea if (!tryHandlePause()) { return {}; // Still paused, return to allow tick. } - return _stripes[stripeId].getNextMessage(deadline); } +FileStorHandler::LockedMessageBatch +FileStorHandlerImpl::next_message_batch(uint32_t stripe_id, vespalib::steady_time now, vespalib::steady_time deadline) +{ + if (!tryHandlePause()) { + return {}; + } + return _stripes[stripe_id].next_message_batch(now, deadline); +} + +FileStorHandler::LockedMessage +FileStorHandlerImpl::LockedMessageBatch::release_as_single_msg() noexcept +{ + assert(lock && messages.size() == 1); + return {std::move(lock), std::move(messages[0].first), std::move(messages[0].second)}; +} + std::shared_ptr<FileStorHandler::BucketLockInterface> FileStorHandlerImpl::Stripe::lock(const document::Bucket &bucket, api::LockingRequirements lockReq) { std::unique_lock guard(*_lock); @@ -858,9 +874,10 @@ FileStorHandlerImpl::sendReplyDirectly(const std::shared_ptr<api::StorageReply>& } FileStorHandlerImpl::MessageEntry::MessageEntry(const std::shared_ptr<api::StorageMessage>& cmd, - const document::Bucket &bucket) + const document::Bucket& bucket, + vespalib::steady_time scheduled_at_time) : _command(cmd), - _timer(), + _timer(scheduled_at_time), _bucket(bucket), _priority(cmd->getPriority()) { } @@ -939,9 +956,8 @@ FileStorHandlerImpl::Stripe::operation_type_should_be_throttled(api::MessageType } FileStorHandler::LockedMessage -FileStorHandlerImpl::Stripe::getNextMessage(vespalib::steady_time deadline) +FileStorHandlerImpl::Stripe::next_message_impl(monitor_guard& guard, vespalib::steady_time deadline) { - std::unique_lock guard(*_lock); ThrottleToken throttle_token; // Try to grab a message+lock, immediately retrying once after a wait // if none can be found and then exiting if the same is the case on the @@ -993,6 +1009,93 @@ FileStorHandlerImpl::Stripe::getNextMessage(vespalib::steady_time deadline) } FileStorHandler::LockedMessage +FileStorHandlerImpl::Stripe::getNextMessage(vespalib::steady_time deadline) +{ + std::unique_lock guard(*_lock); + return next_message_impl(guard, deadline); +} + +namespace { + +constexpr bool is_batchable_feed_op(api::MessageType::Id id) noexcept { + return (id == api::MessageType::PUT_ID || + id == api::MessageType::REMOVE_ID || + id == api::MessageType::UPDATE_ID); +} + +// Precondition: msg must be a feed operation request (put, remove, update) +document::GlobalId gid_from_feed_op(const api::StorageMessage& msg) { + switch (msg.getType().getId()) { + case api::MessageType::PUT_ID: + return static_cast<const api::PutCommand&>(msg).getDocumentId().getGlobalId(); + case api::MessageType::REMOVE_ID: + return static_cast<const api::RemoveCommand&>(msg).getDocumentId().getGlobalId(); + case api::MessageType::UPDATE_ID: + return static_cast<const api::UpdateCommand&>(msg).getDocumentId().getGlobalId(); + default: abort(); + } +} + +} // anon ns + +FileStorHandler::LockedMessageBatch +FileStorHandlerImpl::Stripe::next_message_batch(vespalib::steady_time now, vespalib::steady_time deadline) +{ + const auto max_batch_size = _owner.max_feed_op_batch_size(); + + std::unique_lock guard(*_lock); + auto initial_locked = next_message_impl(guard, deadline); + if (!initial_locked.lock || !is_batchable_feed_op(initial_locked.msg->getType().getId()) || (max_batch_size == 1)) { + return LockedMessageBatch(std::move(initial_locked)); + } + LockedMessageBatch batch(std::move(initial_locked)); + fill_feed_op_batch(guard, batch, max_batch_size, now); + return batch; +} + +void +FileStorHandlerImpl::Stripe::fill_feed_op_batch(monitor_guard& guard, LockedMessageBatch& batch, + uint32_t max_batch_size, vespalib::steady_time now) +{ + assert(batch.size() == 1); + assert(guard.owns_lock()); + BucketIdx& idx = bmi::get<2>(*_queue); + auto bucket_msgs = idx.equal_range(batch.lock->getBucket()); + // Process in FIFO order (_not_ priority order) until we hit the end, a non-batchable operation + // (implicit pipeline stall since bucket set might change) or can't get another throttle token. + // We also stall the pipeline if we get a concurrent modification to the same document (not expected, + // as the distributors should prevent this, but _technically_ it is possible). + const auto expected_max_size = std::min(ssize_t(max_batch_size), std::distance(bucket_msgs.first, bucket_msgs.second) + 1); + vespalib::hash_set<document::GlobalId, document::GlobalId::hash> gids_in_batch(expected_max_size); + gids_in_batch.insert(gid_from_feed_op(*batch.messages[0].first)); + for (auto it = bucket_msgs.first; (it != bucket_msgs.second) && (batch.messages.size() < max_batch_size);) { + if (!is_batchable_feed_op(it->_command->getType().getId())) { + break; + } + auto [existing_iter, inserted] = gids_in_batch.insert(gid_from_feed_op(*it->_command)); + if (!inserted) { + break; // Already present in batch + } + if (messageTimedOutInQueue(*it->_command, now - it->_timer.start_time())) { + // We just ignore timed out ops here; actually generating a timeout reply will be done by + // next_message_impl() during a subsequent invocation. This avoids having to deal with any + // potential issues caused by sending a reply up while holding the queue lock, since we + // can't release it here. + ++it; + continue; + } + auto throttle_token = _owner.operation_throttler().try_acquire_one(); + if (!throttle_token.valid()) { + break; + } + // Note: iterator is const; can't std::move(it->_command) + batch.messages.emplace_back(it->_command, std::move(throttle_token)); + it = idx.erase(it); + } + update_cached_queue_size(guard); +} + +FileStorHandler::LockedMessage FileStorHandlerImpl::Stripe::get_next_async_message(monitor_guard& guard) { if (_owner.isPaused()) { @@ -1021,9 +1124,11 @@ FileStorHandler::LockedMessage FileStorHandlerImpl::Stripe::getMessage(monitor_guard & guard, PriorityIdx & idx, PriorityIdx::iterator iter, ThrottleToken throttle_token) { - std::chrono::milliseconds waitTime(uint64_t(iter->_timer.stop(_metrics->averageQueueWaitingTime))); + std::chrono::milliseconds waitTime(uint64_t(iter->_timer.stop( + _owner._component.getClock().getMonotonicTime(), + _metrics->averageQueueWaitingTime))); - std::shared_ptr<api::StorageMessage> msg = std::move(iter->_command); + std::shared_ptr<api::StorageMessage> msg = iter->_command; // iter is const; can't std::move() document::Bucket bucket(iter->_bucket); idx.erase(iter); // iter not used after this point. update_cached_queue_size(guard); @@ -1032,7 +1137,6 @@ FileStorHandlerImpl::Stripe::getMessage(monitor_guard & guard, PriorityIdx & idx auto locker = std::make_unique<BucketLock>(guard, *this, bucket, msg->getPriority(), msg->getType().getId(), msg->getMsgId(), msg->lockingRequirements()); - guard.unlock(); return {std::move(locker), std::move(msg), std::move(throttle_token)}; } else { std::shared_ptr<api::StorageReply> msgReply(makeQueueTimeoutReply(*msg)); diff --git a/storage/src/vespa/storage/persistence/filestorage/filestorhandlerimpl.h b/storage/src/vespa/storage/persistence/filestorage/filestorhandlerimpl.h index f7c9b218779..ac8e5c52cbf 100644 --- a/storage/src/vespa/storage/persistence/filestorage/filestorhandlerimpl.h +++ b/storage/src/vespa/storage/persistence/filestorage/filestorhandlerimpl.h @@ -55,7 +55,9 @@ public: document::Bucket _bucket; uint8_t _priority; - MessageEntry(const std::shared_ptr<api::StorageMessage>& cmd, const document::Bucket &bId); + MessageEntry(const std::shared_ptr<api::StorageMessage>& cmd, + const document::Bucket& bucket, + vespalib::steady_time scheduled_at_time); MessageEntry(MessageEntry &&) noexcept ; MessageEntry(const MessageEntry &) noexcept; MessageEntry & operator = (const MessageEntry &) = delete; @@ -66,13 +68,13 @@ public: } }; - using PriorityOrder = bmi::ordered_non_unique<bmi::identity<MessageEntry> >; - using BucketOrder = bmi::ordered_non_unique<bmi::member<MessageEntry, document::Bucket, &MessageEntry::_bucket>>; - + // ordered_non_unique shall preserve insertion order as iteration order of equal keys, but this is rather magical... + using PriorityOrder = bmi::ordered_non_unique<bmi::identity<MessageEntry>>; + using BucketOrder = bmi::ordered_non_unique<bmi::member<MessageEntry, document::Bucket, &MessageEntry::_bucket>>; using PriorityQueue = bmi::multi_index_container<MessageEntry, bmi::indexed_by<bmi::sequenced<>, PriorityOrder, BucketOrder>>; + using PriorityIdx = bmi::nth_index<PriorityQueue, 1>::type; + using BucketIdx = bmi::nth_index<PriorityQueue, 2>::type; - using PriorityIdx = bmi::nth_index<PriorityQueue, 1>::type; - using BucketIdx = bmi::nth_index<PriorityQueue, 2>::type; using Clock = std::chrono::steady_clock; using monitor_guard = std::unique_lock<std::mutex>; using atomic_size_t = vespalib::datastore::AtomicValueWrapper<size_t>; @@ -114,7 +116,7 @@ public: ActiveOperationsStats &stats() { return _stats; } }; SafeActiveOperationsStats() : _lock(std::make_unique<std::mutex>()), _stats() {} - Guard guard() { return Guard(*_lock, _stats, ctor_tag()); } + [[nodiscard]] Guard guard() { return Guard(*_lock, _stats, ctor_tag()); } }; Stripe(const FileStorHandlerImpl & owner, MessageSender & messageSender); @@ -123,8 +125,8 @@ public: Stripe & operator =(const Stripe &) = delete; ~Stripe(); void flush(); - bool schedule(MessageEntry messageEntry); - FileStorHandler::LockedMessage schedule_and_get_next_async_message(MessageEntry entry); + [[nodiscard]] bool schedule(MessageEntry messageEntry); + [[nodiscard]] FileStorHandler::LockedMessage schedule_and_get_next_async_message(MessageEntry entry); void waitUntilNoLocks() const; void abort(std::vector<std::shared_ptr<api::StorageReply>> & aborted, const AbortBucketOperationsCommand& cmd); void waitInactive(const AbortBucketOperationsCommand& cmd) const; @@ -151,18 +153,19 @@ public: api::LockingRequirements lockReq, bool count_as_active_merge, const LockEntry & lockEntry); - std::shared_ptr<FileStorHandler::BucketLockInterface> lock(const document::Bucket & bucket, api::LockingRequirements lockReq); + [[nodiscard]] std::shared_ptr<FileStorHandler::BucketLockInterface> lock(const document::Bucket & bucket, api::LockingRequirements lockReq); void failOperations(const document::Bucket & bucket, const api::ReturnCode & code); - FileStorHandler::LockedMessage getNextMessage(vespalib::steady_time deadline); + [[nodiscard]] FileStorHandler::LockedMessage getNextMessage(vespalib::steady_time deadline); + [[nodiscard]] FileStorHandler::LockedMessageBatch next_message_batch(vespalib::steady_time now, vespalib::steady_time deadline); void dumpQueue(std::ostream & os) const; void dumpActiveHtml(std::ostream & os) const; void dumpQueueHtml(std::ostream & os) const; - std::mutex & exposeLock() { return *_lock; } - PriorityQueue & exposeQueue() { return *_queue; } - BucketIdx & exposeBucketIdx() { return bmi::get<2>(*_queue); } + [[nodiscard]] std::mutex & exposeLock() { return *_lock; } + [[nodiscard]] PriorityQueue & exposeQueue() { return *_queue; } + [[nodiscard]] BucketIdx & exposeBucketIdx() { return bmi::get<2>(*_queue); } void setMetrics(FileStorStripeMetrics * metrics) { _metrics = metrics; } - ActiveOperationsStats get_active_operations_stats(bool reset_min_max) const; + [[nodiscard]] ActiveOperationsStats get_active_operations_stats(bool reset_min_max) const; private: void update_cached_queue_size(const std::lock_guard<std::mutex> &) { _cached_queue_size.store_relaxed(_queue->size()); @@ -170,15 +173,20 @@ public: void update_cached_queue_size(const std::unique_lock<std::mutex> &) { _cached_queue_size.store_relaxed(_queue->size()); } - bool hasActive(monitor_guard & monitor, const AbortBucketOperationsCommand& cmd) const; - FileStorHandler::LockedMessage get_next_async_message(monitor_guard& guard); + [[nodiscard]] bool hasActive(monitor_guard & monitor, const AbortBucketOperationsCommand& cmd) const; + [[nodiscard]] FileStorHandler::LockedMessage get_next_async_message(monitor_guard& guard); [[nodiscard]] bool operation_type_should_be_throttled(api::MessageType::Id type_id) const noexcept; + [[nodiscard]] FileStorHandler::LockedMessage next_message_impl(monitor_guard& held_lock, + vespalib::steady_time deadline); + void fill_feed_op_batch(monitor_guard& held_lock, LockedMessageBatch& batch, + uint32_t max_batch_size, vespalib::steady_time now); + // Precondition: the bucket used by `iter`s operation is not locked in a way that conflicts // with its locking requirements. - FileStorHandler::LockedMessage getMessage(monitor_guard & guard, PriorityIdx & idx, - PriorityIdx::iterator iter, - ThrottleToken throttle_token); + [[nodiscard]] FileStorHandler::LockedMessage getMessage(monitor_guard & guard, PriorityIdx & idx, + PriorityIdx::iterator iter, + ThrottleToken throttle_token); using LockedBuckets = vespalib::hash_map<document::Bucket, MultiLockEntry, document::Bucket::hash>; const FileStorHandlerImpl &_owner; MessageSender &_messageSender; @@ -233,7 +241,8 @@ public: bool schedule(const std::shared_ptr<api::StorageMessage>&) override; ScheduleAsyncResult schedule_and_get_next_async_message(const std::shared_ptr<api::StorageMessage>& msg) override; - FileStorHandler::LockedMessage getNextMessage(uint32_t stripeId, vespalib::steady_time deadline) override; + LockedMessage getNextMessage(uint32_t stripeId, vespalib::steady_time deadline) override; + LockedMessageBatch next_message_batch(uint32_t stripe, vespalib::steady_time now, vespalib::steady_time deadline) override; void remapQueueAfterJoin(const RemapInfo& source, RemapInfo& target) override; void remapQueueAfterSplit(const RemapInfo& source, RemapInfo& target1, RemapInfo& target2) override; @@ -292,6 +301,13 @@ public: _throttle_apply_bucket_diff_ops.store(throttle_apply_bucket_diff, std::memory_order_relaxed); } + void set_max_feed_op_batch_size(uint32_t max_batch) noexcept override { + _max_feed_op_batch_size.store(max_batch, std::memory_order_relaxed); + } + [[nodiscard]] uint32_t max_feed_op_batch_size() const noexcept { + return _max_feed_op_batch_size.load(std::memory_order_relaxed); + } + // Implements ResumeGuard::Callback void resume() override; @@ -316,6 +332,7 @@ private: std::atomic<bool> _paused; std::atomic<bool> _throttle_apply_bucket_diff_ops; std::optional<ActiveOperationsStats> _last_active_operations_stats; + std::atomic<uint32_t> _max_feed_op_batch_size; // Returns the index in the targets array we are sending to, or -1 if none of them match. int calculateTargetBasedOnDocId(const api::StorageMessage& msg, std::vector<RemapInfo*>& targets); diff --git a/storage/src/vespa/storage/persistence/filestorage/filestormanager.cpp b/storage/src/vespa/storage/persistence/filestorage/filestormanager.cpp index 0046bd96b65..23de39f7130 100644 --- a/storage/src/vespa/storage/persistence/filestorage/filestormanager.cpp +++ b/storage/src/vespa/storage/persistence/filestorage/filestormanager.cpp @@ -239,6 +239,7 @@ FileStorManager::on_configure(const StorFilestorConfig& config) auto updated_dyn_throttle_params = dynamic_throttle_params_from_config(config, _threads.size()); _filestorHandler->reconfigure_dynamic_throttler(updated_dyn_throttle_params); } + _filestorHandler->set_max_feed_op_batch_size(std::max(1, config.maxFeedOpBatchSize)); // TODO remove once desired throttling behavior is set in stone { _filestorHandler->use_dynamic_operation_throttling(use_dynamic_throttling); diff --git a/storage/src/vespa/storage/persistence/persistencehandler.cpp b/storage/src/vespa/storage/persistence/persistencehandler.cpp index 0612798b43a..a01a4656d01 100644 --- a/storage/src/vespa/storage/persistence/persistencehandler.cpp +++ b/storage/src/vespa/storage/persistence/persistencehandler.cpp @@ -134,7 +134,7 @@ PersistenceHandler::processMessage(api::StorageMessage& msg, MessageTracker::UP _env._metrics.operations.inc(); if (msg.getType().isReply()) { - try{ + try { LOG(debug, "Handling reply: %s", msg.toString().c_str()); LOG(spam, "Message content: %s", msg.toString(true).c_str()); return handleReply(static_cast<api::StorageReply&>(msg), std::move(tracker)); @@ -161,9 +161,7 @@ PersistenceHandler::processMessage(api::StorageMessage& msg, MessageTracker::UP void PersistenceHandler::processLockedMessage(FileStorHandler::LockedMessage lock) const { - LOG(debug, "NodeIndex %d, ptr=%p", _env._nodeIndex, lock.msg.get()); api::StorageMessage & msg(*lock.msg); - // Important: we _copy_ the message shared_ptr instead of moving to ensure that `msg` remains // valid even if the tracker is destroyed by an exception in processMessage(). auto tracker = std::make_unique<MessageTracker>(framework::MilliSecTimer(_clock), _env, _env._fileStorHandler, @@ -174,4 +172,24 @@ PersistenceHandler::processLockedMessage(FileStorHandler::LockedMessage lock) co } } +void +PersistenceHandler::process_locked_message_batch(std::shared_ptr<FileStorHandler::BucketLockInterface> lock, + std::span<BatchedMessage> bucket_messages) +{ + const auto bucket = lock->getBucket(); + auto batch = std::make_shared<AsyncMessageBatch>(std::move(lock), _env, _env._fileStorHandler); + for (auto& bm : bucket_messages) { + assert(bm.first->getBucket() == bucket); + // Important: we _copy_ the message shared_ptr instead of moving to ensure that `*bm.first` remains + // valid even if the tracker is destroyed by an exception in processMessage(). All std::exceptions + // are caught there, so we do not expect our loop to be interrupted. + auto tracker = std::make_unique<MessageTracker>(framework::MilliSecTimer(_clock), _env, batch, + batch->deferred_sender_stub(), bm.first, std::move(bm.second)); + tracker = processMessage(*bm.first, std::move(tracker)); + if (tracker) { + tracker->sendReply(); // Actually defers to batch reply queue + } + } +} + } diff --git a/storage/src/vespa/storage/persistence/persistencehandler.h b/storage/src/vespa/storage/persistence/persistencehandler.h index 0da518a1cfa..224bb70a16b 100644 --- a/storage/src/vespa/storage/persistence/persistencehandler.h +++ b/storage/src/vespa/storage/persistence/persistencehandler.h @@ -2,14 +2,16 @@ #pragma once -#include "processallhandler.h" -#include "mergehandler.h" #include "asynchandler.h" +#include "batched_message.h" +#include "mergehandler.h" #include "persistenceutil.h" -#include "splitjoinhandler.h" +#include "processallhandler.h" #include "simplemessagehandler.h" +#include "splitjoinhandler.h" #include <vespa/storage/common/storagecomponent.h> #include <vespa/vespalib/util/isequencedtaskexecutor.h> +#include <span> namespace storage { @@ -29,6 +31,8 @@ public: ~PersistenceHandler(); void processLockedMessage(FileStorHandler::LockedMessage lock) const; + void process_locked_message_batch(std::shared_ptr<FileStorHandler::BucketLockInterface> lock, + std::span<BatchedMessage> bucket_messages); //TODO Rewrite tests to avoid this api leak const AsyncHandler & asyncHandler() const { return _asyncHandler; } diff --git a/storage/src/vespa/storage/persistence/persistencethread.cpp b/storage/src/vespa/storage/persistence/persistencethread.cpp index a98418281d2..5710c3fe26f 100644 --- a/storage/src/vespa/storage/persistence/persistencethread.cpp +++ b/storage/src/vespa/storage/persistence/persistencethread.cpp @@ -14,6 +14,7 @@ PersistenceThread::PersistenceThread(PersistenceHandler & persistenceHandler, Fi uint32_t stripeId, framework::Component & component) : _persistenceHandler(persistenceHandler), _fileStorHandler(fileStorHandler), + _clock(component.getClock()), _stripeId(stripeId), _thread() { @@ -36,14 +37,19 @@ PersistenceThread::run(framework::ThreadHandle& thread) vespalib::duration max_wait_time = vespalib::adjustTimeoutByDetectedHz(100ms); while (!thread.interrupted()) { - vespalib::steady_time now = vespalib::steady_clock::now(); + vespalib::steady_time now = _clock.getMonotonicTime(); thread.registerTick(framework::UNKNOWN_CYCLE, now); vespalib::steady_time deadline = now + max_wait_time; - FileStorHandler::LockedMessage lock(_fileStorHandler.getNextMessage(_stripeId, deadline)); - - if (lock.lock) { - _persistenceHandler.processLockedMessage(std::move(lock)); + auto batch = _fileStorHandler.next_message_batch(_stripeId, now, deadline); + if (!batch.empty()) { + // Special-case single message batches, as actually scheduling a full batch has more + // overhead due to extra bookkeeping state and deferred reply-sending. + if (batch.size() == 1) { + _persistenceHandler.processLockedMessage(batch.release_as_single_msg()); + } else { + _persistenceHandler.process_locked_message_batch(std::move(batch.lock), batch.messages); + } } } LOG(debug, "Closing down persistence thread"); diff --git a/storage/src/vespa/storage/persistence/persistencethread.h b/storage/src/vespa/storage/persistence/persistencethread.h index aacd1dd4830..2e9852ada73 100644 --- a/storage/src/vespa/storage/persistence/persistencethread.h +++ b/storage/src/vespa/storage/persistence/persistencethread.h @@ -8,6 +8,7 @@ namespace storage { namespace framework { + struct Clock; class Component; class Thread; } @@ -27,10 +28,11 @@ public: framework::Thread& getThread() override { return *_thread; } private: - PersistenceHandler & _persistenceHandler; - FileStorHandler & _fileStorHandler; - uint32_t _stripeId; - std::unique_ptr<framework::Thread> _thread; + PersistenceHandler& _persistenceHandler; + FileStorHandler& _fileStorHandler; + const framework::Clock& _clock; + uint32_t _stripeId; + std::unique_ptr<framework::Thread> _thread; void run(framework::ThreadHandle&) override; }; diff --git a/storage/src/vespa/storage/persistence/persistenceutil.cpp b/storage/src/vespa/storage/persistence/persistenceutil.cpp index c975721c855..febc494aff1 100644 --- a/storage/src/vespa/storage/persistence/persistenceutil.cpp +++ b/storage/src/vespa/storage/persistence/persistenceutil.cpp @@ -11,41 +11,83 @@ LOG_SETUP(".persistence.util"); namespace storage { namespace { - bool isBatchable(api::MessageType::Id id) - { - return (id == api::MessageType::PUT_ID || - id == api::MessageType::REMOVE_ID || - id == api::MessageType::UPDATE_ID); - } - bool hasBucketInfo(api::MessageType::Id id) - { - return (isBatchable(id) || - (id == api::MessageType::REMOVELOCATION_ID || - id == api::MessageType::JOINBUCKETS_ID)); +constexpr bool is_batchable(api::MessageType::Id id) noexcept { + return (id == api::MessageType::PUT_ID || + id == api::MessageType::REMOVE_ID || + id == api::MessageType::UPDATE_ID); +} + +constexpr bool has_bucket_info(api::MessageType::Id id) noexcept { + return (is_batchable(id) || + (id == api::MessageType::REMOVELOCATION_ID || + id == api::MessageType::JOINBUCKETS_ID)); +} + +constexpr vespalib::duration WARN_ON_SLOW_OPERATIONS = 5s; + +} // anon ns + +DeferredReplySenderStub::DeferredReplySenderStub() = default; +DeferredReplySenderStub::~DeferredReplySenderStub() = default; + +AsyncMessageBatch::AsyncMessageBatch(std::shared_ptr<FileStorHandler::BucketLockInterface> bucket_lock, + const PersistenceUtil& env, + MessageSender& reply_sender) noexcept + : _bucket_lock(std::move(bucket_lock)), + _env(env), + _reply_sender(reply_sender), + _deferred_sender_stub() +{ + assert(_bucket_lock); +} + +AsyncMessageBatch::~AsyncMessageBatch() { + const auto bucket_info = _env.getBucketInfo(_bucket_lock->getBucket()); + _env.updateBucketDatabase(_bucket_lock->getBucket(), bucket_info); + + std::lock_guard lock(_deferred_sender_stub._mutex); // Ensure visibility of posted replies + for (auto& reply : _deferred_sender_stub._deferred_replies) { + if (reply->getResult().success()) { + dynamic_cast<api::BucketInfoReply&>(*reply).setBucketInfo(bucket_info); + } + _reply_sender.sendReplyDirectly(reply); } - const vespalib::duration WARN_ON_SLOW_OPERATIONS = 5s; + LOG(debug, "Processed async feed message batch of %zu ops for %s. New bucket info is %s", + _deferred_sender_stub._deferred_replies.size(), + _bucket_lock->getBucket().toString().c_str(), bucket_info.toString().c_str()); } MessageTracker::MessageTracker(const framework::MilliSecTimer & timer, const PersistenceUtil & env, MessageSender & replySender, FileStorHandler::BucketLockInterface::SP bucketLock, - api::StorageMessage::SP msg, + std::shared_ptr<api::StorageMessage> msg, ThrottleToken throttle_token) - : MessageTracker(timer, env, replySender, true, std::move(bucketLock), std::move(msg), std::move(throttle_token)) + : MessageTracker(timer, env, replySender, true, std::move(bucketLock), {}, std::move(msg), std::move(throttle_token)) +{} + +MessageTracker::MessageTracker(const framework::MilliSecTimer& timer, + const PersistenceUtil& env, + std::shared_ptr<AsyncMessageBatch> batch, + MessageSender& deferred_reply_sender, + std::shared_ptr<api::StorageMessage> msg, + ThrottleToken throttle_token) + : MessageTracker(timer, env, deferred_reply_sender, false, {}, std::move(batch), std::move(msg), std::move(throttle_token)) {} MessageTracker::MessageTracker(const framework::MilliSecTimer & timer, const PersistenceUtil & env, MessageSender & replySender, - bool updateBucketInfo, - FileStorHandler::BucketLockInterface::SP bucketLock, - api::StorageMessage::SP msg, + bool update_bucket_info, + std::shared_ptr<FileStorHandler::BucketLockInterface> bucket_lock, + std::shared_ptr<AsyncMessageBatch> part_of_batch, + std::shared_ptr<api::StorageMessage> msg, ThrottleToken throttle_token) : _sendReply(true), - _updateBucketInfo(updateBucketInfo && hasBucketInfo(msg->getType().getId())), - _bucketLock(std::move(bucketLock)), + _updateBucketInfo(update_bucket_info && has_bucket_info(msg->getType().getId())), + _bucketLock(std::move(bucket_lock)), + _part_of_batch(std::move(part_of_batch)), _msg(std::move(msg)), _throttle_token(std::move(throttle_token)), _context(_msg->getPriority(), _msg->getTrace().getLevel()), @@ -61,7 +103,7 @@ MessageTracker::createForTesting(const framework::MilliSecTimer & timer, Persist FileStorHandler::BucketLockInterface::SP bucketLock, api::StorageMessage::SP msg) { return MessageTracker::UP(new MessageTracker(timer, env, replySender, false, std::move(bucketLock), - std::move(msg), ThrottleToken())); + {}, std::move(msg), ThrottleToken())); } void @@ -102,6 +144,7 @@ MessageTracker::sendReply() { if (hasReply()) { getReply().getTrace().addChild(_context.steal_trace()); if (_updateBucketInfo) { + assert(_bucketLock); if (getReply().getResult().success()) { _env.setBucketInfo(*this, _bucketLock->getBucket()); } @@ -163,7 +206,7 @@ MessageTracker::generateReply(api::StorageCommand& cmd) std::shared_ptr<FileStorHandler::OperationSyncPhaseDoneNotifier> MessageTracker::sync_phase_done_notifier_or_nullptr() const { - if (_bucketLock->wants_sync_phase_done_notification()) { + if (_bucketLock && _bucketLock->wants_sync_phase_done_notification()) { return _bucketLock; } return {}; @@ -236,7 +279,7 @@ PersistenceUtil::setBucketInfo(MessageTracker& tracker, const document::Bucket & { api::BucketInfo info = getBucketInfo(bucket); - static_cast<api::BucketInfoReply&>(tracker.getReply()).setBucketInfo(info); + dynamic_cast<api::BucketInfoReply&>(tracker.getReply()).setBucketInfo(info); updateBucketDatabase(bucket, info); } diff --git a/storage/src/vespa/storage/persistence/persistenceutil.h b/storage/src/vespa/storage/persistence/persistenceutil.h index 900f301252e..67e96befe00 100644 --- a/storage/src/vespa/storage/persistence/persistenceutil.h +++ b/storage/src/vespa/storage/persistence/persistenceutil.h @@ -25,12 +25,52 @@ namespace storage { class PersistenceUtil; +struct DeferredReplySenderStub : MessageSender { + std::mutex _mutex; + std::vector<std::shared_ptr<api::StorageReply>> _deferred_replies; + + DeferredReplySenderStub(); + ~DeferredReplySenderStub() override; + + void sendCommand(const std::shared_ptr<api::StorageCommand>&) override { + abort(); // Not supported + } + void sendReply(const std::shared_ptr<api::StorageReply>& reply) override { + std::lock_guard lock(_mutex); + _deferred_replies.emplace_back(reply); + } +}; + +class AsyncMessageBatch { + std::shared_ptr<FileStorHandler::BucketLockInterface> _bucket_lock; + const PersistenceUtil& _env; + MessageSender& _reply_sender; + DeferredReplySenderStub _deferred_sender_stub; +public: + AsyncMessageBatch(std::shared_ptr<FileStorHandler::BucketLockInterface> bucket_lock, + const PersistenceUtil& env, + MessageSender& reply_sender) noexcept; + // Triggered by last referencing batched MessageTracker being destroyed. + // Fetches bucket info, updates DB and sends all deferred replies with the new bucket info. + ~AsyncMessageBatch(); + + [[nodiscard]] MessageSender& deferred_sender_stub() noexcept { return _deferred_sender_stub; } +}; + class MessageTracker { public: using UP = std::unique_ptr<MessageTracker>; - MessageTracker(const framework::MilliSecTimer & timer, const PersistenceUtil & env, MessageSender & replySender, - FileStorHandler::BucketLockInterface::SP bucketLock, std::shared_ptr<api::StorageMessage> msg, + MessageTracker(const framework::MilliSecTimer & timer, const PersistenceUtil & env, MessageSender & reply_sender, + FileStorHandler::BucketLockInterface::SP bucket_lock, std::shared_ptr<api::StorageMessage> msg, + ThrottleToken throttle_token); + + // For use with batching where bucket lock is held separately and bucket info + // is _not_ fetched or updated per message. + MessageTracker(const framework::MilliSecTimer& timer, const PersistenceUtil& env, + std::shared_ptr<AsyncMessageBatch> batch, + MessageSender& deferred_reply_sender, + std::shared_ptr<api::StorageMessage> msg, ThrottleToken throttle_token); ~MessageTracker(); @@ -58,48 +98,53 @@ public: * commands like merge. */ void dontReply() { _sendReply = false; } - bool hasReply() const { return bool(_reply); } - const api::StorageReply & getReply() const { + [[nodiscard]] bool hasReply() const { return bool(_reply); } + [[nodiscard]] const api::StorageReply & getReply() const { return *_reply; } - api::StorageReply & getReply() { + [[nodiscard]] api::StorageReply & getReply() { return *_reply; } - std::shared_ptr<api::StorageReply> && stealReplySP() && { + [[nodiscard]] std::shared_ptr<api::StorageReply> && stealReplySP() && { return std::move(_reply); } void generateReply(api::StorageCommand& cmd); - api::ReturnCode getResult() const { return _result; } + [[nodiscard]] api::ReturnCode getResult() const { return _result; } - spi::Context & context() { return _context; } - document::BucketId getBucketId() const { + [[nodiscard]] spi::Context & context() { return _context; } + [[nodiscard]] document::BucketId getBucketId() const { return _bucketLock->getBucket().getBucketId(); } void sendReply(); - bool checkForError(const spi::Result& response); + [[nodiscard]] bool checkForError(const spi::Result& response); // Returns a non-nullptr notifier instance iff the underlying operation wants to be notified - // when the sync phase is complete. Otherwise returns a nullptr shared_ptr. - std::shared_ptr<FileStorHandler::OperationSyncPhaseDoneNotifier> sync_phase_done_notifier_or_nullptr() const; + // when the sync phase is complete. Otherwise, returns a nullptr shared_ptr. + [[nodiscard]] std::shared_ptr<FileStorHandler::OperationSyncPhaseDoneNotifier> sync_phase_done_notifier_or_nullptr() const; static MessageTracker::UP createForTesting(const framework::MilliSecTimer & timer, PersistenceUtil & env, MessageSender & replySender, FileStorHandler::BucketLockInterface::SP bucketLock, std::shared_ptr<api::StorageMessage> msg); private: - MessageTracker(const framework::MilliSecTimer & timer, const PersistenceUtil & env, MessageSender & replySender, bool updateBucketInfo, - FileStorHandler::BucketLockInterface::SP bucketLock, std::shared_ptr<api::StorageMessage> msg, + MessageTracker(const framework::MilliSecTimer& timer, const PersistenceUtil& env, + MessageSender& reply_sender, bool update_bucket_info, + std::shared_ptr<FileStorHandler::BucketLockInterface> bucket_lock, + std::shared_ptr<AsyncMessageBatch> part_of_batch, + std::shared_ptr<api::StorageMessage> msg, ThrottleToken throttle_token); [[nodiscard]] bool count_result_as_failure() const noexcept; bool _sendReply; bool _updateBucketInfo; + // Either _bucketLock or _part_of_batch must be set, never both at the same time FileStorHandler::BucketLockInterface::SP _bucketLock; + std::shared_ptr<AsyncMessageBatch> _part_of_batch; // nullptr if not batched std::shared_ptr<api::StorageMessage> _msg; ThrottleToken _throttle_token; spi::Context _context; @@ -117,8 +162,6 @@ public: struct LockResult { std::shared_ptr<FileStorHandler::BucketLockInterface> lock; LockResult() : lock() {} - - bool bucketExisted() const { return bool(lock); } }; PersistenceUtil(const ServiceLayerComponent&, FileStorHandler& fileStorHandler, diff --git a/storage/src/vespa/storageframework/defaultimplementation/clock/realclock.h b/storage/src/vespa/storageframework/defaultimplementation/clock/realclock.h index 277e7b4fdfd..93b305370e0 100644 --- a/storage/src/vespa/storageframework/defaultimplementation/clock/realclock.h +++ b/storage/src/vespa/storageframework/defaultimplementation/clock/realclock.h @@ -13,7 +13,7 @@ namespace storage::framework::defaultimplementation { -struct RealClock : public Clock { +struct RealClock final : public Clock { vespalib::steady_time getMonotonicTime() const override; vespalib::system_time getSystemTime() const override; }; diff --git a/storageserver/src/apps/storaged/CMakeLists.txt b/storageserver/src/apps/storaged/CMakeLists.txt index 67377c6cba3..25bf1ced552 100644 --- a/storageserver/src/apps/storaged/CMakeLists.txt +++ b/storageserver/src/apps/storaged/CMakeLists.txt @@ -8,6 +8,7 @@ vespa_add_executable(storageserver_storaged_app DEPENDS storageserver_storageapp protobuf::libprotobuf + absl::failure_signal_handler ) vespa_add_target_package_dependency(storageserver_storaged_app Protobuf) diff --git a/storageserver/src/apps/storaged/storage.cpp b/storageserver/src/apps/storaged/storage.cpp index fe3bf696e9a..cffc03a585b 100644 --- a/storageserver/src/apps/storaged/storage.cpp +++ b/storageserver/src/apps/storaged/storage.cpp @@ -21,6 +21,7 @@ #include <vespa/config/helper/configgetter.hpp> #include <vespa/vespalib/util/signalhandler.h> #include <google/protobuf/message_lite.h> +#include <absl/debugging/failure_signal_handler.h> #include <iostream> #include <csignal> #include <cstdlib> @@ -213,8 +214,15 @@ int StorageApp::main(int argc, char **argv) } // storage int main(int argc, char **argv) { + absl::FailureSignalHandlerOptions opts; + // See `searchcore/src/apps/proton/proton.cpp` for parameter and handler ordering rationale. + opts.call_previous_handler = true; + opts.use_alternate_stack = false; + absl::InstallFailureSignalHandler(opts); + vespalib::SignalHandler::PIPE.ignore(); vespalib::SignalHandler::enable_cross_thread_stack_tracing(); + storage::StorageApp app; storage::sigtramp = &app; int retval = app.main(argc,argv); diff --git a/storageserver/src/vespa/storageserver/app/servicelayerprocess.cpp b/storageserver/src/vespa/storageserver/app/servicelayerprocess.cpp index abeaf06b4ad..d1eed61ba48 100644 --- a/storageserver/src/vespa/storageserver/app/servicelayerprocess.cpp +++ b/storageserver/src/vespa/storageserver/app/servicelayerprocess.cpp @@ -88,7 +88,17 @@ ServiceLayerProcess::updateConfig() bool ServiceLayerProcess::configUpdated() { - return Process::configUpdated(); + bool changed = Process::configUpdated(); + if (_persistence_cfg_handle->isChanged()) { + changed = true; + } + if (_visitor_cfg_handle->isChanged()) { + changed = true; + } + if (_filestor_cfg_handle->isChanged()) { + changed = true; + } + return changed; } void diff --git a/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/Endpoint.java b/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/Endpoint.java index dd76827dd2b..1ae5171c93a 100644 --- a/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/Endpoint.java +++ b/tenant-cd-api/src/main/java/ai/vespa/hosted/cd/Endpoint.java @@ -5,7 +5,6 @@ import java.net.URI; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; -import java.util.Collections; import java.util.Map; /** @@ -34,7 +33,7 @@ public interface Endpoint { /** Creates a request against the endpoint, with the given path. */ default HttpRequest.Builder request(String path) { - return request(path, Collections.emptyMap()); + return request(path, Map.of()); } } diff --git a/testutil/src/main/java/com/yahoo/test/OrderTester.java b/testutil/src/main/java/com/yahoo/test/OrderTester.java index 391eb5c4ebd..6f83cd723b8 100644 --- a/testutil/src/main/java/com/yahoo/test/OrderTester.java +++ b/testutil/src/main/java/com/yahoo/test/OrderTester.java @@ -2,7 +2,6 @@ package com.yahoo.test; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -25,7 +24,7 @@ public abstract class OrderTester<T extends Comparable<? super T>> { @SafeVarargs @SuppressWarnings("varargs") private OrderTester<T> addGroup(T... group) { - groups.add(Arrays.asList(group)); + groups.add(List.of(group)); return this; } diff --git a/testutil/src/test/java/com/yahoo/test/MatchersTestCase.java b/testutil/src/test/java/com/yahoo/test/MatchersTestCase.java index 839856db7f2..c36818e4f7f 100644 --- a/testutil/src/test/java/com/yahoo/test/MatchersTestCase.java +++ b/testutil/src/test/java/com/yahoo/test/MatchersTestCase.java @@ -1,13 +1,14 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.test; -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.hamcrest.Matcher; import org.junit.Test; +import java.util.List; + /** * Tests for com.yahoo.test.Matchers. * @@ -18,16 +19,9 @@ public class MatchersTestCase { @Test public final void testHasItemWithMethodObjectString() { @SuppressWarnings("rawtypes") - final Matcher<Iterable> m = Matchers.hasItemWithMethod("nalle", - "toLowerCase"); - assertEquals( - false, - m.matches(Arrays.asList(new Object[] { Integer.valueOf(1), - Character.valueOf('c'), "blbl" }))); - assertEquals( - true, - m.matches(Arrays.asList(new Object[] { Character.valueOf('c'), - "NALLE" }))); + final Matcher<Iterable> m = Matchers.hasItemWithMethod("nalle", "toLowerCase"); + assertFalse(m.matches(List.of(new Object[]{1, 'c', "blbl"}))); + assertTrue(m.matches(List.of(new Object[]{'c', "NALLE"}))); } } diff --git a/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/ApplicationMojo.java b/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/ApplicationMojo.java index 415bed7419d..279bffcd49e 100644 --- a/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/ApplicationMojo.java +++ b/vespa-application-maven-plugin/src/main/java/com/yahoo/container/plugin/mojo/ApplicationMojo.java @@ -21,7 +21,6 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; -import java.util.Collections; import java.util.List; /** @@ -173,7 +172,7 @@ public class ApplicationMojo extends AbstractMojo { } private static <T> List<T> emptyListIfNull(List<T> modules) { - return modules == null ? Collections.emptyList(): modules; + return modules == null ? List.of(): modules; } } diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/api/AthenzPrincipal.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/api/AthenzPrincipal.java index 08d289e216b..2a1113be26a 100644 --- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/api/AthenzPrincipal.java +++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/api/AthenzPrincipal.java @@ -6,8 +6,6 @@ import java.util.List; import java.util.Objects; import java.util.Optional; -import static java.util.Collections.emptyList; - /** * @author bjorncs */ @@ -18,11 +16,11 @@ public class AthenzPrincipal implements Principal { private final List<AthenzRole> roles; public AthenzPrincipal(AthenzIdentity athenzIdentity) { - this(athenzIdentity, null, emptyList()); + this(athenzIdentity, null, List.of()); } public AthenzPrincipal(AthenzIdentity athenzIdentity, NToken nToken) { - this(athenzIdentity, nToken, emptyList()); + this(athenzIdentity, nToken, List.of()); } public AthenzPrincipal(AthenzIdentity identity, List<AthenzRole> roles) { diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/DefaultZmsClient.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/DefaultZmsClient.java index c4c8fac87b4..f054abf2bd1 100644 --- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/DefaultZmsClient.java +++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/zms/DefaultZmsClient.java @@ -43,7 +43,6 @@ import javax.net.ssl.SSLContext; import java.net.URI; import java.security.PublicKey; import java.time.Instant; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -88,7 +87,7 @@ public class DefaultZmsClient extends ClientBase implements ZmsClient { HttpUriRequest request = RequestBuilder.put() .setUri(uri) .addHeader(createCookieHeader(oAuthCredentials)) - .setEntity(toJsonStringEntity(new TenancyRequestEntity(tenantDomain, providerService, Collections.emptyList()))) + .setEntity(toJsonStringEntity(new TenancyRequestEntity(tenantDomain, providerService, List.of()))) .build(); execute(request, response -> readEntity(response, Void.class)); } diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identity/SiaIdentityProvider.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identity/SiaIdentityProvider.java index ed3a52abb87..2c8908a89a6 100644 --- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identity/SiaIdentityProvider.java +++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identity/SiaIdentityProvider.java @@ -17,15 +17,11 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.Certificate; + import java.security.cert.X509Certificate; import java.util.List; -import java.util.Spliterator; -import java.util.Spliterators; + import java.util.stream.Stream; -import java.util.stream.StreamSupport; /** * A {@link ServiceIdentityProvider} that provides the credentials stored on file system. diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzCredentialsService.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzCredentialsService.java index 40a23ab5904..63c966004e5 100644 --- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzCredentialsService.java +++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzCredentialsService.java @@ -123,9 +123,9 @@ class AthenzCredentialsService { private Optional<AthenzCredentials> tryReadCredentialsFromDisk() { Optional<PrivateKey> privateKey = SiaUtils.readPrivateKeyFile(VESPA_SIA_DIRECTORY, tenantIdentity); - if (!privateKey.isPresent()) return Optional.empty(); + if (privateKey.isEmpty()) return Optional.empty(); Optional<X509Certificate> certificate = SiaUtils.readCertificateFile(VESPA_SIA_DIRECTORY, tenantIdentity); - if (!certificate.isPresent()) return Optional.empty(); + if (certificate.isEmpty()) return Optional.empty(); if (isExpired(certificate.get())) { return Optional.empty(); } diff --git a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/LegacyAthenzIdentityProviderImpl.java b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/LegacyAthenzIdentityProviderImpl.java index 5569eef192c..34324ef18e6 100644 --- a/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/LegacyAthenzIdentityProviderImpl.java +++ b/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/identityprovider/client/LegacyAthenzIdentityProviderImpl.java @@ -38,7 +38,6 @@ import java.security.cert.X509Certificate; import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -277,7 +276,7 @@ public final class LegacyAthenzIdentityProviderImpl extends AbstractComponent im @Override public List<X509Certificate> getIdentityCertificate() { - return Collections.singletonList(credentials.getCertificate()); + return List.of(credentials.getCertificate()); } @Override diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java index 46d8976b1ce..2532a394f4e 100644 --- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java +++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java @@ -18,8 +18,8 @@ import org.junit.jupiter.api.Test; import java.net.URI; import java.security.KeyPair; import java.time.Instant; -import java.util.Arrays; import java.util.HashSet; +import java.util.List; import static com.yahoo.vespa.athenz.identityprovider.api.IdentityType.TENANT; import static com.yahoo.vespa.athenz.identityprovider.api.SignedIdentityDocument.DEFAULT_DOCUMENT_VERSION; @@ -41,7 +41,7 @@ public class IdentityDocumentSignerTest { private static final String configserverHostname = "configserverhostname"; private static final String instanceHostname = "instancehostname"; private static final Instant createdAt = Instant.EPOCH; - private static final HashSet<String> ipAddresses = new HashSet<>(Arrays.asList("1.2.3.4", "::1")); + private static final HashSet<String> ipAddresses = new HashSet<>(List.of("1.2.3.4", "::1")); private static final ClusterType clusterType = ClusterType.CONTAINER; private static final URI ztsUrl = URI.create("https://foo"); private static final AthenzIdentity serviceIdentity = new AthenzService("vespa", "node"); diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java index 1f9ad2ced64..322e9ffaf82 100644 --- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java +++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java @@ -12,7 +12,6 @@ import org.junit.jupiter.api.Test; import javax.security.auth.x500.X500Principal; import java.security.KeyPair; -import java.util.Collections; import java.util.Set; import static com.yahoo.security.SubjectAlternativeName.Type.DNS; @@ -36,7 +35,7 @@ public class InstanceCsrGeneratorTest { VespaUniqueInstanceId vespaUniqueInstanceId = VespaUniqueInstanceId.fromDottedString("0.default.default.foo-app.vespa.us-north-1.prod.node"); KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA); - Pkcs10Csr csr = csrGenerator.generateInstanceCsr(service, vespaUniqueInstanceId, Collections.emptySet(), ClusterType.CONTAINER, keyPair); + Pkcs10Csr csr = csrGenerator.generateInstanceCsr(service, vespaUniqueInstanceId, Set.of(), ClusterType.CONTAINER, keyPair); assertEquals(new X500Principal(String.format("OU=%s, CN=%s", PROVIDER_SERVICE, ATHENZ_SERVICE)), csr.getSubject()); var actualSans = Set.copyOf(csr.getSubjectAlternativeNames()); var expectedSans = Set.of( diff --git a/vespa-documentgen-plugin/src/main/java/com/yahoo/vespa/DocumentGenMojo.java b/vespa-documentgen-plugin/src/main/java/com/yahoo/vespa/DocumentGenMojo.java index 5cd1d3bf9b6..027682e1052 100644 --- a/vespa-documentgen-plugin/src/main/java/com/yahoo/vespa/DocumentGenMojo.java +++ b/vespa-documentgen-plugin/src/main/java/com/yahoo/vespa/DocumentGenMojo.java @@ -598,7 +598,7 @@ public class DocumentGenMojo extends AbstractMojo { private static void exportFieldSetDefinition(Set<FieldSet> fieldSets, Writer out, int ind) throws IOException { out.write(ind(ind) + "java.util.Map<java.lang.String, java.util.Collection<java.lang.String>> fieldSets = new java.util.HashMap<>();\n"); for (FieldSet fieldSet : fieldSets) { - out.write(ind(ind) + "fieldSets.put(\"" + fieldSet.getName() + "\", java.util.Arrays.asList("); + out.write(ind(ind) + "fieldSets.put(\"" + fieldSet.getName() + "\", java.util.List.of("); int count = 0; for (String field : fieldSet.getFieldNames()) { out.write("\"" + field + "\""); diff --git a/vespa-feed-client-api/src/main/java/ai/vespa/feed/client/FeedClientBuilder.java b/vespa-feed-client-api/src/main/java/ai/vespa/feed/client/FeedClientBuilder.java index 7101b8452ed..6fd17154aa8 100644 --- a/vespa-feed-client-api/src/main/java/ai/vespa/feed/client/FeedClientBuilder.java +++ b/vespa-feed-client-api/src/main/java/ai/vespa/feed/client/FeedClientBuilder.java @@ -9,7 +9,6 @@ import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.time.Duration; import java.util.Collection; -import java.util.Collections; import java.util.List; import java.util.function.Supplier; @@ -27,7 +26,7 @@ public interface FeedClientBuilder { * Creates a builder for a single feed container endpoint. * This is for feeding against a container cluster with a load balancer in front of it. **/ - static FeedClientBuilder create(URI endpoint) { return create(Collections.singletonList(endpoint)); } + static FeedClientBuilder create(URI endpoint) { return create(List.of(endpoint)); } /** * Creates a builder which <em>distributes</em> the feed across the given feed container endpoints. diff --git a/vespa-feed-client-api/src/test/java/ai/vespa/feed/client/FeedClientTest.java b/vespa-feed-client-api/src/test/java/ai/vespa/feed/client/FeedClientTest.java index 4b8e91a35a6..d64df85aea3 100644 --- a/vespa-feed-client-api/src/test/java/ai/vespa/feed/client/FeedClientTest.java +++ b/vespa-feed-client-api/src/test/java/ai/vespa/feed/client/FeedClientTest.java @@ -5,7 +5,6 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -89,9 +88,9 @@ class FeedClientTest { CompletableFuture<Result> f3 = CompletableFuture.completedFuture(new MyResult()); MultiFeedException multiException = assertThrows(MultiFeedException.class, () -> FeedClient.await(f1, f2, f3)); - Set<DocumentId> expectedDocsIds = new HashSet<>(Arrays.asList(docId1, docId2)); + Set<DocumentId> expectedDocsIds = new HashSet<>(List.of(docId1, docId2)); assertEquals(expectedDocsIds, new HashSet<>(multiException.documentIds())); - Set<FeedException> expectedExceptions = new HashSet<>(Arrays.asList(exceptionDoc1, exceptionDoc2)); + Set<FeedException> expectedExceptions = new HashSet<>(List.of(exceptionDoc1, exceptionDoc2)); assertEquals(expectedExceptions, new HashSet<>(multiException.feedExceptions())); assertEquals("2 feed operations failed", multiException.getMessage()); } diff --git a/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliArguments.java b/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliArguments.java index e07108a84ad..35faa89388b 100644 --- a/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliArguments.java +++ b/vespa-feed-client-cli/src/main/java/ai/vespa/feed/client/impl/CliArguments.java @@ -18,7 +18,6 @@ import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.time.Duration; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; @@ -26,7 +25,6 @@ import java.util.OptionalDouble; import java.util.OptionalInt; import static ai.vespa.feed.client.FeedClientBuilder.Compression.auto; -import static ai.vespa.feed.client.FeedClientBuilder.Compression.none; /** * Parses command line arguments @@ -139,7 +137,7 @@ class CliArguments { Map<String, String> headers() throws CliArgumentsException { String[] rawArguments = arguments.getOptionValues(HEADER_OPTION); - if (rawArguments == null) return Collections.emptyMap(); + if (rawArguments == null) return Map.of(); Map<String, String> headers = new HashMap<>(); for (String rawArgument : rawArguments) { if (rawArgument.startsWith("\"") || rawArgument.startsWith("'")) { @@ -152,7 +150,7 @@ class CliArguments { if (colonIndex == -1) throw new CliArgumentsException("Invalid header: '" + rawArgument + "'"); headers.put(rawArgument.substring(0, colonIndex), rawArgument.substring(colonIndex + 1).trim()); } - return Collections.unmodifiableMap(headers); + return Map.copyOf(headers); } boolean sslHostnameVerificationDisabled() { return has(DISABLE_SSL_HOSTNAME_VERIFICATION_OPTION); } diff --git a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/FeedClientBuilderImpl.java b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/FeedClientBuilderImpl.java index 0268f1a4394..c271ac356e9 100644 --- a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/FeedClientBuilderImpl.java +++ b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/FeedClientBuilderImpl.java @@ -15,7 +15,6 @@ import java.security.cert.X509Certificate; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -195,7 +194,7 @@ public class FeedClientBuilderImpl implements FeedClientBuilder { /** Sets client SSL certificate/key */ @Override public FeedClientBuilderImpl setCertificate(X509Certificate certificate, PrivateKey privateKey) { - return setCertificate(Collections.singletonList(certificate), privateKey); + return setCertificate(List.of(certificate), privateKey); } @Override diff --git a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/JettyCluster.java b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/JettyCluster.java index 5454249d52e..df010a167f6 100644 --- a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/JettyCluster.java +++ b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/JettyCluster.java @@ -41,7 +41,6 @@ import java.net.Inet4Address; import java.net.InetSocketAddress; import java.net.URI; import java.time.Duration; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -194,7 +193,7 @@ class JettyCluster implements Cluster { proxySslCtxFactory.setSslContext(b.constructProxySslContext()); try { proxySslCtxFactory.start(); } catch (Exception e) { throw new IOException(e); } httpClient.getProxyConfiguration().addProxy( - new HttpProxy(address, proxySslCtxFactory, new Origin.Protocol(Collections.singletonList("h2"), false))); + new HttpProxy(address, proxySslCtxFactory, new Origin.Protocol(List.of("h2"), false))); URI proxyUri = URI.create(endpointUri(b.proxy)); httpClient.getAuthenticationStore().addAuthenticationResult(new Authentication.Result() { @Override public URI getURI() { return proxyUri; } @@ -205,7 +204,7 @@ class JettyCluster implements Cluster { } else { // Assume insecure proxy uses HTTP/1.1 httpClient.getProxyConfiguration().addProxy( - new HttpProxy(address, false, new Origin.Protocol(Collections.singletonList("http/1.1"), false))); + new HttpProxy(address, false, new Origin.Protocol(List.of("http/1.1"), false))); // Bug in Jetty cause authentication result to be ignored for HTTP/1.1 CONNECT requests httpClient.getRequestListeners().add(new Request.Listener() { @Override diff --git a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/SslContextBuilder.java b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/SslContextBuilder.java index 36f708e6535..1b0ad7a6b81 100644 --- a/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/SslContextBuilder.java +++ b/vespa-feed-client/src/main/java/ai/vespa/feed/client/impl/SslContextBuilder.java @@ -28,7 +28,6 @@ import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.security.spec.PKCS8EncodedKeySpec; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Optional; @@ -81,7 +80,7 @@ class SslContextBuilder { keystore.setKeyEntry("cert", privateKey, new char[0], certificate.toArray(new Certificate[0])); } if (hasCaCertificateFile()) { - addCaCertificates(keystore, Arrays.asList(certificates(caCertificatesFile))); + addCaCertificates(keystore, List.of(certificates(caCertificatesFile))); } else if (hasCaCertificateInstance()) { addCaCertificates(keystore, caCertificates); } diff --git a/vespa-feed-client/src/test/java/ai/vespa/feed/client/impl/HttpFeedClientTest.java b/vespa-feed-client/src/test/java/ai/vespa/feed/client/impl/HttpFeedClientTest.java index c79bb7b4606..28bde16f457 100644 --- a/vespa-feed-client/src/test/java/ai/vespa/feed/client/impl/HttpFeedClientTest.java +++ b/vespa-feed-client/src/test/java/ai/vespa/feed/client/impl/HttpFeedClientTest.java @@ -13,7 +13,7 @@ import org.junit.jupiter.api.Test; import java.net.URI; import java.time.Duration; -import java.util.Collections; +import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -42,7 +42,7 @@ class HttpFeedClientTest { @Override public void await() { throw new UnsupportedOperationException(); } @Override public CompletableFuture<HttpResponse> enqueue(DocumentId documentId, HttpRequest request) { return dispatch.get().apply(documentId, request); } } - FeedClient client = new HttpFeedClient(new FeedClientBuilderImpl(Collections.singletonList(URI.create("https://dummy:123"))).setDryrun(true), + FeedClient client = new HttpFeedClient(new FeedClientBuilderImpl(List.of(URI.create("https://dummy:123"))).setDryrun(true), new DryrunCluster(), new MockRequestStrategy()); @@ -214,7 +214,7 @@ class HttpFeedClientTest { void testHandshake() { // dummy:123 does not exist, and results in a host-not-found exception. FeedException exception = assertThrows(FeedException.class, - () -> new HttpFeedClient(new FeedClientBuilderImpl(Collections.singletonList(URI.create("https://dummy:123"))))); + () -> new HttpFeedClient(new FeedClientBuilderImpl(List.of(URI.create("https://dummy:123"))))); String message = exception.getMessage(); assertTrue(message.startsWith("failed handshake with server after "), message); assertTrue(message.contains("java.net.UnknownHostException"), message); @@ -237,19 +237,19 @@ class HttpFeedClientTest { // Old server, and speed-test. assertEquals("server does not support speed test; upgrade to a newer version", assertThrows(FeedException.class, - () -> new HttpFeedClient(new FeedClientBuilderImpl(Collections.singletonList(URI.create("https://dummy:123"))).setSpeedTest(true), + () -> new HttpFeedClient(new FeedClientBuilderImpl(List.of(URI.create("https://dummy:123"))).setSpeedTest(true), cluster, null)) .getMessage()); // Old server. - new HttpFeedClient(new FeedClientBuilderImpl(Collections.singletonList(URI.create("https://dummy:123"))), + new HttpFeedClient(new FeedClientBuilderImpl(List.of(URI.create("https://dummy:123"))), cluster, null); // New server. response.set(okResponse); - new HttpFeedClient(new FeedClientBuilderImpl(Collections.singletonList(URI.create("https://dummy:123"))), + new HttpFeedClient(new FeedClientBuilderImpl(List.of(URI.create("https://dummy:123"))), cluster, null); } diff --git a/vespa-testrunner-components/src/test/java/com/yahoo/vespa/hosted/testrunner/PomXmlGeneratorTest.java b/vespa-testrunner-components/src/test/java/com/yahoo/vespa/hosted/testrunner/PomXmlGeneratorTest.java index 56eb741e302..f3aa10dd1fa 100644 --- a/vespa-testrunner-components/src/test/java/com/yahoo/vespa/hosted/testrunner/PomXmlGeneratorTest.java +++ b/vespa-testrunner-components/src/test/java/com/yahoo/vespa/hosted/testrunner/PomXmlGeneratorTest.java @@ -6,7 +6,6 @@ import org.junit.Test; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; @@ -18,7 +17,7 @@ public class PomXmlGeneratorTest { @Test public void write_system_tests_pom_xml() throws IOException { - List<Path> artifacts = Arrays.asList( + List<Path> artifacts = List.of( Paths.get("components/my-comp.jar"), Paths.get("main.jar")); diff --git a/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/VersionsTestCase.java b/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/VersionsTestCase.java index 4636f96a4bb..52a58474238 100644 --- a/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/VersionsTestCase.java +++ b/vespaclient-container-plugin/src/test/java/com/yahoo/vespa/http/server/VersionsTestCase.java @@ -7,7 +7,6 @@ import org.junit.Test; import java.io.ByteArrayOutputStream; import java.util.Arrays; -import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; @@ -20,17 +19,17 @@ import static org.junit.Assert.assertTrue; */ public class VersionsTestCase { - private static final List<String> EMPTY = Collections.emptyList(); - private static final List<String> ONE_TWO = Arrays.asList("1", "2"); - private static final List<String> ONE_THREE = Arrays.asList("1", "3"); - private static final List<String> TWO_THREE = Arrays.asList("3", "2"); + private static final List<String> EMPTY = List.of(); + private static final List<String> ONE_TWO = List.of("1", "2"); + private static final List<String> ONE_THREE = List.of("1", "3"); + private static final List<String> TWO_THREE = List.of("3", "2"); private static final List<String> ONE_NULL_THREE = Arrays.asList("1", null, "3"); - private static final List<String> ONE_COMMA_THREE = Collections.singletonList("1, 3"); - private static final List<String> ONE_EMPTY_THREE = Arrays.asList("1", "", "3"); - private static final List<String> TOO_LARGE_NUMBER = Collections.singletonList("1000000000"); - private static final List<String> THREE_TOO_LARGE_NUMBER = Arrays.asList("3", "1000000000"); - private static final List<String> THREE_COMMA_TOO_LARGE_NUMBER = Arrays.asList("3,1000000000"); - private static final List<String> GARBAGE = Collections.singletonList("garbage"); + private static final List<String> ONE_COMMA_THREE = List.of("1, 3"); + private static final List<String> ONE_EMPTY_THREE = List.of("1", "", "3"); + private static final List<String> TOO_LARGE_NUMBER = List.of("1000000000"); + private static final List<String> THREE_TOO_LARGE_NUMBER = List.of("3", "1000000000"); + private static final List<String> THREE_COMMA_TOO_LARGE_NUMBER = List.of("3,1000000000"); + private static final List<String> GARBAGE = List.of("garbage"); @Test public void testEmpty() { diff --git a/vespaclient-java/src/main/java/com/yahoo/dummyreceiver/DummyReceiver.java b/vespaclient-java/src/main/java/com/yahoo/dummyreceiver/DummyReceiver.java index 8d8904f042f..9a7d8279b1b 100755..100644 --- a/vespaclient-java/src/main/java/com/yahoo/dummyreceiver/DummyReceiver.java +++ b/vespaclient-java/src/main/java/com/yahoo/dummyreceiver/DummyReceiver.java @@ -18,7 +18,6 @@ import com.yahoo.messagebus.Reply; import com.yahoo.messagebus.network.Identity; import com.yahoo.messagebus.network.rpc.RPCNetworkParams; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.BlockingQueue; @@ -174,7 +173,7 @@ public class DummyReceiver implements MessageHandler { LogSetup.initVespaLogging("dummyreceiver"); DummyReceiver rcv = new DummyReceiver(); - if (!rcv.parseArgs(new LinkedList<>(Arrays.asList(args))) && !rcv.helpOption) { + if (!rcv.parseArgs(new LinkedList<>(List.of(args))) && !rcv.helpOption) { System.exit(1); } if (rcv.helpOption) { diff --git a/vespaclient-java/src/main/java/com/yahoo/vespafeeder/Arguments.java b/vespaclient-java/src/main/java/com/yahoo/vespafeeder/Arguments.java index 9c6613058f1..c81b8ff63b0 100644 --- a/vespaclient-java/src/main/java/com/yahoo/vespafeeder/Arguments.java +++ b/vespaclient-java/src/main/java/com/yahoo/vespafeeder/Arguments.java @@ -11,7 +11,6 @@ import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; -import java.util.Arrays; import java.util.LinkedList; import java.util.List; @@ -107,7 +106,7 @@ public class Arguments { private void parse(String[] argList) throws HelpShownException { List<String> args = new LinkedList<>(); - args.addAll(Arrays.asList(argList)); + args.addAll(List.of(argList)); while (!args.isEmpty()) { String arg = args.remove(0); diff --git a/vespaclient-java/src/main/java/com/yahoo/vespaget/CommandLineOptions.java b/vespaclient-java/src/main/java/com/yahoo/vespaget/CommandLineOptions.java index 8182aa917ae..cd372e72e41 100644 --- a/vespaclient-java/src/main/java/com/yahoo/vespaget/CommandLineOptions.java +++ b/vespaclient-java/src/main/java/com/yahoo/vespaget/CommandLineOptions.java @@ -13,7 +13,6 @@ import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import java.io.InputStream; -import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Scanner; @@ -229,7 +228,7 @@ public class CommandLineOptions { private Iterator<String> getDocumentIds(CommandLine cl) { // Fetch document ids from stdin if no ids are passed in as command line arguments - List<String> documentIds = Arrays.asList(cl.getArgs()); + List<String> documentIds = List.of(cl.getArgs()); // WARNING: CommandLine.getArgs may return a single empty string as the only element if (documentIds.isEmpty() || documentIds.size() == 1 && documentIds.get(0).isEmpty()) { diff --git a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java index 2cb3ab17df4..56ca142841c 100644 --- a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java +++ b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java @@ -7,7 +7,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; -import java.util.Arrays; +import java.util.List; import com.yahoo.clientmetrics.RouteMetricSet; import com.yahoo.document.DocumentPut; @@ -39,7 +39,7 @@ public class VespaFeederTestCase { Arguments arguments = new Arguments(argsS.split(" "), DummySessionFactory.createWithAutoReply()); FeederConfig config = arguments.getFeederConfig(); - assertEquals(false, config.abortondocumenterror()); + assertFalse(config.abortondocumenterror()); assertEquals(13.0, config.timeout(), 0.00001); assertEquals(false, config.retryenabled()); assertEquals("e6", config.route()); @@ -103,7 +103,7 @@ public class VespaFeederTestCase { public void assertRenderErrorOutput(String expected, String[] errors) { ArrayList<String> l = new ArrayList<String>(); - l.addAll(Arrays.asList(errors)); + l.addAll(List.of(errors)); assertEquals(expected, VespaFeeder.renderErrors(l).getMessage()); } @@ -111,16 +111,29 @@ public class VespaFeederTestCase { void testRenderErrors() { { String[] errors = {"foo"}; - assertRenderErrorOutput("Errors:\n" + - "-------\n" + - " foo\n", errors); + assertRenderErrorOutput(""" + Errors: + ------- + foo + """, errors); } { String[] errors = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"}; - assertRenderErrorOutput("First 10 errors (of 11):\n" + - "------------------------\n" + - " 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n 10\n", errors); + assertRenderErrorOutput(""" + First 10 errors (of 11): + ------------------------ + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + """, errors); } } diff --git a/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java b/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java index 0628f4e0f29..1d8f050a037 100644 --- a/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java +++ b/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java @@ -23,7 +23,6 @@ import org.mockito.ArgumentMatcher; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; -import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -99,7 +98,7 @@ public class DocumentRetrieverTest { } private static Iterator<String> asIterator(String... docIds) { - return Arrays.asList(docIds).iterator(); + return List.of(docIds).iterator(); } private static Reply createDocumentReply(String docId) { @@ -214,7 +213,7 @@ public class DocumentRetrieverTest { .setCluster(cluster) .build(); - ClusterList clusterList = new ClusterList(Collections.singletonList(new ClusterDef(cluster))); + ClusterList clusterList = new ClusterList(List.of(new ClusterDef(cluster))); DocumentRetriever documentRetriever = createDocumentRetriever(params, clusterList); documentRetriever.retrieveDocuments(); @@ -230,7 +229,7 @@ public class DocumentRetrieverTest { .setCluster("invalidclustername") .build(); - ClusterList clusterList = new ClusterList(Collections.singletonList(new ClusterDef("storage"))); + ClusterList clusterList = new ClusterList(List.of(new ClusterDef("storage"))); DocumentRetriever documentRetriever = createDocumentRetriever(params, clusterList); documentRetriever.retrieveDocuments(); diff --git a/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java b/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java index 143d5518eff..c4164d04aa2 100644 --- a/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java +++ b/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java @@ -10,7 +10,6 @@ import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -28,7 +27,7 @@ public class BucketStatsPrinterTest { public void mockBucketStatsRetriever() throws BucketStatsException { retriever = mock(BucketStatsRetriever.class); when(retriever.getBucketIdForType(any(), any())).thenReturn(new BucketId(0x42)); - when(retriever.retrieveBucketList(any(), any())).thenReturn(Collections.emptyList()); + when(retriever.retrieveBucketList(any(), any())).thenReturn(List.of()); when(retriever.retrieveBucketStats(any(), any(), any(), any())).thenReturn(""); } @@ -79,7 +78,7 @@ public class BucketStatsPrinterTest { void testShouldPrintBucketStats() throws BucketStatsException { String dummyBucketStats = "dummystats"; GetBucketListReply.BucketInfo bucketInfo = new GetBucketListReply.BucketInfo(new BucketId(0), "dummy"); - when(retriever.retrieveBucketList(any(), any())).thenReturn(Collections.singletonList(bucketInfo)); + when(retriever.retrieveBucketList(any(), any())).thenReturn(List.of(bucketInfo)); when(retriever.retrieveBucketStats(any(), any(), any(), any())).thenReturn(dummyBucketStats); String output = retreiveAndPrintBucketStats(ClientParameters.SelectionType.USER, "1234", true); diff --git a/vespajlib/src/main/java/com/yahoo/collections/CollectionUtil.java b/vespajlib/src/main/java/com/yahoo/collections/CollectionUtil.java index 7f70256233e..1f215f9d90e 100644 --- a/vespajlib/src/main/java/com/yahoo/collections/CollectionUtil.java +++ b/vespajlib/src/main/java/com/yahoo/collections/CollectionUtil.java @@ -51,8 +51,7 @@ public class CollectionUtil { * Returns true if the contents of the two given collections are equal, ignoring order. */ public static boolean equalContentsIgnoreOrder(Collection<?> c1, Collection<?> c2) { - return c1.size() == c2.size() && - c1.containsAll(c2); + return c1.size() == c2.size() && c1.containsAll(c2); } /** diff --git a/vespajlib/src/main/java/com/yahoo/collections/ListenableArrayList.java b/vespajlib/src/main/java/com/yahoo/collections/ListenableArrayList.java index 8ace7598e27..26c0bec34b1 100644 --- a/vespajlib/src/main/java/com/yahoo/collections/ListenableArrayList.java +++ b/vespajlib/src/main/java/com/yahoo/collections/ListenableArrayList.java @@ -56,7 +56,7 @@ public class ListenableArrayList<ITEM> extends ArrayList<ITEM> { } public List<Runnable> listeners() { - if (listeners == null) return Collections.emptyList(); + if (listeners == null) return List.of(); return Collections.unmodifiableList(listeners); } diff --git a/vespajlib/src/main/java/com/yahoo/concurrent/InThreadExecutorService.java b/vespajlib/src/main/java/com/yahoo/concurrent/InThreadExecutorService.java index 96541e555b2..63653b051c0 100644 --- a/vespajlib/src/main/java/com/yahoo/concurrent/InThreadExecutorService.java +++ b/vespajlib/src/main/java/com/yahoo/concurrent/InThreadExecutorService.java @@ -1,7 +1,6 @@ // Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.concurrent; -import java.util.Collections; import java.util.List; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.ExecutorService; @@ -24,7 +23,7 @@ public class InThreadExecutorService extends AbstractExecutorService { @Override public List<Runnable> shutdownNow() { shutdown(); - return Collections.emptyList(); + return List.of(); } @Override diff --git a/vespajlib/src/main/java/com/yahoo/data/access/simple/Value.java b/vespajlib/src/main/java/com/yahoo/data/access/simple/Value.java index 3a02d752aa5..e67c1ebb3b6 100644 --- a/vespajlib/src/main/java/com/yahoo/data/access/simple/Value.java +++ b/vespajlib/src/main/java/com/yahoo/data/access/simple/Value.java @@ -41,8 +41,8 @@ public class Value implements Inspector { public void traverse(ObjectTraverser ot) {} public Inspector entry(int idx) { return invalid; } public Inspector field(java.lang.String name) { return invalid; } - public Iterable<Inspector> entries() { return Collections.emptyList(); } - public Iterable<Map.Entry<java.lang.String,Inspector>> fields() { return Collections.emptyList(); } + public Iterable<Inspector> entries() { return List.of(); } + public Iterable<Map.Entry<java.lang.String,Inspector>> fields() { return List.of(); } public StringBuilder writeJson(StringBuilder target) { return JsonRender.render(this, target, true); } diff --git a/vespajlib/src/main/java/com/yahoo/net/URI.java b/vespajlib/src/main/java/com/yahoo/net/URI.java index d008c589824..5111ad39e88 100644 --- a/vespajlib/src/main/java/com/yahoo/net/URI.java +++ b/vespajlib/src/main/java/com/yahoo/net/URI.java @@ -80,7 +80,7 @@ public class URI implements Cloneable, Comparable<URI> { } /** - * Creates an URI, optionaly keeping the fragment (the part starting by #). + * Creates a URI, optionally keeping the fragment (the part starting by #). * If the uri is hierarchical, it is normalized and incorrect hierarchical uris * which looks like urls are attempted repaired. * @@ -95,7 +95,7 @@ public class URI implements Cloneable, Comparable<URI> { } /** - * Creates an URI, optionaly keeping the fragment (the part starting by #). + * Creates a URI, optionally keeping the fragment (the part starting by #). * If the uri is hierarchical, it is normalized and incorrect hierarchical uris * which looks like urls are attempted repaired. * diff --git a/vespajlib/src/main/java/com/yahoo/system/CommandLineParser.java b/vespajlib/src/main/java/com/yahoo/system/CommandLineParser.java index 704fe9d56c3..12b435111e3 100644 --- a/vespajlib/src/main/java/com/yahoo/system/CommandLineParser.java +++ b/vespajlib/src/main/java/com/yahoo/system/CommandLineParser.java @@ -39,12 +39,12 @@ public class CommandLineParser { } public CommandLineParser(String[] cmds) { - inputStrings = Arrays.asList(cmds); + inputStrings = List.of(cmds); } public CommandLineParser(String progname, String[] cmds) { this.progname=progname; - inputStrings = Arrays.asList(cmds); + inputStrings = List.of(cmds); } /** diff --git a/vespajlib/src/main/java/com/yahoo/tensor/Tensor.java b/vespajlib/src/main/java/com/yahoo/tensor/Tensor.java index d27c7cf0168..d225d6f4641 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/Tensor.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/Tensor.java @@ -23,8 +23,6 @@ import com.yahoo.tensor.functions.Expand; import com.yahoo.tensor.impl.Label; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -170,7 +168,7 @@ public interface Tensor { /** Aggregates cells over a set of dimensions, or over all dimensions if no dimensions are specified */ default Tensor reduce(Reduce.Aggregator aggregator, String ... dimensions) { - return new Reduce<>(new ConstantTensor<>(this), aggregator, Arrays.asList(dimensions)).evaluate(); + return new Reduce<>(new ConstantTensor<>(this), aggregator, List.of(dimensions)).evaluate(); } /** Aggregates cells over a set of dimensions, or over all dimensions if no dimensions are specified */ default Tensor reduce(Reduce.Aggregator aggregator, List<String> dimensions) { @@ -186,8 +184,8 @@ public interface Tensor { } default Tensor rename(String fromDimension, String toDimension) { - return new Rename<>(new ConstantTensor<>(this), Collections.singletonList(fromDimension), - Collections.singletonList(toDimension)).evaluate(); + return new Rename<>(new ConstantTensor<>(this), List.of(fromDimension), + List.of(toDimension)).evaluate(); } default Tensor concat(double argument, String dimension) { @@ -270,26 +268,26 @@ public interface Tensor { default Tensor bit(Tensor argument) { return join(argument, (a,b) -> ((int)b < 8 && (int)b >= 0 && ((int)a & (1 << (int)b)) != 0) ? 1.0 : 0.0); } default Tensor hamming(Tensor argument) { return join(argument, Hamming::hamming); } - default Tensor avg() { return avg(Collections.emptyList()); } - default Tensor avg(String dimension) { return avg(Collections.singletonList(dimension)); } + default Tensor avg() { return avg(List.of()); } + default Tensor avg(String dimension) { return avg(List.of(dimension)); } default Tensor avg(List<String> dimensions) { return reduce(Reduce.Aggregator.avg, dimensions); } - default Tensor count() { return count(Collections.emptyList()); } - default Tensor count(String dimension) { return count(Collections.singletonList(dimension)); } + default Tensor count() { return count(List.of()); } + default Tensor count(String dimension) { return count(List.of(dimension)); } default Tensor count(List<String> dimensions) { return reduce(Reduce.Aggregator.count, dimensions); } - default Tensor max() { return max(Collections.emptyList()); } - default Tensor max(String dimension) { return max(Collections.singletonList(dimension)); } + default Tensor max() { return max(List.of()); } + default Tensor max(String dimension) { return max(List.of(dimension)); } default Tensor max(List<String> dimensions) { return reduce(Reduce.Aggregator.max, dimensions); } - default Tensor median() { return median(Collections.emptyList()); } - default Tensor median(String dimension) { return median(Collections.singletonList(dimension)); } + default Tensor median() { return median(List.of()); } + default Tensor median(String dimension) { return median(List.of(dimension)); } default Tensor median(List<String> dimensions) { return reduce(Reduce.Aggregator.median, dimensions); } - default Tensor min() { return min(Collections.emptyList()); } - default Tensor min(String dimension) { return min(Collections.singletonList(dimension)); } + default Tensor min() { return min(List.of()); } + default Tensor min(String dimension) { return min(List.of(dimension)); } default Tensor min(List<String> dimensions) { return reduce(Reduce.Aggregator.min, dimensions); } - default Tensor prod() { return prod(Collections.emptyList()); } - default Tensor prod(String dimension) { return prod(Collections.singletonList(dimension)); } + default Tensor prod() { return prod(List.of()); } + default Tensor prod(String dimension) { return prod(List.of(dimension)); } default Tensor prod(List<String> dimensions) { return reduce(Reduce.Aggregator.prod, dimensions); } - default Tensor sum() { return sum(Collections.emptyList()); } - default Tensor sum(String dimension) { return sum(Collections.singletonList(dimension)); } + default Tensor sum() { return sum(List.of()); } + default Tensor sum(String dimension) { return sum(List.of(dimension)); } default Tensor sum(List<String> dimensions) { return reduce(Reduce.Aggregator.sum, dimensions); } // ----------------- non-math query methods (that is, computations not returning a tensor) diff --git a/vespajlib/src/main/java/com/yahoo/tensor/TensorTypeParser.java b/vespajlib/src/main/java/com/yahoo/tensor/TensorTypeParser.java index b6bd252f135..fc82be4b33c 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/TensorTypeParser.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/TensorTypeParser.java @@ -3,7 +3,6 @@ package com.yahoo.tensor; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.regex.Matcher; @@ -50,7 +49,7 @@ public class TensorTypeParser { dimensionsSpec = specBody.substring(parenthesisIndex + 1); } - if (dimensionsSpec.isEmpty()) return new TensorType.Builder(valueType, Collections.emptyList()).build(); + if (dimensionsSpec.isEmpty()) return new TensorType.Builder(valueType, List.of()).build(); List<TensorType.Dimension> dimensions = new ArrayList<>(); for (String element : dimensionsSpec.split(",")) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/evaluation/VariableTensor.java b/vespajlib/src/main/java/com/yahoo/tensor/evaluation/VariableTensor.java index 0cef1482292..58b17758cfe 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/evaluation/VariableTensor.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/evaluation/VariableTensor.java @@ -7,7 +7,6 @@ import com.yahoo.tensor.functions.PrimitiveTensorFunction; import com.yahoo.tensor.functions.TensorFunction; import com.yahoo.tensor.functions.ToStringContext; -import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -34,7 +33,7 @@ public class VariableTensor<NAMETYPE extends Name> extends PrimitiveTensorFuncti } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.emptyList(); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { return this; } diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/CellCast.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/CellCast.java index 61207840ded..5655bb020a4 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/CellCast.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/CellCast.java @@ -8,7 +8,6 @@ import com.yahoo.tensor.evaluation.EvaluationContext; import com.yahoo.tensor.evaluation.Name; import com.yahoo.tensor.evaluation.TypeContext; -import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; @@ -32,7 +31,7 @@ public class CellCast<NAMETYPE extends Name> extends PrimitiveTensorFunction<NAM } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.singletonList(argument); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(argument); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/ConstantTensor.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/ConstantTensor.java index c81cde70c75..0ecd4b5f947 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/ConstantTensor.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/ConstantTensor.java @@ -7,7 +7,6 @@ import com.yahoo.tensor.evaluation.EvaluationContext; import com.yahoo.tensor.evaluation.Name; import com.yahoo.tensor.evaluation.TypeContext; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -29,7 +28,7 @@ public class ConstantTensor<NAMETYPE extends Name> extends PrimitiveTensorFuncti } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.emptyList(); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/Diag.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/Diag.java index 382ac94be7d..354e03e6699 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/Diag.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/Diag.java @@ -4,7 +4,6 @@ package com.yahoo.tensor.functions; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.Name; -import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Function; @@ -27,7 +26,7 @@ public class Diag<NAMETYPE extends Name> extends CompositeTensorFunction<NAMETYP } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.emptyList(); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/Expand.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/Expand.java index 3042991e2c0..f5a33dde064 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/Expand.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/Expand.java @@ -4,7 +4,6 @@ package com.yahoo.tensor.functions; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.Name; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -25,7 +24,7 @@ public class Expand<NAMETYPE extends Name> extends CompositeTensorFunction<NAMET } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.singletonList(argument); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(argument); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/L1Normalize.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/L1Normalize.java index 51bd4152479..a5afeb6d2a4 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/L1Normalize.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/L1Normalize.java @@ -3,7 +3,6 @@ package com.yahoo.tensor.functions; import com.yahoo.tensor.evaluation.Name; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -21,7 +20,7 @@ public class L1Normalize<NAMETYPE extends Name> extends CompositeTensorFunction< } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.singletonList(argument); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(argument); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/L2Normalize.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/L2Normalize.java index 4b6ffbca63c..47e341732ca 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/L2Normalize.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/L2Normalize.java @@ -3,7 +3,6 @@ package com.yahoo.tensor.functions; import com.yahoo.tensor.evaluation.Name; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -21,7 +20,7 @@ public class L2Normalize<NAMETYPE extends Name> extends CompositeTensorFunction< } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.singletonList(argument); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(argument); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/Map.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/Map.java index 404be1d6fac..94e75588ba3 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/Map.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/Map.java @@ -9,7 +9,6 @@ import com.yahoo.tensor.evaluation.EvaluationContext; import com.yahoo.tensor.evaluation.Name; import com.yahoo.tensor.evaluation.TypeContext; -import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; @@ -40,7 +39,7 @@ public class Map<NAMETYPE extends Name> extends PrimitiveTensorFunction<NAMETYPE public DoubleUnaryOperator mapper() { return mapper; } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.singletonList(argument); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(argument); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/MapSubspaces.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/MapSubspaces.java index aa9602339e9..93a101909a2 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/MapSubspaces.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/MapSubspaces.java @@ -9,7 +9,6 @@ import com.yahoo.tensor.evaluation.EvaluationContext; import com.yahoo.tensor.evaluation.Name; import com.yahoo.tensor.evaluation.TypeContext; -import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -64,7 +63,7 @@ public class MapSubspaces<NAMETYPE extends Name> extends PrimitiveTensorFunction public TensorFunction<NAMETYPE> argument() { return argument; } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.singletonList(argument); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(argument); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/Random.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/Random.java index 5d51d8cd5c6..811e861de9c 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/Random.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/Random.java @@ -4,7 +4,6 @@ package com.yahoo.tensor.functions; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.Name; -import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @@ -24,7 +23,7 @@ public class Random<NAMETYPE extends Name> extends CompositeTensorFunction<NAMET } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.emptyList(); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/Range.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/Range.java index 8520aef537d..9960fbd58ea 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/Range.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/Range.java @@ -4,7 +4,6 @@ package com.yahoo.tensor.functions; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.Name; -import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.function.Function; @@ -28,7 +27,7 @@ public class Range<NAMETYPE extends Name> extends CompositeTensorFunction<NAMETY } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.emptyList(); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/tensor/functions/Softmax.java b/vespajlib/src/main/java/com/yahoo/tensor/functions/Softmax.java index c2eff01c801..150bf82f0e8 100644 --- a/vespajlib/src/main/java/com/yahoo/tensor/functions/Softmax.java +++ b/vespajlib/src/main/java/com/yahoo/tensor/functions/Softmax.java @@ -4,7 +4,6 @@ package com.yahoo.tensor.functions; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.Name; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -26,7 +25,7 @@ public class Softmax<NAMETYPE extends Name> extends CompositeTensorFunction<NAME } @Override - public List<TensorFunction<NAMETYPE>> arguments() { return Collections.singletonList(argument); } + public List<TensorFunction<NAMETYPE>> arguments() { return List.of(argument); } @Override public TensorFunction<NAMETYPE> withArguments(List<TensorFunction<NAMETYPE>> arguments) { diff --git a/vespajlib/src/main/java/com/yahoo/yolean/trace/TraceNode.java b/vespajlib/src/main/java/com/yahoo/yolean/trace/TraceNode.java index 39a78897bfb..90b9383eb0c 100644 --- a/vespajlib/src/main/java/com/yahoo/yolean/trace/TraceNode.java +++ b/vespajlib/src/main/java/com/yahoo/yolean/trace/TraceNode.java @@ -3,7 +3,6 @@ package com.yahoo.yolean.trace; import com.yahoo.yolean.concurrent.ThreadRobustList; -import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -73,7 +72,7 @@ public class TraceNode { */ public <PAYLOADTYPE> Iterable<PAYLOADTYPE> descendants(final Class<PAYLOADTYPE> payloadType) { if (children == null) { - return Collections.emptyList(); + return List.of(); } return new Iterable<PAYLOADTYPE>() { @@ -118,7 +117,7 @@ public class TraceNode { */ public Iterable<TraceNode> children() { if (children == null) { - return Collections.emptyList(); + return List.of(); } return children; } diff --git a/vespajlib/src/test/java/com/yahoo/collections/CollectionComparatorTestCase.java b/vespajlib/src/test/java/com/yahoo/collections/CollectionComparatorTestCase.java index 54101c7f251..a2420ed3fe5 100644 --- a/vespajlib/src/test/java/com/yahoo/collections/CollectionComparatorTestCase.java +++ b/vespajlib/src/test/java/com/yahoo/collections/CollectionComparatorTestCase.java @@ -3,7 +3,6 @@ package com.yahoo.collections; import org.junit.Test; -import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; @@ -14,16 +13,16 @@ import static org.junit.Assert.assertEquals; public class CollectionComparatorTestCase { @Test public void arrayLength() { - List<String> shortArr = Arrays.asList("x", "y"); - List<String> longArr = Arrays.asList("a", "b", "c", "d", "e"); + List<String> shortArr = List.of("x", "y"); + List<String> longArr = List.of("a", "b", "c", "d", "e"); assertEquals(-1, CollectionComparator.compare(shortArr, longArr)); } @Test public void compareArrays() { - List<String> one = Arrays.asList("b", "c", "d", "d", "e"); - List<String> two = Arrays.asList("a", "b", "c", "d", "e"); + List<String> one = List.of("b", "c", "d", "d", "e"); + List<String> two = List.of("a", "b", "c", "d", "e"); assertEquals(1, CollectionComparator.compare(one, two)); assertEquals(-1, CollectionComparator.compare(two, one)); @@ -31,8 +30,8 @@ public class CollectionComparatorTestCase { @Test public void compareEqualArrays() { - List<String> one = Arrays.asList("a", "b", "c", "d", "e"); - List<String> two = Arrays.asList("a", "b", "c", "d", "e"); + List<String> one = List.of("a", "b", "c", "d", "e"); + List<String> two = List.of("a", "b", "c", "d", "e"); assertEquals(0, CollectionComparator.compare(one, two)); assertEquals(0, CollectionComparator.compare(two, one)); diff --git a/vespajlib/src/test/java/com/yahoo/collections/CollectionUtilTest.java b/vespajlib/src/test/java/com/yahoo/collections/CollectionUtilTest.java index 7cef3423aeb..fd24bfb4f40 100644 --- a/vespajlib/src/test/java/com/yahoo/collections/CollectionUtilTest.java +++ b/vespajlib/src/test/java/com/yahoo/collections/CollectionUtilTest.java @@ -27,7 +27,7 @@ public class CollectionUtilTest { @Test public void testMkString() { assertEquals("1, 2, 3, 4", - CollectionUtil.mkString(Arrays.asList(1, 2, 3, 4), ", ")); + CollectionUtil.mkString(List.of(1, 2, 3, 4), ", ")); } @Test @@ -35,16 +35,14 @@ public class CollectionUtilTest { List<Integer> l2Copy = new ArrayList<>(); l2Copy.addAll(l2); shuffle(); - assertTrue(CollectionUtil.equalContentsIgnoreOrder( - l2, l2Copy)); - assertFalse(CollectionUtil.equalContentsIgnoreOrder( - l1, l2)); + assertTrue(CollectionUtil.equalContentsIgnoreOrder(l2, l2Copy)); + assertFalse(CollectionUtil.equalContentsIgnoreOrder(l1, l2)); } @Test public void testSymmetricDifference() { assertTrue(CollectionUtil.equalContentsIgnoreOrder( - Arrays.asList(1, 2, 3), + List.of(1, 2, 3), CollectionUtil.symmetricDifference(l1, l2))); } } diff --git a/vespajlib/src/test/java/com/yahoo/collections/LazyMapTest.java b/vespajlib/src/test/java/com/yahoo/collections/LazyMapTest.java index 940dc159a17..930b274ef3e 100644 --- a/vespajlib/src/test/java/com/yahoo/collections/LazyMapTest.java +++ b/vespajlib/src/test/java/com/yahoo/collections/LazyMapTest.java @@ -4,7 +4,6 @@ package com.yahoo.collections; import org.junit.Test; import org.mockito.Mockito; -import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -22,7 +21,6 @@ import static org.junit.Assert.fail; * @author Simon Thoresen Hult */ public class LazyMapTest { - @Test public void requireThatInitialDelegateIsEmpty() { LazyMap<String, String> map = newLazyMap(new HashMap<String, String>()); @@ -36,14 +34,14 @@ public class LazyMapTest { assertEquals(LazyMap.SingletonMap.class, map.getDelegate().getClass()); map = newLazyMap(new HashMap<String, String>()); - map.putAll(Collections.singletonMap("foo", "bar")); + map.put("foo", "bar"); assertEquals(LazyMap.SingletonMap.class, map.getDelegate().getClass()); } @Test public void requireThatEmptyMapPutAllEmptyMapDoesNotUpgradeToSingletonMap() { LazyMap<String, String> map = newLazyMap(new HashMap<String, String>()); - map.putAll(Collections.<String, String>emptyMap()); + map.putAll(Map.of()); assertEquals(LazyMap.EmptyMap.class, map.getDelegate().getClass()); } @@ -81,7 +79,7 @@ public class LazyMapTest { assertEquals("bar", map.put("foo", "baz")); assertEquals("baz", map.get("foo")); assertSame(delegate, map.getDelegate()); - map.putAll(Collections.singletonMap("foo", "cox")); + map.put("foo", "cox"); assertSame(delegate, map.getDelegate()); assertEquals("cox", map.get("foo")); } @@ -89,7 +87,7 @@ public class LazyMapTest { @Test public void requireThatSingletonMapPutAllEmptyMapDoesNotUpgradeToFinalMap() { LazyMap<String, String> map = newSingletonMap("foo", "bar"); - map.putAll(Collections.<String, String>emptyMap()); + map.putAll(Map.of()); assertEquals(LazyMap.SingletonMap.class, map.getDelegate().getClass()); } @@ -188,7 +186,7 @@ public class LazyMapTest { Mockito.verify(delegate).put("foo", "bar"); Mockito.verify(delegate).put("baz", "cox"); - Map<String, String> arg = Collections.singletonMap("baz", "cox"); + Map<String, String> arg = Map.of("baz", "cox"); map.putAll(arg); Mockito.verify(delegate).putAll(arg); diff --git a/vespajlib/src/test/java/com/yahoo/collections/LazySetTest.java b/vespajlib/src/test/java/com/yahoo/collections/LazySetTest.java index ecefd891ca9..4acd9ef3214 100644 --- a/vespajlib/src/test/java/com/yahoo/collections/LazySetTest.java +++ b/vespajlib/src/test/java/com/yahoo/collections/LazySetTest.java @@ -4,11 +4,11 @@ package com.yahoo.collections; import org.junit.Test; import org.mockito.Mockito; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.NoSuchElementException; import java.util.Set; @@ -26,25 +26,25 @@ public class LazySetTest { @Test public void requireThatInitialDelegateIsEmpty() { - LazySet<String> set = newLazySet(new HashSet<String>()); + LazySet<String> set = newLazySet(new HashSet<>()); assertEquals(LazySet.EmptySet.class, set.getDelegate().getClass()); } @Test public void requireThatEmptySetAddUpgradesToSingletonSet() { - LazySet<String> set = newLazySet(new HashSet<String>()); + LazySet<String> set = newLazySet(new HashSet<>()); assertTrue(set.add("foo")); assertEquals(LazySet.SingletonSet.class, set.getDelegate().getClass()); - set = newLazySet(new HashSet<String>()); - assertTrue(set.addAll(Arrays.asList("foo"))); + set = newLazySet(new HashSet<>()); + assertTrue(set.addAll(List.of("foo"))); assertEquals(LazySet.SingletonSet.class, set.getDelegate().getClass()); } @Test public void requireThatEmptySetAddAllEmptySetDoesNotUpgradeToSingletonSet() { - LazySet<String> set = newLazySet(new HashSet<String>()); - assertFalse(set.addAll(Collections.<String>emptySet())); + LazySet<String> set = newLazySet(new HashSet<>()); + assertFalse(set.addAll(Set.of())); assertEquals(LazySet.EmptySet.class, set.getDelegate().getClass()); } @@ -52,7 +52,7 @@ public class LazySetTest { public void requireThatEmptySetAddAllUpgradesToFinalSet() { Set<String> delegate = new HashSet<>(); LazySet<String> set = newLazySet(delegate); - assertTrue(set.addAll(Arrays.asList("foo", "bar"))); + assertTrue(set.addAll(List.of("foo", "bar"))); assertSame(delegate, set.getDelegate()); assertEquals(2, delegate.size()); assertTrue(delegate.contains("foo")); @@ -76,7 +76,7 @@ public class LazySetTest { @Test public void requireThatSingletonSetAddAllEmptySetDoesNotUpgradeToFinalSet() { LazySet<String> set = newSingletonSet("foo"); - assertFalse(set.addAll(Collections.<String>emptySet())); + assertFalse(set.addAll(Set.of())); assertEquals(LazySet.SingletonSet.class, set.getDelegate().getClass()); } @@ -102,7 +102,7 @@ public class LazySetTest { public void requireThatSingletonSetAddAllUpgradesToFinalSet() { Set<String> delegate = new HashSet<>(); LazySet<String> set = newSingletonSet(delegate, "foo"); - assertTrue(set.addAll(Arrays.asList("bar"))); + assertTrue(set.addAll(List.of("bar"))); assertSame(delegate, set.getDelegate()); assertEquals(2, delegate.size()); assertTrue(delegate.contains("foo")); @@ -110,7 +110,7 @@ public class LazySetTest { delegate = new HashSet<>(); set = newSingletonSet(delegate, "foo"); - assertTrue(set.addAll(Arrays.asList("bar", "baz"))); + assertTrue(set.addAll(List.of("bar", "baz"))); assertSame(delegate, set.getDelegate()); assertEquals(3, delegate.size()); assertTrue(delegate.contains("foo")); @@ -198,15 +198,15 @@ public class LazySetTest { assertFalse(set.remove("foo")); Mockito.verify(delegate).remove("foo"); - Collection<String> containsAllArg = Collections.singletonList("foo"); + Collection<String> containsAllArg = Set.of("foo"); assertFalse(set.containsAll(containsAllArg)); Mockito.verify(delegate).containsAll(containsAllArg); - Collection<String> retainAllArg = Collections.singletonList("foo"); + Collection<String> retainAllArg = Set.of("foo"); assertFalse(set.retainAll(retainAllArg)); Mockito.verify(delegate).retainAll(retainAllArg); - Collection<String> removeAllArg = Collections.singletonList("foo"); + Collection<String> removeAllArg = Set.of("foo"); assertFalse(set.removeAll(removeAllArg)); Mockito.verify(delegate).removeAll(removeAllArg); diff --git a/vespajlib/src/test/java/com/yahoo/collections/ListenableArrayListTestCase.java b/vespajlib/src/test/java/com/yahoo/collections/ListenableArrayListTestCase.java index 536e4d62502..adee795bb48 100644 --- a/vespajlib/src/test/java/com/yahoo/collections/ListenableArrayListTestCase.java +++ b/vespajlib/src/test/java/com/yahoo/collections/ListenableArrayListTestCase.java @@ -4,7 +4,7 @@ package com.yahoo.collections; import org.junit.Test; import static org.junit.Assert.*; -import java.util.Arrays; +import java.util.List; import java.util.ListIterator; /** @@ -22,9 +22,9 @@ public class ListenableArrayListTestCase { assertEquals(1,listener.invoked); list.add(0,"b"); assertEquals(2,listener.invoked); - list.addAll(Arrays.asList(new String[]{"c", "d"})); + list.addAll(List.of(new String[]{"c", "d"})); assertEquals(3,listener.invoked); - list.addAll(1,Arrays.asList(new String[]{"e", "f"})); + list.addAll(1,List.of(new String[]{"e", "f"})); assertEquals(4,listener.invoked); list.set(0,"g"); assertEquals(5,listener.invoked); diff --git a/vespajlib/src/test/java/com/yahoo/io/reader/NamedReaderTestCase.java b/vespajlib/src/test/java/com/yahoo/io/reader/NamedReaderTestCase.java index b1061fbc9ef..968746319d3 100644 --- a/vespajlib/src/test/java/com/yahoo/io/reader/NamedReaderTestCase.java +++ b/vespajlib/src/test/java/com/yahoo/io/reader/NamedReaderTestCase.java @@ -6,7 +6,6 @@ import java.io.Reader; import java.io.StringReader; import java.lang.reflect.Method; import java.nio.CharBuffer; -import java.util.Collections; import java.util.List; import com.yahoo.protect.ClassValidator; @@ -30,7 +29,7 @@ public class NamedReaderTestCase { assertEquals("test1",r.getName()); assertEquals("test1",r.toString()); assertEquals(stringReader,r.getReader()); - NamedReader.closeAll(Collections.singletonList(r)); + NamedReader.closeAll(List.of(r)); NamedReader.closeAll(null); // noop, nor exception } diff --git a/vespajlib/src/test/java/com/yahoo/net/UrlTokenizerTestCase.java b/vespajlib/src/test/java/com/yahoo/net/UrlTokenizerTestCase.java index 385d58db86f..100507c6cc1 100644 --- a/vespajlib/src/test/java/com/yahoo/net/UrlTokenizerTestCase.java +++ b/vespajlib/src/test/java/com/yahoo/net/UrlTokenizerTestCase.java @@ -359,7 +359,7 @@ public class UrlTokenizerTestCase { } private static void assertTokenize(Url url, UrlToken... expected) { - Iterator<UrlToken> expectedIt = Arrays.asList(expected).iterator(); + Iterator<UrlToken> expectedIt = List.of(expected).iterator(); Iterator<UrlToken> actualIt = new UrlTokenizer(url).tokenize().iterator(); while (expectedIt.hasNext()) { assertTrue(actualIt.hasNext()); @@ -373,7 +373,7 @@ public class UrlTokenizerTestCase { List<UrlToken> actual = new LinkedList<>(); UrlTokenizer.addTokens(actual, UrlToken.Type.PATH, 0, img, true); - Iterator<String> expectedIt = Arrays.asList(expected).iterator(); + Iterator<String> expectedIt = List.of(expected).iterator(); Iterator<UrlToken> actualIt = actual.iterator(); while (expectedIt.hasNext()) { assertTrue(actualIt.hasNext()); diff --git a/vespajlib/src/test/java/com/yahoo/tensor/IndexedTensorTestCase.java b/vespajlib/src/test/java/com/yahoo/tensor/IndexedTensorTestCase.java index 528ca57d256..b5d36326774 100644 --- a/vespajlib/src/test/java/com/yahoo/tensor/IndexedTensorTestCase.java +++ b/vespajlib/src/test/java/com/yahoo/tensor/IndexedTensorTestCase.java @@ -3,9 +3,9 @@ package com.yahoo.tensor; import org.junit.Test; -import java.util.Collections; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; @@ -139,7 +139,7 @@ public class IndexedTensorTestCase { Tensor.Builder builder = Tensor.Builder.of(type); builder.cell(47.0, 98); Tensor tensor = builder.build(); - assertEquals(47.0, tensor.sum(Collections.singletonList("x")).asDouble(), 0.000001); + assertEquals(47.0, tensor.sum(List.of("x")).asDouble(), 0.000001); } private void assertBuildingVWXYZ(TensorType type) { diff --git a/vespajlib/src/test/java/com/yahoo/tensor/MatrixDotProductBenchmark.java b/vespajlib/src/test/java/com/yahoo/tensor/MatrixDotProductBenchmark.java index 378e2397a89..6b0dbac8f2a 100644 --- a/vespajlib/src/test/java/com/yahoo/tensor/MatrixDotProductBenchmark.java +++ b/vespajlib/src/test/java/com/yahoo/tensor/MatrixDotProductBenchmark.java @@ -9,7 +9,6 @@ import com.yahoo.tensor.functions.Join; import com.yahoo.tensor.functions.Reduce; import com.yahoo.tensor.functions.TensorFunction; -import java.util.Collections; import java.util.List; import java.util.Random; @@ -69,7 +68,7 @@ public class MatrixDotProductBenchmark { .value(random.nextDouble()); } } - return Collections.singletonList(builder.build()); + return List.of(builder.build()); } private static void addDimension(TensorType.Builder builder, String name, TensorType.Dimension.Type type, int size) { diff --git a/vespajlib/src/test/java/com/yahoo/tensor/TensorTestCase.java b/vespajlib/src/test/java/com/yahoo/tensor/TensorTestCase.java index 69fb71b9b0e..7a51ea300f4 100644 --- a/vespajlib/src/test/java/com/yahoo/tensor/TensorTestCase.java +++ b/vespajlib/src/test/java/com/yahoo/tensor/TensorTestCase.java @@ -11,7 +11,6 @@ import com.yahoo.tensor.functions.TensorFunction; import org.junit.Test; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.DoubleBinaryOperator; @@ -214,7 +213,7 @@ public class TensorTestCase { Tensor unitK = Tensor.Builder.of(new TensorType.Builder().mapped("k").build()).cell().label("k", 0).value(1).build(); Tensor vectorInJSpace = vector(Type.mapped).multiply(unitJ); Tensor matrixInKSpace = matrix(Type.mapped, 2).get(0).multiply(unitK); - assertEquals("Generic computation implementation", 42, (int)dotProduct(vectorInJSpace, Collections.singletonList(matrixInKSpace))); + assertEquals("Generic computation implementation", 42, (int)dotProduct(vectorInJSpace, List.of(matrixInKSpace))); } @Test @@ -458,7 +457,7 @@ public class TensorTestCase { .value((i+1)*(j+1)); } } - return Collections.singletonList(builder.build()); + return List.of(builder.build()); } private TensorType vectorType(TensorType.Builder builder, String name, TensorType.Dimension.Type type, int size) { diff --git a/vespajlib/src/test/java/com/yahoo/tensor/TypeResolverTestCase.java b/vespajlib/src/test/java/com/yahoo/tensor/TypeResolverTestCase.java index 5d267d4d2f1..ce17a5d846d 100644 --- a/vespajlib/src/test/java/com/yahoo/tensor/TypeResolverTestCase.java +++ b/vespajlib/src/test/java/com/yahoo/tensor/TypeResolverTestCase.java @@ -3,7 +3,6 @@ package com.yahoo.tensor; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.junit.Test; @@ -17,7 +16,7 @@ import static org.junit.Assert.assertTrue; public class TypeResolverTestCase { private static List<String> mkl(String ...values) { - return Arrays.asList(values); + return List.of(values); } @Test diff --git a/zkfacade/src/main/java/com/yahoo/vespa/curator/mock/MemoryFileSystem.java b/zkfacade/src/main/java/com/yahoo/vespa/curator/mock/MemoryFileSystem.java index c4cc1541ca6..d05c8f11ad4 100644 --- a/zkfacade/src/main/java/com/yahoo/vespa/curator/mock/MemoryFileSystem.java +++ b/zkfacade/src/main/java/com/yahoo/vespa/curator/mock/MemoryFileSystem.java @@ -53,7 +53,7 @@ class MemoryFileSystem extends FileSystem { @Override public Iterable<Path> getRootDirectories() { - return Collections.singleton(Paths.get("/")); + return Set.of(Paths.get("/")); } @Override @@ -63,7 +63,7 @@ class MemoryFileSystem extends FileSystem { @Override public Set<String> supportedFileAttributeViews() { - return Collections.emptySet(); + return Set.of(); } @Override diff --git a/zkfacade/src/main/java/com/yahoo/vespa/curator/transaction/CuratorOperations.java b/zkfacade/src/main/java/com/yahoo/vespa/curator/transaction/CuratorOperations.java index 6a3184fa3e1..ed114c7c340 100644 --- a/zkfacade/src/main/java/com/yahoo/vespa/curator/transaction/CuratorOperations.java +++ b/zkfacade/src/main/java/com/yahoo/vespa/curator/transaction/CuratorOperations.java @@ -5,7 +5,6 @@ import com.yahoo.path.Path; import com.yahoo.vespa.curator.Curator; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Optional; @@ -62,7 +61,7 @@ public class CuratorOperations { * This does not fail, but returns an empty list if the path does not exist. */ public static List<CuratorOperation> deleteAll(String path, Curator curator) { - if ( ! curator.exists(Path.fromString(path))) return Collections.emptyList(); + if ( ! curator.exists(Path.fromString(path))) return List.of(); List<CuratorOperation> operations = new ArrayList<>(); deleteRecursively(Path.fromString(path), operations, curator); diff --git a/zookeeper-server/zookeeper-server-3.9.2/src/main/java/org/apache/zookeeper/common/ClientX509Util.java b/zookeeper-server/zookeeper-server-3.9.2/src/main/java/org/apache/zookeeper/common/ClientX509Util.java index 83cfaf11a92..f6dfb0fa4d9 100644 --- a/zookeeper-server/zookeeper-server-3.9.2/src/main/java/org/apache/zookeeper/common/ClientX509Util.java +++ b/zookeeper-server/zookeeper-server-3.9.2/src/main/java/org/apache/zookeeper/common/ClientX509Util.java @@ -23,7 +23,6 @@ import io.netty.handler.ssl.DelegatingSslContext; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; -import java.util.Arrays; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; @@ -32,6 +31,8 @@ import javax.net.ssl.TrustManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + /** * X509 utilities specific for client-server communication framework. * <p> @@ -196,9 +197,9 @@ public class ClientX509Util extends X509Util { if (getSslProvider(config) != SslProvider.JDK) { return null; } - return Arrays.asList(X509Util.getDefaultCipherSuites()); + return List.of(X509Util.getDefaultCipherSuites()); } else { - return Arrays.asList(cipherSuitesInput.split(",")); + return List.of(cipherSuitesInput.split(",")); } } diff --git a/zookeeper-server/zookeeper-server-3.9.2/src/main/java/org/apache/zookeeper/server/quorum/LearnerZooKeeperServer.java b/zookeeper-server/zookeeper-server-3.9.2/src/main/java/org/apache/zookeeper/server/quorum/LearnerZooKeeperServer.java index 8ea94fd4daf..99c4ae16dce 100644 --- a/zookeeper-server/zookeeper-server-3.9.2/src/main/java/org/apache/zookeeper/server/quorum/LearnerZooKeeperServer.java +++ b/zookeeper-server/zookeeper-server-3.9.2/src/main/java/org/apache/zookeeper/server/quorum/LearnerZooKeeperServer.java @@ -19,7 +19,6 @@ package org.apache.zookeeper.server.quorum; import java.io.IOException; -import java.util.Collections; import java.util.Map; import org.apache.zookeeper.jmx.MBeanRegistry; import org.apache.zookeeper.server.DataTreeBean; @@ -61,7 +60,7 @@ public abstract class LearnerZooKeeperServer extends QuorumZooKeeperServer { if (sessionTracker != null) { return ((LearnerSessionTracker) sessionTracker).snapshot(); } - Map<Long, Integer> map = Collections.emptyMap(); + Map<Long, Integer> map = Map.of(); return map; } diff --git a/zookeeper-server/zookeeper-server/src/main/java/org/apache/zookeeper/common/ClientX509Util.java b/zookeeper-server/zookeeper-server/src/main/java/org/apache/zookeeper/common/ClientX509Util.java index 83cfaf11a92..f6dfb0fa4d9 100644 --- a/zookeeper-server/zookeeper-server/src/main/java/org/apache/zookeeper/common/ClientX509Util.java +++ b/zookeeper-server/zookeeper-server/src/main/java/org/apache/zookeeper/common/ClientX509Util.java @@ -23,7 +23,6 @@ import io.netty.handler.ssl.DelegatingSslContext; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslProvider; -import java.util.Arrays; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; @@ -32,6 +31,8 @@ import javax.net.ssl.TrustManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + /** * X509 utilities specific for client-server communication framework. * <p> @@ -196,9 +197,9 @@ public class ClientX509Util extends X509Util { if (getSslProvider(config) != SslProvider.JDK) { return null; } - return Arrays.asList(X509Util.getDefaultCipherSuites()); + return List.of(X509Util.getDefaultCipherSuites()); } else { - return Arrays.asList(cipherSuitesInput.split(",")); + return List.of(cipherSuitesInput.split(",")); } } diff --git a/zookeeper-server/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/LearnerZooKeeperServer.java b/zookeeper-server/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/LearnerZooKeeperServer.java index 8ea94fd4daf..99c4ae16dce 100644 --- a/zookeeper-server/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/LearnerZooKeeperServer.java +++ b/zookeeper-server/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/LearnerZooKeeperServer.java @@ -19,7 +19,6 @@ package org.apache.zookeeper.server.quorum; import java.io.IOException; -import java.util.Collections; import java.util.Map; import org.apache.zookeeper.jmx.MBeanRegistry; import org.apache.zookeeper.server.DataTreeBean; @@ -61,7 +60,7 @@ public abstract class LearnerZooKeeperServer extends QuorumZooKeeperServer { if (sessionTracker != null) { return ((LearnerSessionTracker) sessionTracker).snapshot(); } - Map<Long, Integer> map = Collections.emptyMap(); + Map<Long, Integer> map = Map.of(); return map; } |