Implement GraalVM native JSON configuration generation

This commit implements 4 package private Json serializers
for JavaSerializationHints, ProxyHints, ReflectionHints
and ResourceHints to serialize GraalVM native JSON configuration
as documented in
https://www.graalvm.org/22.0/reference-manual/native-image/BuildConfiguration/.

It exposes the related functionality via
NativeConfigurationGenerator which allows to generate the
relevant files on the filesystem via the
FileNativeConfigurationGenerator implementation.

The generated *-config.json files have been validated working
with GraalVM 22.0.

Closes gh-27991
This commit is contained in:
Sébastien Deleuze
2022-03-02 10:53:17 +01:00
parent bb9cf7cce1
commit 77e0100f42
15 changed files with 1280 additions and 0 deletions
@@ -0,0 +1,192 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.springframework.aot.hint.ExecutableMode;
import org.springframework.aot.hint.JavaSerializationHints;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.ProxyHints;
import org.springframework.aot.hint.ReflectionHints;
import org.springframework.aot.hint.ResourceHints;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeReference;
import org.springframework.core.codec.StringDecoder;
import org.springframework.util.MimeType;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link FileNativeConfigurationGenerator}.
*
* @author Sebastien Deleuze
*/
public class FileNativeConfigurationGeneratorTests {
@TempDir
static Path tempDir;
@Test
void emptyConfig() {
Path empty = tempDir.resolve("empty");
FileNativeConfigurationGenerator generator = new FileNativeConfigurationGenerator(empty);
generator.generate(new RuntimeHints());
assertThat(empty.toFile().listFiles()).isNull();
}
@Test
void serializationConfig() throws IOException, JSONException {
FileNativeConfigurationGenerator generator = new FileNativeConfigurationGenerator(tempDir);
RuntimeHints hints = new RuntimeHints();
JavaSerializationHints serializationHints = hints.javaSerialization();
serializationHints.registerType(Integer.class);
serializationHints.registerType(Long.class);
generator.generate(hints);
assertEquals("""
[
{ "name" : "java.lang.Integer" },
{ "name" : "java.lang.Long" }
]""", "serialization-config.json");
}
@Test
void proxyConfig() throws IOException, JSONException {
FileNativeConfigurationGenerator generator = new FileNativeConfigurationGenerator(tempDir);
RuntimeHints hints = new RuntimeHints();
ProxyHints proxyHints = hints.proxies();
proxyHints.registerJdkProxy(Function.class);
proxyHints.registerJdkProxy(Function.class, Consumer.class);
generator.generate(hints);
assertEquals("""
[
{ "interfaces" : [ "java.util.function.Function" ] },
{ "interfaces" : [ "java.util.function.Function", "java.util.function.Consumer" ] }
]""", "proxy-config.json");
}
@Test
void reflectionConfig() throws IOException, JSONException {
FileNativeConfigurationGenerator generator = new FileNativeConfigurationGenerator(tempDir);
RuntimeHints hints = new RuntimeHints();
ReflectionHints reflectionHints = hints.reflection();
reflectionHints.registerType(StringDecoder.class, builder -> {
builder
.onReachableType(TypeReference.of(String.class))
.withMembers(MemberCategory.PUBLIC_FIELDS, MemberCategory.DECLARED_FIELDS,
MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS, MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INTROSPECT_PUBLIC_METHODS, MemberCategory.INTROSPECT_DECLARED_METHODS,
MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.PUBLIC_CLASSES, MemberCategory.DECLARED_CLASSES)
.withField("DEFAULT_CHARSET", fieldBuilder -> {})
.withField("defaultCharset", fieldBuilder -> {
fieldBuilder.allowWrite(true);
fieldBuilder.allowUnsafeAccess(true);
})
.withConstructor(List.of(TypeReference.of(List.class), TypeReference.of(boolean.class), TypeReference.of(MimeType.class)), constructorHint ->
constructorHint.withMode(ExecutableMode.INTROSPECT))
.withMethod("setDefaultCharset", List.of(TypeReference.of(Charset.class)), ctorBuilder -> {})
.withMethod("getDefaultCharset", Collections.emptyList(), constructorHint ->
constructorHint.withMode(ExecutableMode.INTROSPECT));
});
generator.generate(hints);
assertEquals("""
[
{
"name" : "org.springframework.core.codec.StringDecoder",
"condition" : { "typeReachable" : "java.lang.String" },
"allPublicFields" : true,
"allDeclaredFields" : true,
"queryAllPublicConstructors" : true,
"queryAllDeclaredConstructors" : true,
"allPublicConstructors" : true,
"allDeclaredConstructors" : true,
"queryAllPublicMethods" : true,
"queryAllDeclaredMethods" : true,
"allPublicMethods" : true,
"allDeclaredMethods" : true,
"allPublicClasses" : true,
"allDeclaredClasses" : true,
"fields" : [
{ "name" : "DEFAULT_CHARSET" },
{ "name" : "defaultCharset", "allowWrite" = true, "allowUnsafeAccess" = true }
],
"methods" : [
{ "name" : "setDefaultCharset", "parameterTypes": [ "java.nio.charset.Charset" ] }
],
"queriedMethods" : [
{ "name" : "<init>", "parameterTypes": [ "java.util.List", "boolean", "org.springframework.util.MimeType" ] },
{ "name" : "getDefaultCharset" }
]
}
]""", "reflect-config.json");
}
@Test
void resourceConfig() throws IOException, JSONException {
FileNativeConfigurationGenerator generator = new FileNativeConfigurationGenerator(tempDir);
RuntimeHints hints = new RuntimeHints();
ResourceHints resourceHints = hints.resources();
resourceHints.registerPattern("com/example/test.properties");
resourceHints.registerPattern("com/example/another.properties");
generator.generate(hints);
assertEquals("""
{
"resources": {
"includes" : [
{"pattern" : "\\\\Qcom/example/test.properties\\\\E"},
{"pattern" : "\\\\Qcom/example/another.properties\\\\E"}
]
}
}""", "resource-config.json");
}
@Test
void namespace() {
String groupId = "foo.bar";
String artifactId = "baz";
String filename = "resource-config.json";
FileNativeConfigurationGenerator generator = new FileNativeConfigurationGenerator(tempDir, groupId, artifactId);
RuntimeHints hints = new RuntimeHints();
ResourceHints resourceHints = hints.resources();
resourceHints.registerPattern("com/example/test.properties");
generator.generate(hints);
Path jsonFile = tempDir.resolve("META-INF").resolve("native-image").resolve(groupId).resolve(artifactId).resolve(filename);
assertThat(jsonFile.toFile().exists()).isTrue();
}
private void assertEquals(String expectedString, String filename) throws IOException, JSONException {
Path jsonFile = tempDir.resolve("META-INF").resolve("native-image").resolve(filename);
String content = new String(Files.readAllBytes(jsonFile));
JSONAssert.assertEquals(expectedString, content, JSONCompareMode.LENIENT);
}
}
@@ -0,0 +1,68 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.springframework.aot.hint.JavaSerializationHints;
import org.springframework.aot.hint.TypeReference;
import org.springframework.core.env.Environment;
/**
* Tests for {@link JavaSerializationHintsSerializer}.
*
* @author Sebastien Deleuze
*/
public class JavaSerializationHintsSerializerTests {
private final JavaSerializationHintsSerializer serializer = new JavaSerializationHintsSerializer();
@Test
void empty() throws JSONException {
JavaSerializationHints hints = new JavaSerializationHints();
assertEquals("[]", hints);
}
@Test
void one() throws JSONException {
JavaSerializationHints hints = new JavaSerializationHints().registerType(TypeReference.of(String.class));
assertEquals("""
[
{ "name" : "java.lang.String" }
]""", hints);
}
@Test
void two() throws JSONException {
JavaSerializationHints hints = new JavaSerializationHints()
.registerType(TypeReference.of(String.class))
.registerType(TypeReference.of(Environment.class));
assertEquals("""
[
{ "name" : "java.lang.String" },
{ "name" : "org.springframework.core.env.Environment" }
]""", hints);
}
private void assertEquals(String expectedString, JavaSerializationHints hints) throws JSONException {
JSONAssert.assertEquals(expectedString, serializer.serialize(hints), JSONCompareMode.LENIENT);
}
}
@@ -0,0 +1,74 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link JsonUtils}.
*
* @author Sebastien Deleuze
*/
public class JsonUtilsTests {
@Test
void unescaped() {
assertThat(JsonUtils.escape("azerty")).isEqualTo("azerty");
}
@Test
void escapeDoubleQuote() {
assertThat(JsonUtils.escape("foo\"bar")).isEqualTo("foo\\\"bar");
}
@Test
void escapeBackslash() {
assertThat(JsonUtils.escape("foo\"bar")).isEqualTo("foo\\\"bar");
}
@Test
void escapeBackspace() {
assertThat(JsonUtils.escape("foo\bbar")).isEqualTo("foo\\bbar");
}
@Test
void escapeFormfeed() {
assertThat(JsonUtils.escape("foo\fbar")).isEqualTo("foo\\fbar");
}
@Test
void escapeNewline() {
assertThat(JsonUtils.escape("foo\nbar")).isEqualTo("foo\\nbar");
}
@Test
void escapeCarriageReturn() {
assertThat(JsonUtils.escape("foo\rbar")).isEqualTo("foo\\rbar");
}
@Test
void escapeTab() {
assertThat(JsonUtils.escape("foo\tbar")).isEqualTo("foo\\tbar");
}
@Test
void escapeUnicode() {
assertThat(JsonUtils.escape("foo\u001Fbar")).isEqualTo("foo\\u001fbar");
}
}
@@ -0,0 +1,71 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex;
import java.util.function.Consumer;
import java.util.function.Function;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.springframework.aot.hint.ProxyHints;
/**
* Tests for {@link ProxyHintsSerializer}.
*
* @author Sebastien Deleuze
*/
public class ProxyHintsSerializerTests {
private final ProxyHintsSerializer serializer = new ProxyHintsSerializer();
@Test
void empty() throws JSONException {
ProxyHints hints = new ProxyHints();
assertEquals("[]", hints);
}
@Test
void one() throws JSONException {
ProxyHints hints = new ProxyHints();
hints.registerJdkProxy(Function.class);
assertEquals("""
[
{ "interfaces" : [ "java.util.function.Function" ] }
]""", hints);
}
@Test
void two() throws JSONException {
ProxyHints hints = new ProxyHints();
hints.registerJdkProxy(Function.class);
hints.registerJdkProxy(Function.class, Consumer.class);
assertEquals("""
[
{ "interfaces" : [ "java.util.function.Function" ] },
{ "interfaces" : [ "java.util.function.Function", "java.util.function.Consumer" ] }
]""", hints);
}
private void assertEquals(String expectedString, ProxyHints hints) throws JSONException {
JSONAssert.assertEquals(expectedString, serializer.serialize(hints), JSONCompareMode.LENIENT);
}
}
@@ -0,0 +1,124 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.springframework.aot.hint.ExecutableMode;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.ReflectionHints;
import org.springframework.aot.hint.TypeReference;
import org.springframework.core.codec.StringDecoder;
import org.springframework.util.MimeType;
/**
* Tests for {@link ReflectionHintsSerializer}.
*
* @author Sebastien Deleuze
*/
public class ReflectionHintsSerializerTests {
private final ReflectionHintsSerializer serializer = new ReflectionHintsSerializer();
@Test
void empty() throws JSONException {
ReflectionHints hints = new ReflectionHints();
assertEquals("[]", hints);
}
@Test
void one() throws JSONException {
ReflectionHints hints = new ReflectionHints();
hints.registerType(StringDecoder.class, builder -> {
builder
.onReachableType(TypeReference.of(String.class))
.withMembers(MemberCategory.PUBLIC_FIELDS, MemberCategory.DECLARED_FIELDS,
MemberCategory.INTROSPECT_PUBLIC_CONSTRUCTORS, MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INTROSPECT_PUBLIC_METHODS, MemberCategory.INTROSPECT_DECLARED_METHODS,
MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.PUBLIC_CLASSES, MemberCategory.DECLARED_CLASSES)
.withField("DEFAULT_CHARSET", fieldBuilder -> {})
.withField("defaultCharset", fieldBuilder -> {
fieldBuilder.allowWrite(true);
fieldBuilder.allowUnsafeAccess(true);
})
.withConstructor(List.of(TypeReference.of(List.class), TypeReference.of(boolean.class), TypeReference.of(MimeType.class)), constructorHint ->
constructorHint.withMode(ExecutableMode.INTROSPECT))
.withMethod("setDefaultCharset", List.of(TypeReference.of(Charset.class)), ctorBuilder -> {})
.withMethod("getDefaultCharset", Collections.emptyList(), constructorHint ->
constructorHint.withMode(ExecutableMode.INTROSPECT));
});
assertEquals("""
[
{
"name" : "org.springframework.core.codec.StringDecoder",
"condition" : { "typeReachable" : "java.lang.String" },
"allPublicFields" : true,
"allDeclaredFields" : true,
"queryAllPublicConstructors" : true,
"queryAllDeclaredConstructors" : true,
"allPublicConstructors" : true,
"allDeclaredConstructors" : true,
"queryAllPublicMethods" : true,
"queryAllDeclaredMethods" : true,
"allPublicMethods" : true,
"allDeclaredMethods" : true,
"allPublicClasses" : true,
"allDeclaredClasses" : true,
"fields" : [
{ "name" : "DEFAULT_CHARSET" },
{ "name" : "defaultCharset", "allowWrite" = true, "allowUnsafeAccess" = true }
],
"methods" : [
{ "name" : "setDefaultCharset", "parameterTypes": [ "java.nio.charset.Charset" ] }
],
"queriedMethods" : [
{ "name" : "<init>", "parameterTypes": [ "java.util.List", "boolean", "org.springframework.util.MimeType" ] },
{ "name" : "getDefaultCharset" }
]
}
]""", hints);
}
@Test
void two() throws JSONException {
ReflectionHints hints = new ReflectionHints();
hints.registerType(Integer.class, builder -> {
});
hints.registerType(Long.class, builder -> {
});
assertEquals("""
[
{ "name" : "java.lang.Integer" },
{ "name" : "java.lang.Long" }
]""", hints);
}
private void assertEquals(String expectedString, ReflectionHints hints) throws JSONException {
JSONAssert.assertEquals(expectedString, serializer.serialize(hints), JSONCompareMode.LENIENT);
}
}
@@ -0,0 +1,125 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex;
import java.io.IOException;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.springframework.aot.hint.ResourceHints;
/**
* Tests for {@link ResourceHintsSerializer}.
*
* @author Sebastien Deleuze
*/
public class ResourceHintsSerializerTests {
private final ResourceHintsSerializer serializer = new ResourceHintsSerializer();
@Test
void empty() throws IOException, JSONException {
ResourceHints hints = new ResourceHints();
assertEquals("{}", hints);
}
@Test
void registerExactMatch() throws JSONException {
ResourceHints hints = new ResourceHints();
hints.registerPattern("com/example/test.properties");
hints.registerPattern("com/example/another.properties");
assertEquals("""
{
"resources": {
"includes": [
{ "pattern" : "\\\\Qcom/example/test.properties\\\\E"},
{ "pattern" : "\\\\Qcom/example/another.properties\\\\E"}
]
}
}""", hints);
}
@Test
void registerPattern() throws JSONException {
ResourceHints hints = new ResourceHints();
hints.registerPattern("com/example/*.properties");
assertEquals("""
{
"resources": {
"includes" : [
{ "pattern" : "\\\\Qcom/example/\\\\E.*\\\\Q.properties\\\\E"}
]
}
}""", hints);
}
@Test
void registerPatternWithIncludesAndExcludes() throws JSONException {
ResourceHints hints = new ResourceHints();
hints.registerPattern("com/example/*.properties", hint -> hint.excludes("com/example/to-ignore.properties"));
hints.registerPattern("org/example/*.properties", hint -> hint.excludes("org/example/to-ignore.properties"));
assertEquals("""
{
"resources": {
"includes": [
{ "pattern" : "\\\\Qcom/example/\\\\E.*\\\\Q.properties\\\\E"},
{ "pattern" : "\\\\Qorg/example/\\\\E.*\\\\Q.properties\\\\E"}
],
"excludes": [
{ "pattern" : "\\\\Qcom/example/to-ignore.properties\\\\E"},
{ "pattern" : "\\\\Qorg/example/to-ignore.properties\\\\E"}
]
}
}""", hints);
}
@Test
void registerType() throws JSONException {
ResourceHints hints = new ResourceHints();
hints.registerType(String.class);
assertEquals("""
{
"resources": {
"includes" : [
{ "pattern" : "\\\\Qjava/lang/String.class\\\\E"}
]
}
}""", hints);
}
@Test
void registerResourceBundle() throws JSONException {
ResourceHints hints = new ResourceHints();
hints.registerResourceBundle("com.example.message");
hints.registerResourceBundle("com.example.message2");
assertEquals("""
{
"bundles": [
{ "name" : "com.example.message"},
{ "name" : "com.example.message2"}
]
}""", hints);
}
private void assertEquals(String expectedString, ResourceHints hints) throws JSONException {
JSONAssert.assertEquals(expectedString, serializer.serialize(hints), JSONCompareMode.LENIENT);
}
}