From 983c8e372214db116f707b41fb6d6bf9e0f037f8 Mon Sep 17 00:00:00 2001 From: Andrea Peruffo Date: Wed, 26 Oct 2022 17:41:48 +0100 Subject: [PATCH] Fix primitive types encoding of default values --- .../fabric8/java/generator/nodes/JObject.java | 38 +++++-- ...ojos.testAkkaMicroservicesCrd.approved.txt | 12 +- .../invoker.properties | 17 +++ .../it/default-values-instantiation/pom.xml | 106 ++++++++++++++++++ .../it/certmanager/TestDefaultValues.java | 63 +++++++++++ .../src/test/resources/empty.yaml | 21 ++++ .../src/test/resources/example.yaml | 94 ++++++++++++++++ 7 files changed, 336 insertions(+), 15 deletions(-) create mode 100644 java-generator/it/src/it/default-values-instantiation/invoker.properties create mode 100644 java-generator/it/src/it/default-values-instantiation/pom.xml create mode 100644 java-generator/it/src/it/default-values-instantiation/src/test/java/io/fabric8/it/certmanager/TestDefaultValues.java create mode 100644 java-generator/it/src/it/default-values-instantiation/src/test/resources/empty.yaml create mode 100644 java-generator/it/src/it/default-values-instantiation/src/test/resources/example.yaml diff --git a/java-generator/core/src/main/java/io/fabric8/java/generator/nodes/JObject.java b/java-generator/core/src/main/java/io/fabric8/java/generator/nodes/JObject.java index fb551675695..e1c4c11e82d 100644 --- a/java-generator/core/src/main/java/io/fabric8/java/generator/nodes/JObject.java +++ b/java-generator/core/src/main/java/io/fabric8/java/generator/nodes/JObject.java @@ -244,7 +244,19 @@ public GeneratorResult generateJava() { } if (prop.getDefaultValue() != null) { - objField.getVariable(0).setInitializer(generateDefaultInitializerExpression(prop)); + Expression primitiveDefault = generatePrimitiveDefaultInitializerExpression(prop); + + if (primitiveDefault != null) { + objField.getVariable(0).setInitializer(primitiveDefault); + } else { + objField.getVariable(0).setInitializer( + new NameExpr( + "io.fabric8.kubernetes.client.utils.Serialization.unmarshal(" + + "\"" + StringEscapeUtils.escapeJava(Serialization.asJson(prop.getDefaultValue())) + "\"" + + ", " + + prop.getClassType() + ".class" + + ")")); + } } } catch (Exception cause) { throw new JavaGeneratorException( @@ -286,17 +298,25 @@ public GeneratorResult generateJava() { } /** - * This method is responsible for creating an expression that will initialize the default value. + * This method is responsible for creating an expression that will initialize the default value if primitive * * @return a {@link Expression} instance that contains a call to the * {@link Serialization#unmarshal(String, Class)} method. */ - private Expression generateDefaultInitializerExpression(AbstractJSONSchema2Pojo prop) { - return new NameExpr( - "io.fabric8.kubernetes.client.utils.Serialization.unmarshal(" - + "\"" + StringEscapeUtils.escapeJava(Serialization.asJson(prop.getDefaultValue())) + "\"" - + ", " - + prop.getClassType() + ".class" - + ")"); + private Expression generatePrimitiveDefaultInitializerExpression(AbstractJSONSchema2Pojo prop) { + if (prop.getDefaultValue().isValueNode()) { + String value = prop.getDefaultValue().toString(); + if (prop.getClassType().equals("Long") && prop.getDefaultValue().canConvertToLong()) { + return new LongLiteralExpr(value + "L"); + } else if (prop.getClassType().equals("Float") && prop.getDefaultValue().isFloatingPointNumber()) { + return new DoubleLiteralExpr(value + "f"); + } else if (prop.getClassType().equals("Boolean") && prop.getDefaultValue().isBoolean()) { + return new BooleanLiteralExpr(prop.getDefaultValue().booleanValue()); + } else { + return new NameExpr(value); + } + } else { + return null; + } } } diff --git a/java-generator/core/src/test/resources/io/fabric8/java/generator/approvals/ApprovalTest.generate_withValidCrd_shouldGeneratePojos.testAkkaMicroservicesCrd.approved.txt b/java-generator/core/src/test/resources/io/fabric8/java/generator/approvals/ApprovalTest.generate_withValidCrd_shouldGeneratePojos.testAkkaMicroservicesCrd.approved.txt index b54a334b005..5ecdf7d9fd7 100644 --- a/java-generator/core/src/test/resources/io/fabric8/java/generator/approvals/ApprovalTest.generate_withValidCrd_shouldGeneratePojos.testAkkaMicroservicesCrd.approved.txt +++ b/java-generator/core/src/test/resources/io/fabric8/java/generator/approvals/ApprovalTest.generate_withValidCrd_shouldGeneratePojos.testAkkaMicroservicesCrd.approved.txt @@ -21,7 +21,7 @@ public class AkkaMicroserviceSpec implements io.fabric8.kubernetes.api.model.Kub @io.fabric8.generator.annotation.Pattern("^(off)$|^(102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$") @com.fasterxml.jackson.annotation.JsonPropertyDescription("Akka Management (Cluster Bootstrap) HTTP port in the range 1024 - 65535. Can be disabled with \"off\". This port is exposed as HTTP_MGMT_PORT environment variable if it is enabled.") @com.fasterxml.jackson.annotation.JsonSetter(nulls = com.fasterxml.jackson.annotation.Nulls.SKIP) - private String akkaManagementPort = io.fabric8.kubernetes.client.utils.Serialization.unmarshal("\"8558\"", String.class); + private String akkaManagementPort = "8558"; public String getAkkaManagementPort() { return akkaManagementPort; @@ -186,7 +186,7 @@ public class AkkaMicroserviceSpec implements io.fabric8.kubernetes.api.model.Kub @io.fabric8.generator.annotation.Pattern("^(off)$|^(102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$") @com.fasterxml.jackson.annotation.JsonPropertyDescription("gRPC port in the range 1024 - 65535. Can be disabled with \"off\". This port is exposed as GRPC_PORT environment variable if it is enabled.") @com.fasterxml.jackson.annotation.JsonSetter(nulls = com.fasterxml.jackson.annotation.Nulls.SKIP) - private String grpcPort = io.fabric8.kubernetes.client.utils.Serialization.unmarshal("\"8101\"", String.class); + private String grpcPort = "8101"; public String getGrpcPort() { return grpcPort; @@ -219,7 +219,7 @@ public class AkkaMicroserviceSpec implements io.fabric8.kubernetes.api.model.Kub @io.fabric8.generator.annotation.Pattern("^(off)$|^(102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$") @com.fasterxml.jackson.annotation.JsonPropertyDescription("HTTP port in the range 1024 - 65535. Disabled by default. This port is exposed as HTTP_PORT environment variable if it is enabled.") @com.fasterxml.jackson.annotation.JsonSetter(nulls = com.fasterxml.jackson.annotation.Nulls.SKIP) - private String httpPort = io.fabric8.kubernetes.client.utils.Serialization.unmarshal("\"off\"", String.class); + private String httpPort = "off"; public String getHttpPort() { return httpPort; @@ -285,7 +285,7 @@ public class AkkaMicroserviceSpec implements io.fabric8.kubernetes.api.model.Kub @com.fasterxml.jackson.annotation.JsonProperty("javaOptions") @com.fasterxml.jackson.annotation.JsonPropertyDescription("Additional arguments to the application JVM. It will be added to the `JAVA_TOOL_OPTIONS` environment variable, which will be used by most JVM implementations.") @com.fasterxml.jackson.annotation.JsonSetter(nulls = com.fasterxml.jackson.annotation.Nulls.SKIP) - private String javaOptions = io.fabric8.kubernetes.client.utils.Serialization.unmarshal("\"\"", String.class); + private String javaOptions = ""; public String getJavaOptions() { return javaOptions; @@ -398,7 +398,7 @@ public class AkkaMicroserviceSpec implements io.fabric8.kubernetes.api.model.Kub @io.fabric8.generator.annotation.Pattern("^(off)$|^(102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$") @com.fasterxml.jackson.annotation.JsonPropertyDescription("HTTP port to expose metrics for Prometheus to scrape. Must be in the range 1024 - 65535. Disabled by default. This port is exposed as HTTP_PROMETHEUS_PORT environment variable if it is enabled.") @com.fasterxml.jackson.annotation.JsonSetter(nulls = com.fasterxml.jackson.annotation.Nulls.SKIP) - private String prometheusPort = io.fabric8.kubernetes.client.utils.Serialization.unmarshal("\"off\"", String.class); + private String prometheusPort = "off"; public String getPrometheusPort() { return prometheusPort; @@ -432,7 +432,7 @@ public class AkkaMicroserviceSpec implements io.fabric8.kubernetes.api.model.Kub @io.fabric8.generator.annotation.Min(0.0) @com.fasterxml.jackson.annotation.JsonPropertyDescription("Number of desired pods.") @com.fasterxml.jackson.annotation.JsonSetter(nulls = com.fasterxml.jackson.annotation.Nulls.SKIP) - private Long replicas = io.fabric8.kubernetes.client.utils.Serialization.unmarshal("1", Long.class); + private Long replicas = 1L; public Long getReplicas() { return replicas; diff --git a/java-generator/it/src/it/default-values-instantiation/invoker.properties b/java-generator/it/src/it/default-values-instantiation/invoker.properties new file mode 100644 index 00000000000..9135f207843 --- /dev/null +++ b/java-generator/it/src/it/default-values-instantiation/invoker.properties @@ -0,0 +1,17 @@ +# +# Copyright (C) 2015 Red Hat, Inc. +# +# 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 +# +# http://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. +# + +invoker.goals=test diff --git a/java-generator/it/src/it/default-values-instantiation/pom.xml b/java-generator/it/src/it/default-values-instantiation/pom.xml new file mode 100644 index 00000000000..674f921e816 --- /dev/null +++ b/java-generator/it/src/it/default-values-instantiation/pom.xml @@ -0,0 +1,106 @@ + + + + + 4.0.0 + + default-values-instantiation + io.fabric8.it + 0.0-SNAPSHOT + jar + + + @maven.compiler.source@ + @maven.compiler.target@ + + + + + io.sundr + sundr-adapter-reflect + @sundrio.version@ + compile + + + io.sundr + builder-annotations + @sundrio.version@ + compile + + + org.projectlombok + lombok + @lombok.version@ + provided + + + io.fabric8 + java-generator-integration-tests + @project.version@ + + + io.fabric8 + generator-annotations + @project.version@ + + + org.junit.jupiter + junit-jupiter-api + @junit.version@ + test + + + org.junit.jupiter + junit-jupiter-engine + @junit.version@ + test + + + + + + + io.fabric8 + java-generator-maven-plugin + @project.version@ + + + + generate + + + + + src/test/resources/example.yaml + false + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M7 + + false + false + + + + + + diff --git a/java-generator/it/src/it/default-values-instantiation/src/test/java/io/fabric8/it/certmanager/TestDefaultValues.java b/java-generator/it/src/it/default-values-instantiation/src/test/java/io/fabric8/it/certmanager/TestDefaultValues.java new file mode 100644 index 00000000000..653c7093d39 --- /dev/null +++ b/java-generator/it/src/it/default-values-instantiation/src/test/java/io/fabric8/it/certmanager/TestDefaultValues.java @@ -0,0 +1,63 @@ +/** + * Copyright (C) 2015 Red Hat, Inc. + * + * 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 + * + * http://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 io.fabric8.it.certmanager; + +import com.fasterxml.jackson.databind.JsonNode; +import io.cert_manager.v1.CertificateRequest; +import io.cert_manager.v1.certificaterequestspec.Ten; +import io.fabric8.kubernetes.client.utils.Serialization; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TestDefaultValues { + + @Test + void testDefaultValues() throws Exception { + // Arrange + CertificateRequest cr = + Serialization.unmarshal(getClass().getResourceAsStream("/empty.yaml"), CertificateRequest.class); + + // Act + String one = cr.getSpec().getOne(); + Boolean two = cr.getSpec().getTwo(); + Integer three = cr.getSpec().getThree(); + Long four = cr.getSpec().getFour(); + Long five = cr.getSpec().getFive(); + Float six = cr.getSpec().getSix(); + Double seven = cr.getSpec().getSeven(); + Double eight = cr.getSpec().getEight(); + List nine = cr.getSpec().getNine(); + Ten ten = cr.getSpec().getTen(); + + // Assert + assertEquals("one", one); + assertEquals(true, two); + assertEquals(3, three); + assertEquals(4L, four); + assertEquals(5L, five); + assertEquals(6,1f, six); + assertEquals(7.2d, seven); + assertEquals(8.2d, eight); + assertEquals(2, nine.size()); + assertEquals("nine1", nine.get(0)); + assertEquals("nine2", nine.get(1)); + assertEquals("tenone", ten.getTenOne()); + assertEquals("tentwo", ten.getTenTwo()); + } +} diff --git a/java-generator/it/src/it/default-values-instantiation/src/test/resources/empty.yaml b/java-generator/it/src/it/default-values-instantiation/src/test/resources/empty.yaml new file mode 100644 index 00000000000..e05157362aa --- /dev/null +++ b/java-generator/it/src/it/default-values-instantiation/src/test/resources/empty.yaml @@ -0,0 +1,21 @@ +# +# Copyright (C) 2015 Red Hat, Inc. +# +# 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 +# +# http://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. +# + +apiVersion: cert-manager.io/v1 +kind: CertificateRequest +metadata: + name: my-ca-cr +spec: {} diff --git a/java-generator/it/src/it/default-values-instantiation/src/test/resources/example.yaml b/java-generator/it/src/it/default-values-instantiation/src/test/resources/example.yaml new file mode 100644 index 00000000000..f5efe9155a3 --- /dev/null +++ b/java-generator/it/src/it/default-values-instantiation/src/test/resources/example.yaml @@ -0,0 +1,94 @@ +# +# Copyright (C) 2015 Red Hat, Inc. +# +# 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 +# +# http://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. +# + + +--- +# Source: cert-manager/templates/templates.out +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: certificaterequests.cert-manager.io +spec: + group: cert-manager.io + names: + kind: CertificateRequest + listKind: CertificateRequestList + plural: certificaterequests + shortNames: + - cr + - crs + singular: certificaterequest + categories: + - cert-manager + scope: Namespaced + versions: + - name: v1 + schema: + openAPIV3Schema: + description: "A sample to verify all default values" + type: object + required: + - spec + properties: + spec: + description: Desired state of the CertificateRequest resource. + type: object + properties: + one: + type: string + default: one + two: + type: boolean + default: true + three: + type: integer + format: int32 + default: 3 + four: + type: integer + format: int64 + default: 4 + five: + type: integer + default: 5 + six: + type: number + format: float + default: 6.1 + seven: + type: number + format: double + default: 7.2 + eight: + type: number + default: 8.2 + nine: + type: array + items: + type: string + default: ['nine1', 'nine2'] + ten: + type: object + properties: + tenOne: + type: string + tenTwo: + type: string + default: + tenOne: "tenone" + tenTwo: "tentwo" + served: true + storage: true