diff --git a/.github/workflows/springwolf-addons.yml b/.github/workflows/springwolf-addons.yml index c516baf30..f972d3b5f 100644 --- a/.github/workflows/springwolf-addons.yml +++ b/.github/workflows/springwolf-addons.yml @@ -51,6 +51,15 @@ jobs: - name: Run build, check, analyzeDependencies on add-on run: ./gradlew -p ${{ env.addon }} build + - name: Publish Test Report + uses: mikepenz/action-junit-report@v6 + if: success() || failure() + with: + check_name: test-addon-${{ matrix.addon }} + require_tests: true + report_paths: '**/build/test-results/test/TEST-*.xml' + annotate_only: github.event.pull_request.head.repo.full_name != github.repository # for forks + - name: Publish package if: github.ref == 'refs/heads/main' run: ./gradlew -p ${{ env.addon }} publish diff --git a/.github/workflows/springwolf-asyncapi.yml b/.github/workflows/springwolf-asyncapi.yml index 3d27923e5..76a6c1374 100644 --- a/.github/workflows/springwolf-asyncapi.yml +++ b/.github/workflows/springwolf-asyncapi.yml @@ -40,6 +40,15 @@ jobs: - name: Build with Gradle run: ./gradlew -p springwolf-asyncapi build + - name: Publish Test Report + uses: mikepenz/action-junit-report@v6 + if: success() || failure() + with: + check_name: test-asyncapi + require_tests: true + report_paths: '**/build/test-results/test/TEST-*.xml' + annotate_only: github.event.pull_request.head.repo.full_name != github.repository # for forks + - name: Publish package if: github.ref == 'refs/heads/main' run: ./gradlew -p springwolf-asyncapi publish diff --git a/.github/workflows/springwolf-bindings.yml b/.github/workflows/springwolf-bindings.yml index a2698e02a..687f6c966 100644 --- a/.github/workflows/springwolf-bindings.yml +++ b/.github/workflows/springwolf-bindings.yml @@ -43,6 +43,15 @@ jobs: - name: Run build, check, analyzeDependencies on bindings run: ./gradlew -p springwolf-bindings build + - name: Publish Test Report + uses: mikepenz/action-junit-report@v6 + if: success() || failure() + with: + check_name: test-bindings + require_tests: true + report_paths: '**/build/test-results/test/TEST-*.xml' + annotate_only: github.event.pull_request.head.repo.full_name != github.repository # for forks + - name: Publish package if: github.ref == 'refs/heads/main' run: ./gradlew -p springwolf-bindings publish diff --git a/springwolf-add-ons/springwolf-common-model-converters/src/main/java/io/github/springwolf/addons/common_model_converters/converters/SimpleClassModelConverter.java b/springwolf-add-ons/springwolf-common-model-converters/src/main/java/io/github/springwolf/addons/common_model_converters/converters/SimpleClassModelConverter.java index 0604c0dd3..813c8b7cb 100644 --- a/springwolf-add-ons/springwolf-common-model-converters/src/main/java/io/github/springwolf/addons/common_model_converters/converters/SimpleClassModelConverter.java +++ b/springwolf-add-ons/springwolf-common-model-converters/src/main/java/io/github/springwolf/addons/common_model_converters/converters/SimpleClassModelConverter.java @@ -14,7 +14,7 @@ * Sometimes adding documentation annotation is not possible on classes, i.e. they are marked as final or are from external libraries. * This converter allows to add documentation to such classes. Duplicate the _target_ class as _native_ into your project and add documentation annotations. * Then, create an instance (@Bean, @Component) of this converter in your configuration mapping the classes. - * + *

* Example: {@link io.github.springwolf.addons.common_model_converters.converters.monetaryamount.MonetaryAmountConverter} */ public class SimpleClassModelConverter implements ModelConverter { @@ -28,7 +28,7 @@ public SimpleClassModelConverter(Class targetClass, Class nativeClass) { } @Override - public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator chain) { + public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator chain) { Class rawClass = getRawClass(type); boolean isNativeType = isNativeType(rawClass); @@ -50,7 +50,8 @@ private Class getRawClass(AnnotatedType type) { return javaType != null ? javaType.getRawClass() : null; } - private Schema proceedWithChain(AnnotatedType type, ModelConverterContext context, Iterator chain) { + private Schema proceedWithChain( + AnnotatedType type, ModelConverterContext context, Iterator chain) { return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null; } diff --git a/springwolf-add-ons/springwolf-common-model-converters/src/main/java/io/github/springwolf/addons/common_model_converters/converters/enums/NameInReffedSchemaModelConverter.java b/springwolf-add-ons/springwolf-common-model-converters/src/main/java/io/github/springwolf/addons/common_model_converters/converters/enums/NameInReffedSchemaModelConverter.java index 01901e130..d1762e0fa 100644 --- a/springwolf-add-ons/springwolf-common-model-converters/src/main/java/io/github/springwolf/addons/common_model_converters/converters/enums/NameInReffedSchemaModelConverter.java +++ b/springwolf-add-ons/springwolf-common-model-converters/src/main/java/io/github/springwolf/addons/common_model_converters/converters/enums/NameInReffedSchemaModelConverter.java @@ -12,12 +12,12 @@ import java.util.Iterator; /** - * Workaround for https://github.com/swagger-api/swagger-core/pull/4727 + * Workaround for swagger-core PR 4727 */ public class NameInReffedSchemaModelConverter implements ModelConverter { @Override - public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator chain) { + public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator chain) { JavaType javaType = Json.mapper().constructType(type.getType()); if (chain.hasNext()) { Schema schema = chain.next().resolve(type, context, chain); diff --git a/springwolf-add-ons/springwolf-common-model-converters/src/test/java/io/github/springwolf/addons/common_model_converters/converters/enums/NameInReffedSchemaModelConverterTest.java b/springwolf-add-ons/springwolf-common-model-converters/src/test/java/io/github/springwolf/addons/common_model_converters/converters/enums/NameInReffedSchemaModelConverterTest.java index 6a9753160..2d07cf71e 100644 --- a/springwolf-add-ons/springwolf-common-model-converters/src/test/java/io/github/springwolf/addons/common_model_converters/converters/enums/NameInReffedSchemaModelConverterTest.java +++ b/springwolf-add-ons/springwolf-common-model-converters/src/test/java/io/github/springwolf/addons/common_model_converters/converters/enums/NameInReffedSchemaModelConverterTest.java @@ -21,19 +21,19 @@ void nameIsAddedToReffedSchema() { converters.addConverter(modelsConverter); // when - final Map models = converters.readAll(MyRootObject.class); + final Map models = converters.readAll(MyRootObject.class); // then assertThat(models).isNotNull(); assertThat(models.size()).isEqualTo(2); - Schema myRootObject = models.get("MyRootObject"); + Schema myRootObject = (Schema) models.get("MyRootObject"); assertThat(myRootObject).isNotNull(); assertThat(myRootObject.getName()).isEqualTo("MyRootObject"); - Schema myEnumObjectField = (Schema) myRootObject.getProperties().get("myEnumObjectField"); + Schema myEnumObjectField = (Schema) myRootObject.getProperties().get("myEnumObjectField"); assertThat(myEnumObjectField.getName()).isEqualTo("myEnumObjectField"); assertThat(myEnumObjectField.get$ref()).isEqualTo("#/components/schemas/MyEnumObject"); - Schema myEnumObject = models.get("MyEnumObject"); + Schema myEnumObject = (Schema) models.get("MyEnumObject"); assertThat(myEnumObject).isNotNull(); assertThat(myEnumObject.getName()).isEqualTo("MyEnumObject"); } diff --git a/springwolf-add-ons/springwolf-common-model-converters/src/test/java/io/github/springwolf/addons/common_model_converters/converters/monetaryamount/MonetaryAmountConverterTest.java b/springwolf-add-ons/springwolf-common-model-converters/src/test/java/io/github/springwolf/addons/common_model_converters/converters/monetaryamount/MonetaryAmountConverterTest.java index 84aeafbd9..60f6af179 100644 --- a/springwolf-add-ons/springwolf-common-model-converters/src/test/java/io/github/springwolf/addons/common_model_converters/converters/monetaryamount/MonetaryAmountConverterTest.java +++ b/springwolf-add-ons/springwolf-common-model-converters/src/test/java/io/github/springwolf/addons/common_model_converters/converters/monetaryamount/MonetaryAmountConverterTest.java @@ -22,25 +22,25 @@ void monetaryAmountConverter() { converters.addConverter(modelsConverter); // when - final Map models = converters.readAll(new AnnotatedType(javax.money.MonetaryAmount.class)); + final Map models = converters.readAll(new AnnotatedType(javax.money.MonetaryAmount.class)); // then - final Schema model = models.get("MonetaryAmount"); + final Schema model = (Schema) models.get("MonetaryAmount"); assertThat(model).isNotNull(); assertThat(model.getProperties().size()).isEqualTo(2); - final Schema amountProperty = (Schema) model.getProperties().get("amount"); + final Schema amountProperty = (Schema) model.getProperties().get("amount"); assertThat(amountProperty).isNotNull(); - final Schema currencyProperty = (Schema) model.getProperties().get("currency"); + final Schema currencyProperty = (Schema) model.getProperties().get("currency"); assertThat(currencyProperty).isNotNull(); - final Schema missingProperty = (Schema) model.getProperties().get("missing"); + final Schema missingProperty = (Schema) model.getProperties().get("missing"); assertThat(missingProperty).isNull(); // then - final Schema originalModel = models.get("javax.money.MonetaryAmount"); + final Schema originalModel = (Schema) models.get("javax.money.MonetaryAmount"); assertThat(originalModel).isNotNull(); assertThat(originalModel.getType()).isNull(); diff --git a/springwolf-add-ons/springwolf-json-schema/src/test/java/io/github/springwolf/addons/json_schema/JsonSchemaCustomizerTest.java b/springwolf-add-ons/springwolf-json-schema/src/test/java/io/github/springwolf/addons/json_schema/JsonSchemaCustomizerTest.java index a512f1d44..3431a4b96 100644 --- a/springwolf-add-ons/springwolf-json-schema/src/test/java/io/github/springwolf/addons/json_schema/JsonSchemaCustomizerTest.java +++ b/springwolf-add-ons/springwolf-json-schema/src/test/java/io/github/springwolf/addons/json_schema/JsonSchemaCustomizerTest.java @@ -41,7 +41,7 @@ void handleEmptySchemaTest() { } @Test - void shouldAddJsonSchemaExtensionTest() throws Exception { + void shouldAddJsonSchemaExtensionTest() { // given AsyncAPI asyncAPI = createAsyncApi(); SchemaObject schemaObject = new SchemaObject(); diff --git a/springwolf-add-ons/springwolf-json-schema/src/test/java/io/github/springwolf/addons/json_schema/JsonSchemaGeneratorTest.java b/springwolf-add-ons/springwolf-json-schema/src/test/java/io/github/springwolf/addons/json_schema/JsonSchemaGeneratorTest.java index a7b5db537..3394f3a44 100644 --- a/springwolf-add-ons/springwolf-json-schema/src/test/java/io/github/springwolf/addons/json_schema/JsonSchemaGeneratorTest.java +++ b/springwolf-add-ons/springwolf-json-schema/src/test/java/io/github/springwolf/addons/json_schema/JsonSchemaGeneratorTest.java @@ -10,7 +10,7 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; import io.github.springwolf.asyncapi.v3.model.schema.SchemaType; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.BooleanSchema; @@ -46,7 +46,7 @@ class JsonSchemaGeneratorTest { @ParameterizedTest @MethodSource - void validateJsonSchemaTest(String expectedJsonSchema, Supplier> asyncApiSchema) throws Exception { + void validateJsonSchemaTest(String expectedJsonSchema, Supplier> asyncApiSchema) { // given ComponentSchema actualSchema = swaggerSchemaMapper.mapSchema(asyncApiSchema.get()); diff --git a/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/bindings/jms/JMSServerBinding.java b/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/bindings/jms/JMSServerBinding.java index 2c6785278..45b5f8448 100644 --- a/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/bindings/jms/JMSServerBinding.java +++ b/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/bindings/jms/JMSServerBinding.java @@ -32,7 +32,7 @@ public class JMSServerBinding extends ServerBinding { /** * OPTIONAL. Additional properties to set on the JMS ConnectionFactory implementation for the JMS Provider. */ - // FIXME: See https://github.com/asyncapi/bindings/issues/232 + // Bug report, see https://github.com/asyncapi/bindings/issues/232 @JsonProperty("properties") private List> properties; diff --git a/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/model/AsyncAPI.java b/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/model/AsyncAPI.java index 360b9c040..acc3bbdfb 100644 --- a/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/model/AsyncAPI.java +++ b/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/model/AsyncAPI.java @@ -34,7 +34,7 @@ public class AsyncAPI extends ExtendableObject { /** * REQUIRED. Specifies the AsyncAPI Specification version being used. It can be used by tooling Specifications and * clients to interpret the version. The structure shall be major.minor.patch, where patch versions must be - * compatible with the existing major.minor tooling. Typically patch versions will be introduced to address errors + * compatible with the existing major.minor tooling. Typically, patch versions will be introduced to address errors * in the documentation, and tooling should typically be compatible with the corresponding major.minor (1.0.*). * Patch versions will correspond to patches of this document. */ diff --git a/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/model/components/ComponentSchema.java b/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/model/components/ComponentSchema.java index 08a29528b..7d02783aa 100644 --- a/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/model/components/ComponentSchema.java +++ b/springwolf-asyncapi/src/main/java/io/github/springwolf/asyncapi/v3/model/components/ComponentSchema.java @@ -14,9 +14,9 @@ /** * Container class representing a schema in the 'components' block of an AsyncAPI document. Contains either *

* Json Serialization removes this container class and serializes the content Object directly. */ diff --git a/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/bindings/jms/JMSBindingTest.java b/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/bindings/jms/JMSBindingTest.java index 1864b9c72..0ccb57e1b 100644 --- a/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/bindings/jms/JMSBindingTest.java +++ b/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/bindings/jms/JMSBindingTest.java @@ -44,7 +44,7 @@ void shouldSerializeJMSChannel() throws Exception { .isEqualTo(example); } - // FIXME: See https://github.com/asyncapi/bindings/issues/232 + // Bug report, see https://github.com/asyncapi/bindings/issues/232 @Test void shouldSerializeJMSServerBinding() throws Exception { var asyncapi = AsyncAPI.builder() diff --git a/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/jackson/DefaultAsyncApiSerializerServiceIntegrationTest.java b/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/jackson/DefaultAsyncApiSerializerServiceIntegrationTest.java index 09b7bfdbe..cf6bcd8ee 100644 --- a/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/jackson/DefaultAsyncApiSerializerServiceIntegrationTest.java +++ b/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/jackson/DefaultAsyncApiSerializerServiceIntegrationTest.java @@ -79,7 +79,6 @@ private AsyncAPI getAsyncAPITestObject(SchemaFormat schemaFormat) { .bindings(Map.of( "kafka", KafkaMessageBinding.builder() - // FIXME: We should have a SchemaString (Schema) .key(SchemaObject.builder() .type(Set.of(SchemaType.STRING.getValue())) .build()) @@ -150,8 +149,10 @@ private Map createPayloadSchema(SchemaFormat schemaForm void AsyncAPI_should_map_to_a_valid_asyncapi_json(SchemaFormat schemaFormat, String expectedFile) throws Exception { AsyncAPI asyncapi = getAsyncAPITestObject(schemaFormat); String actual = serializer.toJsonString(asyncapi); - InputStream s = this.getClass().getResourceAsStream(expectedFile + ".json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8); + String expected; + try (InputStream s = this.getClass().getResourceAsStream(expectedFile + ".json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8); + } assertThatJson(actual).isEqualTo(expected); } diff --git a/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/AsyncAPITest.java b/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/AsyncAPITest.java index 195f70af3..367567341 100644 --- a/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/AsyncAPITest.java +++ b/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/AsyncAPITest.java @@ -382,7 +382,4 @@ void shouldCreateStreetlightsKafkaAsyncAPI() throws Exception { .whenIgnoringPaths("components.operationTraits.kafka.bindings.kafka.bindingVersion") .isEqualTo(example); } - - // FIXME: We should have the capability to serialize automatically creating the $ref values with the proper keys - // Current approach forces the developer to manually create the structure, which is limiting } diff --git a/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/operation/OperationTest.java b/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/operation/OperationTest.java index fb874d3b5..2c097110f 100644 --- a/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/operation/OperationTest.java +++ b/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/operation/OperationTest.java @@ -51,7 +51,7 @@ void shouldSerializeOperation() throws Exception { String example = ClasspathUtil.readAsString("/v3/model/operation/operation.json"); assertThatJson(serializer.toJsonString(operation)) - // FIXME: https://github.com/asyncapi/spec/issues/1007 + // Bug report, see https://github.com/asyncapi/spec/issues/1007 .whenIgnoringPaths("bindings.amqp.bindingVersion", "bindings.amqp.expiration", "security") .isEqualTo(example); } diff --git a/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/schema/SchemaTest.java b/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/schema/SchemaTest.java index e01872fbb..3e966d3a6 100644 --- a/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/schema/SchemaTest.java +++ b/springwolf-asyncapi/src/test/java/io/github/springwolf/asyncapi/v3/model/schema/SchemaTest.java @@ -16,7 +16,7 @@ class SchemaTest { private static final DefaultAsyncApiSerializerService serializer = new DefaultAsyncApiSerializerService(); @Test - void shouldSerializePrimitiveSample() throws Exception { + void shouldSerializePrimitiveSample() { var schema = SchemaObject.builder() .type(Set.of(SchemaType.STRING.getValue())) .format("email") @@ -32,7 +32,7 @@ void shouldSerializePrimitiveSample() throws Exception { } @Test - void shouldSerializeSimpleModel() throws Exception { + void shouldSerializeSimpleModel() { var schema = SchemaObject.builder() .type(Set.of(SchemaType.OBJECT.getValue())) .required(List.of("name")) @@ -75,7 +75,7 @@ void shouldSerializeSimpleModel() throws Exception { } @Test - void shouldSerializeStringToStringMapping() throws Exception { + void shouldSerializeStringToStringMapping() { var schema = SchemaObject.builder() .type(Set.of(SchemaType.OBJECT.getValue())) .additionalProperties(ComponentSchema.of(SchemaObject.builder() @@ -95,7 +95,7 @@ void shouldSerializeStringToStringMapping() throws Exception { } @Test - void shouldSerializeModelMapping() throws Exception { + void shouldSerializeModelMapping() { var schema = SchemaObject.builder() .type(Set.of(SchemaType.OBJECT.getValue())) .additionalProperties(ComponentSchema.of(SchemaReference.toSchema("ComplexModel"))) @@ -113,7 +113,7 @@ void shouldSerializeModelMapping() throws Exception { } @Test - void shouldSerializeModelWithExample() throws Exception { + void shouldSerializeModelWithExample() { var schema = SchemaObject.builder() .type(Set.of(SchemaType.OBJECT.getValue())) .properties(Map.of( @@ -157,7 +157,7 @@ void shouldSerializeModelWithExample() throws Exception { } @Test - void shouldSerializeModelWithBooleans() throws Exception { + void shouldSerializeModelWithBooleans() { var schema = SchemaObject.builder() .type(Set.of(SchemaType.OBJECT.getValue())) .properties(Map.of( @@ -182,7 +182,7 @@ void shouldSerializeModelWithBooleans() throws Exception { } @Test - void shouldSerializeModelsWithComposition() throws Exception { + void shouldSerializeModelsWithComposition() { var schemas = Map.of( "schemas", Map.of( @@ -262,7 +262,7 @@ void shouldSerializeModelsWithComposition() throws Exception { } @Test - void shouldSerializeModelsWithPolimorphismSupport() throws Exception { + void shouldSerializeModelsWithPolimorphismSupport() { var schemas = Map.of( "schemas", Map.of( diff --git a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/amqp/scanners/operations/AmqpOperationBindingProcessor.java b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/amqp/scanners/operations/AmqpOperationBindingProcessor.java index 097483e3a..90d5660da 100644 --- a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/amqp/scanners/operations/AmqpOperationBindingProcessor.java +++ b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/amqp/scanners/operations/AmqpOperationBindingProcessor.java @@ -11,7 +11,7 @@ public class AmqpOperationBindingProcessor extends AbstractOperationBindingProcessor { public AmqpOperationBindingProcessor(StringValueResolver stringValueResolver) { - super(stringValueResolver); + super(stringValueResolver, AmqpAsyncOperationBinding.class); } @Override diff --git a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/generic/annotation/AsyncGenericOperationBinding.java b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/generic/annotations/AsyncGenericOperationBinding.java similarity index 93% rename from springwolf-bindings/src/main/java/io/github/springwolf/bindings/generic/annotation/AsyncGenericOperationBinding.java rename to springwolf-bindings/src/main/java/io/github/springwolf/bindings/generic/annotations/AsyncGenericOperationBinding.java index ba7ef6cdf..702d8e633 100644 --- a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/generic/annotation/AsyncGenericOperationBinding.java +++ b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/generic/annotations/AsyncGenericOperationBinding.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.bindings.generic.annotation; +package io.github.springwolf.bindings.generic.annotations; import io.github.springwolf.core.asyncapi.annotations.AsyncOperationBinding; diff --git a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/generic/scanners/operations/AsyncGenericOperationBindingProcessor.java b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/generic/scanners/operations/AsyncGenericOperationBindingProcessor.java index 24f07f2d6..86b101bf8 100644 --- a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/generic/scanners/operations/AsyncGenericOperationBindingProcessor.java +++ b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/generic/scanners/operations/AsyncGenericOperationBindingProcessor.java @@ -2,7 +2,7 @@ package io.github.springwolf.bindings.generic.scanners.operations; import io.github.springwolf.asyncapi.v3.bindings.OperationBinding; -import io.github.springwolf.bindings.generic.annotation.AsyncGenericOperationBinding; +import io.github.springwolf.bindings.generic.annotations.AsyncGenericOperationBinding; import io.github.springwolf.core.asyncapi.scanners.bindings.operations.AbstractOperationBindingProcessor; import io.github.springwolf.core.asyncapi.scanners.bindings.operations.ProcessedOperationBinding; import org.springframework.util.StringValueResolver; @@ -14,7 +14,7 @@ public class AsyncGenericOperationBindingProcessor extends AbstractOperationBindingProcessor { public AsyncGenericOperationBindingProcessor(StringValueResolver stringValueResolver) { - super(stringValueResolver); + super(stringValueResolver, AsyncGenericOperationBinding.class); } @Override diff --git a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/jms/scanners/operations/JmsOperationBindingProcessor.java b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/jms/scanners/operations/JmsOperationBindingProcessor.java index a0a7492fb..62a3b4b28 100644 --- a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/jms/scanners/operations/JmsOperationBindingProcessor.java +++ b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/jms/scanners/operations/JmsOperationBindingProcessor.java @@ -9,7 +9,7 @@ public class JmsOperationBindingProcessor extends AbstractOperationBindingProcessor { public JmsOperationBindingProcessor(StringValueResolver stringValueResolver) { - super(stringValueResolver); + super(stringValueResolver, JmsAsyncOperationBinding.class); } @Override diff --git a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/kafka/scanners/channels/KafkaChannelBindingProcessor.java b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/kafka/scanners/channels/KafkaChannelBindingProcessor.java index 9ad268bca..e471a01ea 100644 --- a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/kafka/scanners/channels/KafkaChannelBindingProcessor.java +++ b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/kafka/scanners/channels/KafkaChannelBindingProcessor.java @@ -18,7 +18,7 @@ public class KafkaChannelBindingProcessor extends AbstractChannelBindingProcesso KafkaChannelTopicConfiguration.builder().build(); public KafkaChannelBindingProcessor(StringValueResolver stringValueResolver) { - super(stringValueResolver); + super(stringValueResolver, KafkaAsyncChannelBinding.class); } protected ProcessedChannelBinding mapToChannelBinding(KafkaAsyncChannelBinding bindingAnnotation) { diff --git a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/kafka/scanners/operations/KafkaOperationBindingProcessor.java b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/kafka/scanners/operations/KafkaOperationBindingProcessor.java index 6b5e9d488..00582fee0 100644 --- a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/kafka/scanners/operations/KafkaOperationBindingProcessor.java +++ b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/kafka/scanners/operations/KafkaOperationBindingProcessor.java @@ -16,7 +16,7 @@ public class KafkaOperationBindingProcessor extends AbstractOperationBindingProcessor { public KafkaOperationBindingProcessor(StringValueResolver stringValueResolver) { - super(stringValueResolver); + super(stringValueResolver, KafkaAsyncOperationBinding.class); } @Override diff --git a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/sns/scanners/operations/SnsOperationBindingProcessor.java b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/sns/scanners/operations/SnsOperationBindingProcessor.java index 68b9d171f..ab3c92a23 100644 --- a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/sns/scanners/operations/SnsOperationBindingProcessor.java +++ b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/sns/scanners/operations/SnsOperationBindingProcessor.java @@ -15,7 +15,7 @@ public class SnsOperationBindingProcessor extends AbstractOperationBindingProcessor { public SnsOperationBindingProcessor(StringValueResolver stringValueResolver) { - super(stringValueResolver); + super(stringValueResolver, SnsAsyncOperationBinding.class); } @Override diff --git a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/sqs/scanners/operations/SqsOperationBindingProcessor.java b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/sqs/scanners/operations/SqsOperationBindingProcessor.java index 0e2ea11c8..babef3e1f 100644 --- a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/sqs/scanners/operations/SqsOperationBindingProcessor.java +++ b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/sqs/scanners/operations/SqsOperationBindingProcessor.java @@ -15,7 +15,7 @@ public class SqsOperationBindingProcessor extends AbstractOperationBindingProcessor { public SqsOperationBindingProcessor(StringValueResolver stringValueResolver) { - super(stringValueResolver); + super(stringValueResolver, SqsAsyncOperationBinding.class); } @Override diff --git a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/stomp/scanners/operations/StompOperationBindingProcessor.java b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/stomp/scanners/operations/StompOperationBindingProcessor.java index 4ab6b8a98..3136f1f40 100644 --- a/springwolf-bindings/src/main/java/io/github/springwolf/bindings/stomp/scanners/operations/StompOperationBindingProcessor.java +++ b/springwolf-bindings/src/main/java/io/github/springwolf/bindings/stomp/scanners/operations/StompOperationBindingProcessor.java @@ -10,7 +10,7 @@ public class StompOperationBindingProcessor extends AbstractOperationBindingProcessor { public StompOperationBindingProcessor(StringValueResolver stringValueResolver) { - super(stringValueResolver); + super(stringValueResolver, StompAsyncOperationBinding.class); } @Override diff --git a/springwolf-bindings/src/test/java/io/github/springwolf/bindings/generic/scanners/operations/AsyncGenericOperationBindingProcessorTest.java b/springwolf-bindings/src/test/java/io/github/springwolf/bindings/generic/scanners/operations/AsyncGenericOperationBindingProcessorTest.java index c33b6e6d2..6f06789e0 100644 --- a/springwolf-bindings/src/test/java/io/github/springwolf/bindings/generic/scanners/operations/AsyncGenericOperationBindingProcessorTest.java +++ b/springwolf-bindings/src/test/java/io/github/springwolf/bindings/generic/scanners/operations/AsyncGenericOperationBindingProcessorTest.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.bindings.generic.scanners.operations; -import io.github.springwolf.bindings.generic.annotation.AsyncGenericOperationBinding; +import io.github.springwolf.bindings.generic.annotations.AsyncGenericOperationBinding; import io.github.springwolf.core.asyncapi.scanners.bindings.operations.ProcessedOperationBinding; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/SpringwolfInitApplicationListener.java b/springwolf-core/src/main/java/io/github/springwolf/core/SpringwolfInitApplicationListener.java index db68ab950..10f5a3492 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/SpringwolfInitApplicationListener.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/SpringwolfInitApplicationListener.java @@ -6,6 +6,7 @@ import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties.InitMode; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.jspecify.annotations.NonNull; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; @@ -22,7 +23,7 @@ public class SpringwolfInitApplicationListener implements ApplicationListener getForGroupName(String groupName) { initAsyncAPI(); } - if (asyncAPIResult.groupedApi != null) { - return Optional.ofNullable(asyncAPIResult.groupedApi.get(groupName)); + Map groupedApi = asyncAPIResult.groupedApi; + if (groupedApi != null) { + return Optional.ofNullable(groupedApi.get(groupName)); } else { throw new RuntimeException("Error occurred during creation of AsyncAPI", asyncAPIResult.exception); } @@ -117,7 +118,7 @@ protected synchronized void initAsyncAPI() { /** * checks whether asyncApi has internally already been initialized or not. * - * @return true if asyncApi has not allready been created and initialized. + * @return true if asyncApi has not already been created and initialized. */ public boolean isNotInitialized() { return this.asyncAPIResult == null; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/channels/DefaultChannelsService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/channels/DefaultChannelsService.java index ac062287c..2c45640e1 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/channels/DefaultChannelsService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/channels/DefaultChannelsService.java @@ -31,8 +31,7 @@ public Map findChannels() { for (ChannelsScanner scanner : channelsScanners) { try { - Map channels = scanner.scan(); - foundChannelItems.addAll(channels.values()); + foundChannelItems.addAll(scanner.scan()); } catch (Exception e) { log.warn("An error was encountered during channel scanning with {}: {}", scanner, e.getMessage(), e); } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/ComponentsService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/ComponentsService.java index f58b2c22c..261eb4141 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/ComponentsService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/ComponentsService.java @@ -2,21 +2,12 @@ package io.github.springwolf.core.asyncapi.components; import io.github.springwolf.asyncapi.v3.model.channel.message.Message; -import io.github.springwolf.asyncapi.v3.model.channel.message.MessageObject; -import io.github.springwolf.asyncapi.v3.model.channel.message.MessageReference; import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; -import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; -import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; -import jakarta.annotation.Nullable; -import java.lang.reflect.Type; import java.util.Map; /** - * ComponentsService provides services to resolve schemas or schema names from given types. - * Additionally, this is a registry for all schemas and messages which are detected during the - * scan process. Theses collected schemas and messages will provide to the content of the 'components' block - * in the resulting AsyncAPI object. + * Provides the schemas and messages to include in the AsyncAPI components block. */ public interface ComponentsService { @@ -27,52 +18,10 @@ public interface ComponentsService { */ Map getSchemas(); - /** - * Resolves a schema for the given type and contentType. Registers this schema and all - * resolved schemas which a referenced by the root schema with this {@link ComponentsService}. - * - * @param type Type to resolve a schema from - * @param contentType Runtime ContentType of Schema - * @return a {@link SchemaReference} referencing the root schema, or null if no schema could be resolved. - */ - @Nullable - ComponentSchema resolvePayloadSchema(Type type, String contentType); - - /** - * registers the given schema with this {@link ComponentsService} - * @param schemaWithoutRef the schema to register, typically a header schema - * @return the title attribute of the given schema - */ - String registerSchema(SchemaObject schemaWithoutRef); - /** * Provides a map of all registered messages. * * @return the registered messages */ Map getMessages(); - - /** - * registers the given message with this {@link ComponentsService} - * - * @param message the message to register - * @return a {@link MessageReference} referencing the given message - */ - MessageReference registerMessage(MessageObject message); - - /** - * Provides a schema name for the given type. The result is either the full-qualified classname or - * the simple classname of the given type - which depends on {@link io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties#isUseFqn()}. - * - * @param type Type to generate a schema name from - * @return the resulting schema name - */ - String getSchemaName(Type type); - - /** - * Provides a simple schema name for the given type, which is the simple classname of the type. - * @param type Type to generate a simple schema name from - * @return the resulting schema name - */ - String getSimpleSchemaName(Type type); } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/DefaultComponentsService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/DefaultComponentsService.java index 37cad2d5d..111b3db53 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/DefaultComponentsService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/DefaultComponentsService.java @@ -2,127 +2,25 @@ package io.github.springwolf.core.asyncapi.components; import io.github.springwolf.asyncapi.v3.model.channel.message.Message; -import io.github.springwolf.asyncapi.v3.model.channel.message.MessageObject; -import io.github.springwolf.asyncapi.v3.model.channel.message.MessageReference; import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; -import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; +import io.github.springwolf.core.asyncapi.messages.MessagesService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; +import lombok.RequiredArgsConstructor; -import java.lang.reflect.Type; -import java.util.HashMap; import java.util.Map; -/** - * Default implementation of {@link ComponentsService} interface. It provides services to resolve schemas or schema - * names from given types. Additionally, this is a registry for all schemas and messages which are detected during the - * scan process. Theses collected schemas and messages will provide to the content of the 'components' block - * in the resulting AsyncAPI object. - */ -@Slf4j -@AllArgsConstructor +@RequiredArgsConstructor public class DefaultComponentsService implements ComponentsService { + private final SchemasService schemasService; + private final MessagesService messagesService; - private final SwaggerSchemaService schemaService; - - /** - * maps a schema name (key) to a detected corresponding {@link ComponentSchema}. - */ - private final Map schemas = new HashMap<>(); - - private final Map messages = new HashMap<>(); - - /** - * Provides a map of all registered schemas. - * - * @return the registered payload and header schemas - */ @Override public Map getSchemas() { - return schemas; - } - - /** - * Resolves a schema for the given type and contentType. Registers this schema and all - * resolved schemas which a referenced by the root schema with this {@link ComponentsService}. - * - * @param type Type to resolve a schema from - * @param contentType Runtime ContentType of Schema - * @return the root schema for the given type - */ - @Override - public ComponentSchema resolvePayloadSchema(Type type, String contentType) { - SwaggerSchemaService.ExtractedSchemas payload = schemaService.resolveSchema(type, contentType); - payload.referencedSchemas().forEach(schemas::putIfAbsent); - return payload.rootSchema(); - } - - /** - * registers the given schema with this {@link ComponentsService}. - *

NOTE

- * Use only with schemas with max. one level of properties. Providing {@link SchemaObject}s with deep - * property hierarchy will result in a corrupted result. - *
- * A typical usecase for this method is registering of header schemas, which have typically a simple structure. - * - * @param schemaWithoutRef the schema to register, typically a header schema - * @return the title attribute of the given schema - */ - @Override - public String registerSchema(SchemaObject schemaWithoutRef) { - log.trace("Registering schema for {}", schemaWithoutRef.getTitle()); - - ComponentSchema processedSchema = schemaService.postProcessSchemaWithoutRef(schemaWithoutRef); - this.schemas.putIfAbsent(schemaWithoutRef.getTitle(), processedSchema); - - return schemaWithoutRef.getTitle(); + return schemasService.getSchemas(); } - /** - * Provides a map of all registered messages. - * - * @return the registered messages - */ @Override public Map getMessages() { - return this.messages; - } - - /** - * registers the given message with this {@link ComponentsService} - * - * @param message the message to register - * @return a {@link MessageReference} referencing the given message - */ - @Override - public MessageReference registerMessage(MessageObject message) { - log.trace("Registering message for {}", message.getMessageId()); - - messages.putIfAbsent(message.getMessageId(), message); - - return MessageReference.toComponentMessage(message); - } - - /** - * Provides a schema name for the given type. The result is either the full-qualified classname or - * the simple classname of the given type - which depends on {@link io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties#isUseFqn()}. - * - * @param type Type to generate a schema name from - * @return the resulting schema name - */ - @Override - public String getSchemaName(Type type) { - return schemaService.getNameFromType(type); - } - - /** - * Provides a simple schema name for the given type, which is the simple classname of the type. - * @param type Type to generate a simple schema name from - * @return the resulting schema name - */ - @Override - public String getSimpleSchemaName(Type type) { - return schemaService.getSimpleNameFromType(type); + return messagesService.getMessages(); } } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/postprocessors/ExampleGeneratorPostProcessor.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/postprocessors/ExampleGeneratorPostProcessor.java deleted file mode 100644 index dd10acbd1..000000000 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/postprocessors/ExampleGeneratorPostProcessor.java +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.postprocessors; - -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.SchemaWalker; -import io.swagger.v3.oas.models.media.Schema; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; - -import java.util.Map; -import java.util.Optional; - -@RequiredArgsConstructor -@Slf4j -public class ExampleGeneratorPostProcessor implements SchemasPostProcessor { - - private final SchemaWalkerProvider schemaWalkerProvider; - - @Override - public void process(Schema schema, Map definitions, String contentType) { - if (schema.getExample() == null) { - log.trace("Generate example for {}", schema.getName()); - - Optional schemaWalkerOptional = schemaWalkerProvider.generatorFor(contentType); - if (schemaWalkerOptional.isPresent()) { - Object example = schemaWalkerOptional.get().fromSchema(schema, definitions); - schema.setExample(example); - } else { - log.debug("No matching SchemaWalker for contentType {} for example {}", contentType, schema.getName()); - } - } - } -} diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/messages/DefaultMessagesService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/messages/DefaultMessagesService.java new file mode 100644 index 000000000..de1ada94a --- /dev/null +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/messages/DefaultMessagesService.java @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: Apache-2.0 +package io.github.springwolf.core.asyncapi.messages; + +import io.github.springwolf.asyncapi.v3.model.channel.message.Message; +import io.github.springwolf.asyncapi.v3.model.channel.message.MessageObject; +import io.github.springwolf.asyncapi.v3.model.channel.message.MessageReference; +import lombok.extern.slf4j.Slf4j; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +public class DefaultMessagesService implements MessagesService { + private final Map messages = new HashMap<>(); + + @Override + public Map getMessages() { + return messages; + } + + @Override + public MessageReference registerMessage(MessageObject message) { + log.trace("Registering message for {}", message.getMessageId()); + messages.putIfAbsent(message.getMessageId(), message); + return MessageReference.toComponentMessage(message); + } +} diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/messages/MessagesService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/messages/MessagesService.java new file mode 100644 index 000000000..c5a18c61e --- /dev/null +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/messages/MessagesService.java @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +package io.github.springwolf.core.asyncapi.messages; + +import io.github.springwolf.asyncapi.v3.model.channel.message.Message; +import io.github.springwolf.asyncapi.v3.model.channel.message.MessageObject; +import io.github.springwolf.asyncapi.v3.model.channel.message.MessageReference; + +import java.util.Map; + +public interface MessagesService { + Map getMessages(); + + MessageReference registerMessage(MessageObject message); +} diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/operations/DefaultOperationsService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/operations/DefaultOperationsService.java index 8b3c728cb..327d41b5c 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/operations/DefaultOperationsService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/operations/DefaultOperationsService.java @@ -31,8 +31,7 @@ public Map findOperations() { for (OperationsScanner scanner : operationScanners) { try { - Map channels = scanner.scan(); - foundOperations.addAll(channels.values()); + foundOperations.addAll(scanner.scan()); } catch (Exception e) { log.warn("An error was encountered during operation scanning with {}: {}", scanner, e.getMessage(), e); } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/ChannelsScanner.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/ChannelsScanner.java index e591c3622..aa3ef75c3 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/ChannelsScanner.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/ChannelsScanner.java @@ -3,14 +3,12 @@ import io.github.springwolf.asyncapi.v3.model.channel.ChannelObject; -import java.util.Map; +import java.util.List; public interface ChannelsScanner { /** - * @return A mapping of channel names to their respective channel object for a given protocol. - *

- * Maintainer note: Use {@link ChannelObject#getChannelId()} as the key for the map. + * @return The channel objects found for a given protocol. */ - Map scan(); + List scan(); } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/OperationsScanner.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/OperationsScanner.java index 25f840817..6283947ca 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/OperationsScanner.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/OperationsScanner.java @@ -3,12 +3,12 @@ import io.github.springwolf.asyncapi.v3.model.operation.Operation; -import java.util.Map; +import java.util.List; public interface OperationsScanner { /** - * @return A mapping of operation names to their respective operation object for a given protocol. + * @return The operations found for a given protocol. */ - Map scan(); + List scan(); } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/BindingContext.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/BindingContext.java index 32c425c24..fa289326f 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/BindingContext.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/BindingContext.java @@ -15,6 +15,10 @@ public record BindingContext( T annotation, Class annotatedClass, @Nullable Method annotatedMethod) { + public static BindingContext of(U annotation) { + return new BindingContext<>(annotation, null, null); + } + public static BindingContext ofAnnotatedClass(Class annotatedClass, U annotation) { return new BindingContext<>(annotation, annotatedClass, null); } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/BindingFactory.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/BindingFactory.java index 58c51f58a..f50855221 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/BindingFactory.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/BindingFactory.java @@ -11,54 +11,16 @@ import java.util.Map; public interface BindingFactory { - /** - * @deprecated use {@link #getChannelId(BindingContext)} instead - */ - @Deprecated - default String getChannelId(T annotation) { - return ReferenceUtil.toValidId(getChannelName(annotation)); - } - /** - * Same as {@link #getChannelId(Annotation)}, with access to the context in which the annotation was found. - *

- * Maintainer note: delegates to {@link #getChannelId(Annotation)} to stay compatible with existing implementations. - */ default String getChannelId(BindingContext bindingContext) { - return getChannelId(bindingContext.annotation()); + return ReferenceUtil.toValidId(getChannelName(bindingContext)); } - /** - * @deprecated use {@link #getChannelName(BindingContext)} instead - */ - @Deprecated - String getChannelName(T annotation); - - /** - * Same as {@link #getChannelName(Annotation)}, with access to the context in which the annotation was found. - *

- * Maintainer note: delegates to {@link #getChannelName(Annotation)} to stay compatible with existing implementations. - */ - default String getChannelName(BindingContext bindingContext) { - return getChannelName(bindingContext.annotation()); - } + String getChannelName(BindingContext bindingContext); - Map buildChannelBinding(T annotation); + Map buildChannelBinding(BindingContext bindingContext); - /** - * @deprecated use {@link #buildOperationBinding(BindingContext)} instead - */ - @Deprecated - Map buildOperationBinding(T annotation); - - /** - * Same as {@link #buildOperationBinding(Annotation)}, with access to the context in which the annotation was found. - *

- * Maintainer note: delegates to {@link #buildOperationBinding(Annotation)} to stay compatible with existing implementations. - */ - default Map buildOperationBinding(BindingContext bindingContext) { - return buildOperationBinding(bindingContext.annotation()); - } + Map buildOperationBinding(BindingContext bindingContext); - Map buildMessageBinding(T annotation, SchemaObject headerSchema); + Map buildMessageBinding(BindingContext bindingContext, SchemaObject headerSchema); } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/channels/AbstractChannelBindingProcessor.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/channels/AbstractChannelBindingProcessor.java index d19195777..96bbf4a12 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/channels/AbstractChannelBindingProcessor.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/channels/AbstractChannelBindingProcessor.java @@ -2,26 +2,27 @@ package io.github.springwolf.core.asyncapi.scanners.bindings.channels; import io.github.springwolf.core.asyncapi.annotations.AsyncChannelBinding; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; import org.springframework.util.StringValueResolver; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; -import java.lang.reflect.ParameterizedType; import java.util.Arrays; import java.util.Optional; import java.util.stream.Stream; @Slf4j -@RequiredArgsConstructor -public abstract class AbstractChannelBindingProcessor implements ChannelBindingProcessor { +public abstract class AbstractChannelBindingProcessor implements ChannelBindingProcessor { private final StringValueResolver stringValueResolver; + private final Class specificAnnotationClazz; - private final Class specificAnnotationClazz = - (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; + protected AbstractChannelBindingProcessor( + StringValueResolver stringValueResolver, Class specificAnnotationClazz) { + this.stringValueResolver = stringValueResolver; + this.specificAnnotationClazz = specificAnnotationClazz; + } @Override public Optional process(AnnotatedElement annotatedElement) { diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/operations/AbstractOperationBindingProcessor.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/operations/AbstractOperationBindingProcessor.java index ec2f77ac0..d5c04848b 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/operations/AbstractOperationBindingProcessor.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/bindings/operations/AbstractOperationBindingProcessor.java @@ -2,26 +2,27 @@ package io.github.springwolf.core.asyncapi.scanners.bindings.operations; import io.github.springwolf.core.asyncapi.annotations.AsyncOperationBinding; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; import org.springframework.util.StringValueResolver; import java.lang.annotation.Annotation; import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; import java.util.Arrays; import java.util.Optional; import java.util.stream.Stream; @Slf4j -@RequiredArgsConstructor -public abstract class AbstractOperationBindingProcessor implements OperationBindingProcessor { +public abstract class AbstractOperationBindingProcessor implements OperationBindingProcessor { private final StringValueResolver stringValueResolver; + private final Class specificAnnotationClazz; - private final Class specificAnnotationClazz = - (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; + protected AbstractOperationBindingProcessor( + StringValueResolver stringValueResolver, Class specificAnnotationClazz) { + this.stringValueResolver = stringValueResolver; + this.specificAnnotationClazz = specificAnnotationClazz; + } @Override public Optional process(Method method) { diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelMerger.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelMerger.java index 6f9811f6d..4f830d37d 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelMerger.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelMerger.java @@ -44,8 +44,10 @@ public static Map mergeChannels(List chann private static ChannelObject mergeChannel(ChannelObject channel, ChannelObject otherChannel) { ChannelObject mergedChannel = channel != null ? channel : otherChannel; - mergeMessages(channel, otherChannel, mergedChannel); - mergeBindings(channel, otherChannel, mergedChannel); + if (channel != null) { + mergeMessages(channel, otherChannel, mergedChannel); + mergeBindings(channel, otherChannel, mergedChannel); + } return mergedChannel; } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelsInClassScannerAdapter.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelsInClassScannerAdapter.java index 563373601..c357311b4 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelsInClassScannerAdapter.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelsInClassScannerAdapter.java @@ -8,7 +8,6 @@ import java.util.Collection; import java.util.List; -import java.util.Map; import java.util.Set; @RequiredArgsConstructor @@ -19,12 +18,10 @@ public class ChannelsInClassScannerAdapter implements ChannelsScanner { private final ChannelsInClassScanner channelsInClassScanner; @Override - public Map scan() { + public List scan() { Set> components = classScanner.scan(); - List channels = mapToChannels(components); - - return ChannelMerger.mergeChannels(channels); + return mapToChannels(components); } private List mapToChannels(Set> components) { diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/channel/SpringAnnotationChannelService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/channel/SpringAnnotationChannelService.java index d697a1a56..68eb94055 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/channel/SpringAnnotationChannelService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/channel/SpringAnnotationChannelService.java @@ -20,7 +20,7 @@ public class SpringAnnotationChannelService bindingFactory; public ChannelObject buildChannel(BindingContext bindingContext, Map messages) { - Map channelBinding = bindingFactory.buildChannelBinding(bindingContext.annotation()); + Map channelBinding = bindingFactory.buildChannelBinding(bindingContext); Map chBinding = channelBinding != null ? new HashMap<>(channelBinding) : null; String channelName = bindingFactory.getChannelName(bindingContext); return ChannelObject.builder() diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractor.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractor.java index 0130572b7..529734ec4 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractor.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractor.java @@ -5,7 +5,7 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaType; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.messaging.handler.annotation.Header; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/AsyncAnnotationMessageService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/AsyncAnnotationMessageService.java index 1662c8efd..a7f3f1643 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/AsyncAnnotationMessageService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/AsyncAnnotationMessageService.java @@ -9,12 +9,13 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; import io.github.springwolf.core.asyncapi.annotations.AsyncOperation; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.bindings.messages.MessageBindingProcessor; import io.github.springwolf.core.asyncapi.scanners.common.annotation.AsyncAnnotationUtil; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadAsyncOperationService; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; import io.github.springwolf.core.asyncapi.scanners.common.utils.TextUtils; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -29,7 +30,8 @@ public class AsyncAnnotationMessageService { private final PayloadAsyncOperationService payloadAsyncOperationService; - private final ComponentsService componentsService; + private final MessagesService messagesService; + private final SchemasService schemasService; private final List messageBindingProcessors; private final StringValueResolver stringValueResolver; @@ -37,7 +39,7 @@ public MessageObject buildMessage(AsyncOperation operationData, Method method) { PayloadSchemaObject payloadSchema = payloadAsyncOperationService.extractSchema(operationData, method); SchemaObject headerSchema = AsyncAnnotationUtil.getAsyncHeaders(operationData, stringValueResolver); - String headerSchemaName = this.componentsService.registerSchema(headerSchema); + String headerSchemaName = this.schemasService.registerSchema(headerSchema); Map messageBinding = AsyncAnnotationUtil.processMessageBindingFromAnnotation(method, messageBindingProcessors); @@ -58,7 +60,7 @@ public MessageObject buildMessage(AsyncOperation operationData, Method method) { AsyncAnnotationUtil.processAsyncMessageAnnotation(builder, operationData.message(), this.stringValueResolver); MessageObject message = builder.build(); - this.componentsService.registerMessage(message); + this.messagesService.registerMessage(message); return message; } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/SpringAnnotationMessageService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/SpringAnnotationMessageService.java index f06fc8e3d..f953401e4 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/SpringAnnotationMessageService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/SpringAnnotationMessageService.java @@ -8,11 +8,13 @@ import io.github.springwolf.asyncapi.v3.model.schema.MultiFormatSchema; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; +import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingFactory; import io.github.springwolf.core.asyncapi.scanners.common.headers.AsyncHeadersBuilder; import io.github.springwolf.core.asyncapi.scanners.common.headers.HeaderSchemaObjectMerger; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -25,15 +27,18 @@ public class SpringAnnotationMessageService private final BindingFactory bindingFactory; private final AsyncHeadersBuilder asyncHeadersBuilder; - private final ComponentsService componentsService; + private final MessagesService messagesService; + private final SchemasService schemasService; public MessageObject buildMessage( MethodAnnotation annotation, PayloadSchemaObject payloadSchema, SchemaObject headers) { SchemaObject headerSchema = asyncHeadersBuilder.buildHeaders(payloadSchema); SchemaObject mergedHeaderSchema = HeaderSchemaObjectMerger.merge(headerSchema, headers); - String headerModelName = componentsService.registerSchema(mergedHeaderSchema); + String headerModelName = schemasService.registerSchema(mergedHeaderSchema); - Map messageBinding = bindingFactory.buildMessageBinding(annotation, mergedHeaderSchema); + BindingContext bindingContext = BindingContext.of(annotation); + Map messageBinding = + bindingFactory.buildMessageBinding(bindingContext, mergedHeaderSchema); MessagePayload payload = MessagePayload.of( MultiFormatSchema.builder().schema(payloadSchema.payload()).build()); @@ -48,7 +53,7 @@ public MessageObject buildMessage( .bindings(messageBinding) .build(); - this.componentsService.registerMessage(message); + this.messagesService.registerMessage(message); return message; } } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/SpringAnnotationMessagesService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/SpringAnnotationMessagesService.java index da6b1158a..08e706ce7 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/SpringAnnotationMessagesService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/message/SpringAnnotationMessagesService.java @@ -9,7 +9,7 @@ import io.github.springwolf.asyncapi.v3.model.schema.MultiFormatSchema; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingFactory; import io.github.springwolf.core.asyncapi.scanners.common.headers.AsyncHeadersBuilder; @@ -17,6 +17,7 @@ import io.github.springwolf.core.asyncapi.scanners.common.headers.HeaderSchemaObjectMerger; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadMethodService; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -37,7 +38,8 @@ public class SpringAnnotationMessagesService private final AsyncHeadersBuilder asyncHeadersBuilder; private final PayloadMethodService payloadMethodService; private final HeaderClassExtractor headerClassExtractor; - private final ComponentsService componentsService; + private final MessagesService messagesService; + private final SchemasService schemasService; public enum MessageType { CHANNEL, @@ -63,9 +65,11 @@ private MessageObject buildMessage(ClassAnnotation classAnnotation, Method metho SchemaObject headerSchema = asyncHeadersBuilder.buildHeaders(payloadSchema); SchemaObject headers = headerClassExtractor.extractHeader(method, payloadSchema); SchemaObject mergedHeaderSchema = HeaderSchemaObjectMerger.merge(headerSchema, headers); - String headerSchemaName = componentsService.registerSchema(mergedHeaderSchema); + String headerSchemaName = schemasService.registerSchema(mergedHeaderSchema); - Map messageBinding = bindingFactory.buildMessageBinding(classAnnotation, headerSchema); + BindingContext bindingContext = + BindingContext.ofAnnotatedMethod(method.getDeclaringClass(), method, classAnnotation); + Map messageBinding = bindingFactory.buildMessageBinding(bindingContext, headerSchema); MessagePayload payload = MessagePayload.of( MultiFormatSchema.builder().schema(payloadSchema.payload()).build()); @@ -80,7 +84,7 @@ private MessageObject buildMessage(ClassAnnotation classAnnotation, Method metho .bindings(messageBinding) .build(); - this.componentsService.registerMessage(message); + this.messagesService.registerMessage(message); return message; } } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/payload/internal/PayloadService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/payload/internal/PayloadService.java index 84b3b98a0..8f5040e40 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/payload/internal/PayloadService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/payload/internal/PayloadService.java @@ -4,8 +4,8 @@ import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaType; -import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -17,7 +17,7 @@ @Slf4j @RequiredArgsConstructor public class PayloadService { - private final ComponentsService componentsService; + private final SchemasService schemasService; private final SpringwolfConfigProperties properties; private static final String PAYLOAD_NOT_USED_KEY = "PayloadNotUsed"; @@ -39,24 +39,20 @@ public PayloadSchemaObject buildSchema(Type payloadType) { /** * creates a {@link PayloadSchemaObject} from the given type and content type. Registers the created schema objects - * with this {@link ComponentsService}. - * - * @param contentType - * @param payloadType - * @return + * with this {@link SchemasService}. */ public PayloadSchemaObject buildSchema(String contentType, Type payloadType) { - String schemaName = componentsService.getSchemaName(payloadType); - String simpleSchemaName = componentsService.getSimpleSchemaName(payloadType); + String schemaName = schemasService.getSchemaName(payloadType); + String simpleSchemaName = schemasService.getSimpleSchemaName(payloadType); - ComponentSchema schema = componentsService.resolvePayloadSchema(payloadType, contentType); + ComponentSchema schema = schemasService.registerType(payloadType, contentType); return new PayloadSchemaObject(schemaName, simpleSchemaName, schema); } public PayloadSchemaObject useUnusedPayload() { ComponentSchema schema = PAYLOAD_NOT_USED.schema(); if (schema != null && schema.getSchema() != null) { - this.componentsService.registerSchema(schema.getSchema()); + this.schemasService.registerSchema(schema.getSchema()); } return PAYLOAD_NOT_USED; } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/utils/StringValueResolverProxy.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/utils/StringValueResolverProxy.java index 00cfd5335..861ac5896 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/utils/StringValueResolverProxy.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/common/utils/StringValueResolverProxy.java @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.core.asyncapi.scanners.common.utils; +import org.jspecify.annotations.NonNull; import org.springframework.context.EmbeddedValueResolverAware; import org.springframework.util.StringValueResolver; @@ -11,12 +12,12 @@ public class StringValueResolverProxy implements StringValueResolver, EmbeddedVa private StringValueResolver delegate; @Override - public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) { + public void setEmbeddedValueResolver(@NonNull StringValueResolver stringValueResolver) { this.delegate = stringValueResolver; } @Override - public String resolveStringValue(String strVal) { + public String resolveStringValue(@NonNull String strVal) { return delegate.resolveStringValue(strVal); } } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationMerger.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationMerger.java index e0237b26e..67ad83fc7 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationMerger.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationMerger.java @@ -46,10 +46,12 @@ public static Map mergeOperations(List operations) private static Operation mergeOperation(Operation operation, Operation otherOperation) { Operation mergedOperation = operation != null ? operation : otherOperation; - List mergedMessages = - mergeMessageReferences(operation.getMessages(), otherOperation.getMessages()); - if (!mergedMessages.isEmpty()) { - mergedOperation.setMessages(mergedMessages); + if (operation != null) { + List mergedMessages = + mergeMessageReferences(operation.getMessages(), otherOperation.getMessages()); + if (!mergedMessages.isEmpty()) { + mergedOperation.setMessages(mergedMessages); + } } return mergedOperation; } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationsInClassScannerAdapter.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationsInClassScannerAdapter.java index 26cad6e95..abd1b9bfd 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationsInClassScannerAdapter.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationsInClassScannerAdapter.java @@ -7,7 +7,6 @@ import lombok.RequiredArgsConstructor; import java.util.List; -import java.util.Map; import java.util.Set; @RequiredArgsConstructor @@ -18,12 +17,10 @@ public class OperationsInClassScannerAdapter implements OperationsScanner { private final OperationsInClassScanner classProcessor; @Override - public Map scan() { + public List scan() { Set> components = classScanner.scan(); - List operations = mapToOperations(components); - - return OperationMerger.mergeOperations(operations); + return mapToOperations(components); } private List mapToOperations(Set> components) { diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/DefaultSchemasService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/DefaultSchemasService.java new file mode 100644 index 000000000..3fff9059a --- /dev/null +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/DefaultSchemasService.java @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +package io.github.springwolf.core.asyncapi.schemas; + +import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; +import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@RequiredArgsConstructor +public class DefaultSchemasService implements SchemasService { + private final SwaggerSchemaService schemaService; + private final Map schemas = new HashMap<>(); + + @Override + public Map getSchemas() { + return schemas; + } + + @Override + public ComponentSchema registerType(Type type, String contentType) { + SwaggerSchemaService.ExtractedSchemas payload = schemaService.resolveSchema(type, contentType); + payload.referencedSchemas().forEach(schemas::putIfAbsent); + return payload.rootSchema(); + } + + @Override + public String registerSchema(SchemaObject schemaWithoutRef) { + log.trace("Registering schema for {}", schemaWithoutRef.getTitle()); + ComponentSchema processedSchema = schemaService.postProcessSchemaWithoutRef(schemaWithoutRef); + schemas.putIfAbsent(schemaWithoutRef.getTitle(), processedSchema); + return schemaWithoutRef.getTitle(); + } + + @Override + public String getSchemaName(Type type) { + return schemaService.getNameFromType(type); + } + + @Override + public String getSimpleSchemaName(Type type) { + return schemaService.getSimpleNameFromType(type); + } +} diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SchemasService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SchemasService.java new file mode 100644 index 000000000..7a9895506 --- /dev/null +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SchemasService.java @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 +package io.github.springwolf.core.asyncapi.schemas; + +import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; +import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; +import jakarta.annotation.Nullable; + +import java.lang.reflect.Type; +import java.util.Map; + +public interface SchemasService { + Map getSchemas(); + + @Nullable + ComponentSchema registerType(Type type, String contentType); + + String registerSchema(SchemaObject schemaWithoutRef); + + String getSchemaName(Type type); + + String getSimpleSchemaName(Type type); +} diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/ModelConvertersProvider.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/converters/ModelConvertersRegisterer.java similarity index 93% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/ModelConvertersProvider.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/converters/ModelConvertersRegisterer.java index e4ffc959d..377f9a703 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/ModelConvertersProvider.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/converters/ModelConvertersRegisterer.java @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.schemas; +package io.github.springwolf.core.asyncapi.schemas.converters; +import io.github.springwolf.core.asyncapi.schemas.schema.SpringwolfTypeNameResolver; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.core.converter.ModelConverter; import io.swagger.v3.core.converter.ModelConverters; @@ -18,7 +19,7 @@ * Provides fully prepared {@link io.swagger.v3.core.converter.ModelConverters} for openapi v3 and v3.1 * requirements. */ -public class ModelConvertersProvider { +public class ModelConvertersRegisterer { @Getter private final TypeNameResolver typeNameResolver; @@ -28,7 +29,7 @@ public class ModelConvertersProvider { @Getter private final ModelConverters modelConverters; - public ModelConvertersProvider( + public ModelConvertersRegisterer( SpringwolfConfigProperties springwolfConfigProperties, List externalModelConverters, List jacksonModules) { diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/converters/SchemaTitleModelConverter.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/converters/SchemaTitleModelConverter.java index 8eec7832f..6656e7aa6 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/converters/SchemaTitleModelConverter.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/converters/SchemaTitleModelConverter.java @@ -17,7 +17,7 @@ @Slf4j public class SchemaTitleModelConverter implements ModelConverter { @Override - public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator chain) { + public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator chain) { if (!chain.hasNext()) return null; Schema schema = chain.next().resolve(type, context, chain); diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SpringwolfTypeNameResolver.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/SpringwolfTypeNameResolver.java similarity index 87% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SpringwolfTypeNameResolver.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/SpringwolfTypeNameResolver.java index a4ad7f2d8..fdc9832cb 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SpringwolfTypeNameResolver.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/SpringwolfTypeNameResolver.java @@ -1,12 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.schemas; +package io.github.springwolf.core.asyncapi.schemas.schema; import io.swagger.v3.core.jackson.TypeNameResolver; /** * Subclass of {@link TypeNameResolver} with a public constructor to * create new instances of TypeNameResolvers. - * + *

* Avoids interference with other libraries usages of the TypeNameResolver */ public class SpringwolfTypeNameResolver extends TypeNameResolver { diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaMapper.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaMapper.java similarity index 81% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaMapper.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaMapper.java index 088ab3319..033c9e276 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaMapper.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaMapper.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.schemas; +package io.github.springwolf.core.asyncapi.schemas.schema; import io.github.springwolf.asyncapi.v3.model.ExternalDocumentation; import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; @@ -7,7 +7,7 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; import io.github.springwolf.asyncapi.v3.model.schema.SchemaType; -import io.github.springwolf.core.asyncapi.components.examples.formatter.ExampleFormatter; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.formatter.ExampleFormatter; import io.github.springwolf.core.configuration.properties.PayloadSchemaFormat; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.oas.models.media.ObjectSchema; @@ -15,6 +15,7 @@ import lombok.RequiredArgsConstructor; import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -29,12 +30,19 @@ public class SwaggerSchemaMapper { private final SpringwolfConfigProperties springwolfConfigProperties; - public Map mapSchemasMap(Map schemaMap) { + public Map mapSchemasMap(Map schemaMap) { return schemaMap.entrySet().stream() - .map(entry -> Map.entry(entry.getKey(), mapSchema(entry.getValue()))) + .map(entry -> Map.entry(entry.getKey(), mapSchema(requireSwaggerSchema(entry.getValue())))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } + private Schema requireSwaggerSchema(Object schema) { + if (schema instanceof Schema swaggerSchema) { + return swaggerSchema; + } + throw new IllegalArgumentException("Expected a Swagger Schema but got: " + schema); + } + /** * creates a {@link ComponentSchema} from the given Swagger schema. If the given Swagger schema represents a * Reference, the resulting {@link ComponentSchema} will contain a corresponding {@link SchemaReference} to the @@ -44,7 +52,7 @@ public Map mapSchemasMap(Map schemaMap) * @param swaggerSchema the Swagger schema to convert * @return ComponentSchema with either a {@link SchemaReference} or a {@link SchemaObject}. */ - public ComponentSchema mapSchemaOrRef(Schema swaggerSchema) { + public ComponentSchema mapSchemaOrRef(Schema swaggerSchema) { if (swaggerSchema.get$ref() != null) { return ComponentSchema.of(new SchemaReference(swaggerSchema.get$ref())); } @@ -59,11 +67,10 @@ public ComponentSchema mapSchemaOrRef(Schema swaggerSchema) { * as long as the child schemas are 'real' schemas and not schema references. So this method performs a deep conversion * of the entire Swagger schema. * - * @param * @param swaggerSchema the given Swagger schema instance * @return the resulting AsyncAPI SchemaObject */ - public ComponentSchema mapSchema(Schema swaggerSchema) { + public ComponentSchema mapSchema(Schema swaggerSchema) { PayloadSchemaFormat payloadSchemaFormat = springwolfConfigProperties.getDocket().getPayloadSchemaFormat(); return switch (payloadSchemaFormat) { @@ -74,10 +81,7 @@ public ComponentSchema mapSchema(Schema swaggerSchema) { } /** - * transforms the given Swagger schema to an AsyncApi schema. - * - * @param swaggerSchema - * @return + * transforms the given Swagger schema to an AsyncApi schema */ private SchemaObject mapSwaggerSchemaToAsyncApiSchema(Schema swaggerSchema) { @@ -99,9 +103,8 @@ private SchemaObject mapSwaggerSchemaToAsyncApiSchema(Schema swaggerSchema) { boolean isNullable = Boolean.TRUE.equals(swaggerSchema.getNullable()); assignType(swaggerSchema, builder, isNullable); - Map properties = swaggerSchema.getProperties(); - if (properties != null) { - Map propertiesMapped = properties.entrySet().stream() + if (swaggerSchema.getProperties() != null) { + Map propertiesMapped = swaggerSchema.getProperties().entrySet().stream() .map(entry -> Map.entry(entry.getKey(), mapSchemaOrRef(entry.getValue()))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); @@ -152,10 +155,11 @@ private SchemaObject mapSwaggerSchemaToAsyncApiSchema(Schema swaggerSchema) { builder.examples(List.of(ExampleFormatter.processExampleObject(example))); } - List examples = swaggerSchema.getExamples(); + List examples = swaggerSchema.getExamples(); if (examples != null && !examples.isEmpty()) { - List processedExamples = ((List) examples) - .stream().map(ExampleFormatter::processExampleObject).collect(Collectors.toList()); + List processedExamples = examples.stream() + .map(ExampleFormatter::processExampleObject) + .collect(Collectors.toList()); builder.examples(processedExamples); } @@ -170,31 +174,31 @@ private SchemaObject mapSwaggerSchemaToAsyncApiSchema(Schema swaggerSchema) { builder.discriminator(swaggerSchema.getDiscriminator().getPropertyName()); } - List allOf = swaggerSchema.getAllOf(); - if (allOf != null) { - builder.allOf(allOf.stream().map(this::mapSchemaOrRef).collect(Collectors.toList())); + if (swaggerSchema.getAllOf() != null) { + builder.allOf( + swaggerSchema.getAllOf().stream().map(this::mapSchemaOrRef).collect(Collectors.toList())); } - List oneOf = swaggerSchema.getOneOf(); - if (oneOf != null) { - builder.oneOf(oneOf.stream().map(this::mapSchemaOrRef).collect(Collectors.toList())); + if (swaggerSchema.getOneOf() != null) { + builder.oneOf( + swaggerSchema.getOneOf().stream().map(this::mapSchemaOrRef).collect(Collectors.toList())); } - List anyOf = swaggerSchema.getAnyOf(); - if (anyOf != null) { - builder.anyOf(anyOf.stream().map(this::mapSchemaOrRef).collect(Collectors.toList())); + if (swaggerSchema.getAnyOf() != null) { + builder.anyOf( + swaggerSchema.getAnyOf().stream().map(this::mapSchemaOrRef).collect(Collectors.toList())); } if (swaggerSchema.getConst() != null) { builder.constValue(swaggerSchema.getConst()); } - Schema not = swaggerSchema.getNot(); + Schema not = swaggerSchema.getNot(); if (not != null) { builder.not(mapSchemaOrRef(not)); } - Schema items = swaggerSchema.getItems(); + Schema items = swaggerSchema.getItems(); if (items != null && "array".equals(swaggerSchema.getType())) { builder.items(mapSchemaOrRef(items)); } @@ -206,7 +210,8 @@ private SchemaObject mapSwaggerSchemaToAsyncApiSchema(Schema swaggerSchema) { return builder.build(); } - private static void assignType(Schema swaggerSchema, SchemaObject.SchemaObjectBuilder builder, boolean isNullable) { + private static void assignType( + Schema swaggerSchema, SchemaObject.SchemaObjectBuilder builder, boolean isNullable) { Set schemaTypes = swaggerSchema.getTypes(); Set types = schemaTypes == null ? new HashSet<>() : new HashSet<>(schemaTypes); @@ -244,9 +249,6 @@ private static void assignType(Schema swaggerSchema, SchemaObject.SchemaObjectBu /** * expects an object representing a schema and tries to unwrap this schema, if it is a * ComponentSchema or MultiFormatSchema. The method works recursive on unwrapped Objects. - * - * @param schema - * @return */ private Object unwrapSchema(Object schema) { if (schema instanceof ComponentSchema componentSchema) { @@ -300,33 +302,34 @@ public Schema mapToSwagger(Object schema) { *

Note

* This method does not perform a 'deep' transformation, only the root attributes of asyncApiSchema * are mapped to the Swagger schema (best-effort). - * - * @param asyncApiSchema - * @return swagger Schema */ - private Schema mapSchemaObjectToSwagger(SchemaObject asyncApiSchema) { - Schema swaggerSchema = new ObjectSchema(); + private Schema mapSchemaObjectToSwagger(SchemaObject asyncApiSchema) { + Schema swaggerSchema = new ObjectSchema(); swaggerSchema.setName(asyncApiSchema.getTitle()); swaggerSchema.setTitle(asyncApiSchema.getTitle()); if (asyncApiSchema.getType() != null) { swaggerSchema.setType(asyncApiSchema.getType().stream() - .filter(type -> !type.equals(SchemaType.NULL)) + .filter(type -> !type.equals(SchemaType.NULL.getValue())) .findFirst() .orElse(null)); swaggerSchema.setTypes(asyncApiSchema.getType()); } swaggerSchema.setFormat(asyncApiSchema.getFormat()); swaggerSchema.setDescription(asyncApiSchema.getDescription()); - swaggerSchema.setExamples(asyncApiSchema.getExamples()); - swaggerSchema.setEnum(asyncApiSchema.getEnumValues()); + if (asyncApiSchema.getExamples() != null) { + swaggerSchema.setExamples(new ArrayList<>(asyncApiSchema.getExamples())); + } + if (asyncApiSchema.getEnumValues() != null) { + swaggerSchema.setEnum(new ArrayList<>(asyncApiSchema.getEnumValues())); + } swaggerSchema.setConst(asyncApiSchema.getConstValue()); if (asyncApiSchema.getProperties() != null) { - Map properties = asyncApiSchema.getProperties().entrySet().stream() - .map((property) -> Map.entry(property.getKey(), (Schema) mapToSwagger(property.getValue()))) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - swaggerSchema.setProperties(properties); + swaggerSchema.setProperties(new HashMap<>()); + asyncApiSchema + .getProperties() + .forEach((name, property) -> swaggerSchema.addProperty(name, mapToSwagger(property))); } return swaggerSchema; @@ -334,12 +337,9 @@ private Schema mapSchemaObjectToSwagger(SchemaObject asyncApiSchema) { /** * transforms the given asyncapi {@link SchemaReference} to a Swagger Schema Object. - * - * @param asyncApiSchemaReference - * @return */ - private Schema mapSchemaReferenceToSwagger(SchemaReference asyncApiSchemaReference) { - Schema swaggerSchema = new Schema(); + private Schema mapSchemaReferenceToSwagger(SchemaReference asyncApiSchemaReference) { + Schema swaggerSchema = new Schema<>(); swaggerSchema.set$ref(asyncApiSchemaReference.getRef()); return swaggerSchema; } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaService.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaService.java similarity index 84% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaService.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaService.java index 97a8cb9a1..4f6a5ca6b 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaService.java @@ -1,11 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.schemas; +package io.github.springwolf.core.asyncapi.schemas.schema; import io.github.springwolf.asyncapi.v3.model.ReferenceUtil; import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.core.asyncapi.annotations.AsyncApiPayload; -import io.github.springwolf.core.asyncapi.components.postprocessors.SchemasPostProcessor; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; +import io.github.springwolf.core.asyncapi.schemas.schema.postprocessors.SchemasPostProcessor; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.core.converter.AnnotatedType; import io.swagger.v3.core.converter.ModelConverters; @@ -37,7 +38,7 @@ public class SwaggerSchemaService { private final SpringwolfConfigProperties properties; private final List schemaPostProcessors; private final SwaggerSchemaMapper swaggerSchemaMapper; - private final ModelConvertersProvider modelConvertersProvider; + private final ModelConvertersRegisterer modelConvertersRegisterer; private final TypeNameResolver simpleNameTypeNameResolver = new SpringwolfTypeNameResolver(false); public record ExtractedSchemas(ComponentSchema rootSchema, Map referencedSchemas) {} @@ -52,15 +53,12 @@ public record ExtractedSchemas(ComponentSchema rootSchema, Map * A typical usecase for this method is postprocessing of header schemas, which have typically a simple structure. - * - * @param schemaWithoutRef - * @return */ public ComponentSchema postProcessSchemaWithoutRef(SchemaObject schemaWithoutRef) { - Schema headerSchema = swaggerSchemaMapper.mapToSwagger(schemaWithoutRef); + Schema headerSchema = swaggerSchemaMapper.mapToSwagger(schemaWithoutRef); // call postprocessors - Map newSchemasToProcess = Map.of(headerSchema.getName(), headerSchema); + Map> newSchemasToProcess = Map.of(headerSchema.getName(), headerSchema); postProcessSchemas(newSchemasToProcess, new HashMap<>(newSchemasToProcess), DEFAULT_CONTENT_TYPE); // convert Swagger schema back to an AsyncAPI SchemaObject @@ -73,18 +71,14 @@ public ExtractedSchemas postProcessSimpleSchema(Class type) { /** * creates a {@link ExtractedSchemas} from the given type. The resulting ExtractedSchemas will contain the root - * schema (which is always a schema ref) and a List of conrecte schemas referenced from the root schema. - * - * @param type - * @param contentType - * @return + * schema (which is always a schema ref) and a List of concrete schemas referenced from the root schema. */ public ExtractedSchemas resolveSchema(Type type, String contentType) { String actualContentType = StringUtils.isBlank(contentType) ? properties.getDocket().getDefaultContentType() : contentType; // use swagger to resolve type to a swagger ResolvedSchema Object. - ModelConverters converterToUse = modelConvertersProvider.getModelConverters(); + ModelConverters converterToUse = modelConvertersRegisterer.getModelConverters(); ResolvedSchema resolvedSchema = converterToUse.resolveAsResolvedSchema(new AnnotatedType(type).resolveAsRef(true)); @@ -95,11 +89,12 @@ public ExtractedSchemas resolveSchema(Type type, String contentType) { ComponentSchema stringComponentSchema = swaggerSchemaMapper.mapSchema(stringPropertySchema); return new ExtractedSchemas(stringComponentSchema, Map.of()); } else { - Map newSchemasToProcess = new LinkedHashMap<>(resolvedSchema.referencedSchemas); + Map> newSchemasToProcess = new LinkedHashMap<>(); + resolvedSchema.referencedSchemas.forEach(newSchemasToProcess::put); newSchemasToProcess.putIfAbsent(getNameFromType(type), resolvedSchema.schema); preProcessSchemas(resolvedSchema.schema, newSchemasToProcess, type); - HashMap processedSchemas = new HashMap<>(newSchemasToProcess); + HashMap> processedSchemas = new HashMap<>(newSchemasToProcess); postProcessSchemas(newSchemasToProcess, processedSchemas, actualContentType); return createExtractedSchemas(resolvedSchema.schema, processedSchemas); @@ -111,23 +106,22 @@ public ExtractedSchemas resolveSchema(Type type, String contentType) { * * @param rootSchema Swagger root schema * @param referencedSchemas all referenced swagger schemas - * @return */ - private ExtractedSchemas createExtractedSchemas(Schema rootSchema, Map referencedSchemas) { + private ExtractedSchemas createExtractedSchemas(Schema rootSchema, Map> referencedSchemas) { ComponentSchema rootComponentSchema = swaggerSchemaMapper.mapSchemaOrRef(rootSchema); Map referencedComponentSchemas = swaggerSchemaMapper.mapSchemasMap(referencedSchemas); return new ExtractedSchemas(rootComponentSchema, referencedComponentSchemas); } - private void preProcessSchemas(Schema payloadSchema, Map schemas, Type type) { + private void preProcessSchemas(Schema payloadSchema, Map> schemas, Type type) { removeEmptySchemas(schemas); processCommonModelConverters(payloadSchema, schemas); processAsyncApiPayloadAnnotation(schemas, type); processSchemaAnnotation(payloadSchema, type); } - private void removeEmptySchemas(Map schemas) { + private void removeEmptySchemas(Map> schemas) { schemas.entrySet().stream().toList().forEach(e -> { if (e.getValue().getType() == null && e.getValue().getTypes() == null @@ -146,7 +140,7 @@ private void removeEmptySchemas(Map schemas) { *

* This method will remove the native and puts the target, converted schema in place. */ - private void processCommonModelConverters(Schema payloadSchema, Map schemas) { + private void processCommonModelConverters(Schema payloadSchema, Map> schemas) { schemas.values().stream() .filter(schema -> schema.getType() == null) .filter(schema -> schema.get$ref() != null) @@ -166,7 +160,7 @@ private void processCommonModelConverters(Schema payloadSchema, Map schema, String targetSchemaName, String sourceSchemaName) { if (schema != null && schema.get$ref() != null) { String refTypeName = ReferenceUtil.getLastSegment(schema.get$ref()); if (refTypeName.equals(sourceSchemaName)) { @@ -175,7 +169,7 @@ private void updatePayloadSchemaRef(Schema schema, String targetSchemaName, Stri } } - private void processSchemaAnnotation(Schema payloadSchema, Type type) { + private void processSchemaAnnotation(Schema payloadSchema, Type type) { JavaType javaType = Json.mapper().constructType(type); Class clazz = javaType.getRawClass(); if (payloadSchema != null) { @@ -186,7 +180,7 @@ private void processSchemaAnnotation(Schema payloadSchema, Type type) { } } - private void processAsyncApiPayloadAnnotation(Map schemas, Type type) { + private void processAsyncApiPayloadAnnotation(Map> schemas, Type type) { JavaType javaType = Json.mapper().constructType(type); Class clazz = javaType.getRawClass(); List withPayloadAnnotatedFields = Arrays.stream(clazz.getDeclaredFields()) @@ -216,7 +210,7 @@ public String getNameFromType(Type type) { return primitiveType.getKeyClass().getName(); } JavaType javaType = Json.mapper().constructType(type); - return modelConvertersProvider.getTypeNameResolver().nameForType(javaType); + return modelConvertersRegisterer.getTypeNameResolver().nameForType(javaType); } public String getSimpleNameFromType(Type type) { @@ -225,9 +219,9 @@ public String getSimpleNameFromType(Type type) { } private void postProcessSchemas( - Map schemasToProcess, Map schemas, String contentType) { + Map> schemasToProcess, Map> schemas, String contentType) { for (SchemasPostProcessor processor : schemaPostProcessors) { - for (Schema schema : schemasToProcess.values()) { + for (Schema schema : schemasToProcess.values()) { if (!schemas.containsValue(schema)) { // If the post-processor removed the schema, we can skip it continue; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/SchemaWalkerProvider.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/SchemaWalkerProvider.java similarity index 59% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/SchemaWalkerProvider.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/SchemaWalkerProvider.java index 2aec306d1..6135c68bb 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/SchemaWalkerProvider.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/SchemaWalkerProvider.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples; +package io.github.springwolf.core.asyncapi.schemas.schema.examples; -import io.github.springwolf.core.asyncapi.components.examples.walkers.SchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.SchemaWalker; import lombok.RequiredArgsConstructor; import java.util.List; @@ -13,9 +13,9 @@ @RequiredArgsConstructor public class SchemaWalkerProvider { - private final List schemaWalkers; + private final List> schemaWalkers; - public Optional generatorFor(String contentType) { + public Optional> generatorFor(String contentType) { return schemaWalkers.stream() .filter(walker -> walker.canHandle(contentType)) .findFirst(); diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/formatter/ExampleFormatter.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/formatter/ExampleFormatter.java similarity index 90% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/formatter/ExampleFormatter.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/formatter/ExampleFormatter.java index ac32e493d..6c5b9aaee 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/formatter/ExampleFormatter.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/formatter/ExampleFormatter.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.formatter; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.formatter; import java.text.SimpleDateFormat; import java.time.OffsetDateTime; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalker.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalker.java similarity index 78% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalker.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalker.java index a5c41e33d..7c5bcb1b8 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalker.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalker.java @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers; import io.github.springwolf.asyncapi.v3.model.ReferenceUtil; -import io.github.springwolf.core.asyncapi.components.examples.formatter.ExampleFormatter; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.formatter.ExampleFormatter; import io.swagger.v3.oas.models.media.MapSchema; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; @@ -11,7 +11,9 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.util.CollectionUtils; +import java.util.ArrayList; import java.util.Comparator; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -53,7 +55,7 @@ public boolean canHandle(String contentType) { } @Override - public R fromSchema(Schema schema, Map definitions) { + public R fromSchema(Schema schema, Map definitions) { exampleValueGenerator.initialize(); Optional schemaName = exampleValueGenerator.lookupSchemaName(schema); @@ -70,7 +72,7 @@ public R fromSchema(Schema schema, Map definitions) { } private Optional buildExample( - Optional name, Schema schema, Map definitions, Set visited) { + Optional name, Schema schema, Map definitions, Set> visited) { log.trace("Building example for schema {}", schema); Optional exampleValue = getExampleFromSchemaAnnotation(name, schema); @@ -87,13 +89,13 @@ private Optional buildExample( return example; } - private Optional getExampleFromSchemaAnnotation(Optional fieldName, Schema schema) { + private Optional getExampleFromSchemaAnnotation(Optional fieldName, Schema schema) { return getExampleValueFromSchemaAnnotation(fieldName, schema, schema.getExample()) .or(() -> getExampleValueFromSchemaAnnotation(fieldName, schema, schema.getDefault())); } private Optional getExampleValueFromSchemaAnnotation( - Optional fieldName, Schema schema, Object exampleValue) { + Optional fieldName, Schema schema, Object exampleValue) { // schema is a map of properties from a nested object, whose example cannot be inferred if (exampleValue == null) { return Optional.empty(); @@ -154,7 +156,7 @@ private Optional getExampleValueFromSchemaAnnotation( * The caller must ensure that the schema has not been visited before to avoid infinite recursion */ private Optional buildExampleFromUnvisitedSchema( - Optional name, Schema schema, Map definitions, Set visited) { + Optional name, Schema schema, Map definitions, Set> visited) { Optional> resolvedSchema = resolveSchemaFromRef(schema, definitions); if (resolvedSchema.isPresent()) { return buildExample(name, resolvedSchema.get(), definitions, visited); @@ -187,8 +189,8 @@ private Optional buildExampleFromUnvisitedSchema( }; } - private Optional buildArrayExample(Schema schema, Map definitions, Set visited) { - Schema arrayItemSchema = + private Optional buildArrayExample(Schema schema, Map definitions, Set> visited) { + Schema arrayItemSchema = resolveSchemaFromRef(schema.getItems(), definitions).orElse(schema.getItems()); Optional arrayName = exampleValueGenerator.lookupSchemaName(schema); @@ -201,7 +203,7 @@ private Optional buildArrayExample(Schema schema, Map definit .map(arrayItem -> exampleValueGenerator.createArrayExample(arrayName, arrayItem)); } - private Optional buildFromStringSchema(Schema schema) { + private Optional buildFromStringSchema(Schema schema) { String format = schema.getFormat(); if (format == null) { return exampleValueGenerator.createStringExample(DEFAULT_STRING_EXAMPLE, schema); @@ -219,7 +221,7 @@ private Optional buildFromStringSchema(Schema schema) { }; } - private Optional buildFromConstOrEnum(Schema schema) { + private Optional buildFromConstOrEnum(Schema schema) { Object constValue = schema.getConst(); if (constValue != null) { return exampleValueGenerator.createStringExample(constValue.toString(), schema); @@ -233,18 +235,15 @@ private Optional buildFromConstOrEnum(Schema schema) { return Optional.empty(); } - private String getFirstEnumValue(Schema schema) { - List enums = schema.getEnum(); + private String getFirstEnumValue(Schema schema) { + List enums = schema.getEnum(); if (enums != null) { - Optional firstEnumEntry = enums.stream().findFirst(); - if (firstEnumEntry.isPresent()) { - return firstEnumEntry.get(); - } + return enums.stream().findFirst().map(Object::toString).orElse(null); } return null; } - private Optional getFallbackExampleSchemaStringForFormat(String schemaFormat, Schema schema) { + private Optional getFallbackExampleSchemaStringForFormat(String schemaFormat, Schema schema) { return switch (schemaFormat) { case "int32", "int64" -> exampleValueGenerator.createStringExample(DEFAULT_INTEGER_EXAMPLE.toString(), schema); @@ -258,11 +257,10 @@ private Optional getFallbackExampleSchemaStringForFormat(String schemaFormat, * looks in schemas openapi-v3 'type' and openapi-v3.1 'types' fields to * find the best candidate to use as an example value. * - * @param schema * @return the type to use for example values, or null if no suitable type was found. */ @Nullable - String getTypeForExampleValue(Schema schema) { + String getTypeForExampleValue(Schema schema) { // if the single type field is present, it has precedence over the types field if (schema.getType() != null) { return schema.getType(); @@ -282,10 +280,10 @@ String getTypeForExampleValue(Schema schema) { } private Optional buildFromComposedSchema( - Optional name, Schema schema, Map definitions, Set visited) { - final List schemasAllOf = schema.getAllOf(); - final List schemasAnyOf = schema.getAnyOf(); - final List schemasOneOf = schema.getOneOf(); + Optional name, Schema schema, Map definitions, Set> visited) { + final List> schemasAllOf = schemasOf(schema.getAllOf()); + final List> schemasAnyOf = schemasOf(schema.getAnyOf()); + final List> schemasOneOf = schemasOf(schema.getOneOf()); if (!CollectionUtils.isEmpty(schemasAllOf)) { return buildFromObjectSchemaWithAllOf(name, schemasAllOf, definitions, visited); } else if (!CollectionUtils.isEmpty(schemasAnyOf)) { @@ -298,15 +296,15 @@ private Optional buildFromComposedSchema( } private Optional buildFromObjectSchema( - Optional name, Schema schema, Map definitions, Set visited) { + Optional name, Schema schema, Map definitions, Set> visited) { final Optional exampleValue; - final Map properties = schema.getProperties(); + final Map> properties = getProperties(schema); final Object additionalProperties = schema.getAdditionalProperties(); if (properties != null) { exampleValue = buildFromObjectSchemaWithProperties(name, properties, definitions, visited); - } else if (schema instanceof MapSchema && additionalProperties instanceof Schema schema1) { - exampleValue = buildMapExample(name, schema1, definitions, visited); + } else if (schema instanceof MapSchema && additionalProperties instanceof Schema additionalPropertySchema) { + exampleValue = buildMapExample(name, additionalPropertySchema, definitions, visited); } else { exampleValue = exampleValueGenerator.createEmptyObjectExample(); } @@ -315,9 +313,9 @@ private Optional buildFromObjectSchema( } private Optional buildMapExample( - Optional name, Schema additionalProperties, Map definitions, Set visited) { + Optional name, Schema additionalProperties, Map definitions, Set> visited) { T object = exampleValueGenerator.startObject(name); - Map mapProperties = Map.of(DEFAULT_MAP_KEY_EXAMPLE, additionalProperties); + Map> mapProperties = Map.of(DEFAULT_MAP_KEY_EXAMPLE, additionalProperties); exampleValueGenerator.addPropertyExamples( object, buildPropertyExampleListFromSchema(mapProperties, definitions, visited)); exampleValueGenerator.endObject(); @@ -327,9 +325,9 @@ private Optional buildMapExample( private Optional buildFromObjectSchemaWithProperties( Optional name, - Map properties, - Map definitions, - Set visited) { + Map> properties, + Map definitions, + Set> visited) { T object = exampleValueGenerator.startObject(name); exampleValueGenerator.addPropertyExamples( object, buildPropertyExampleListFromSchema(properties, definitions, visited)); @@ -339,7 +337,7 @@ private Optional buildFromObjectSchemaWithProperties( } private Optional buildFromObjectSchemaWithAllOf( - Optional name, List schemasAllOf, Map definitions, Set visited) { + Optional name, List> schemasAllOf, Map definitions, Set> visited) { T object = exampleValueGenerator.startObject(name); exampleValueGenerator.addPropertyExamples( object, buildPropertyExampleListFromSchemas(schemasAllOf, definitions, visited)); @@ -349,7 +347,7 @@ private Optional buildFromObjectSchemaWithAllOf( } private List> buildPropertyExampleListFromSchema( - Map properties, Map definitions, Set visited) { + Map> properties, Map definitions, Set> visited) { return properties.entrySet().stream() .map(propertySchema -> { // There can be instances where the schema has no name and only the property is named @@ -371,10 +369,10 @@ private List> buildPropertyExampleListFromSchema( } private List> buildPropertyExampleListFromSchemas( - List schemas, Map definitions, Set visited) { + List> schemas, Map definitions, Set> visited) { return schemas.stream() .map(schema -> resolveSchemaFromRef(schema, definitions).orElse(schema)) - .map(Schema::getProperties) + .map(DefaultSchemaWalker::getProperties) .filter(Objects::nonNull) .flatMap(propertiesFromSchema -> buildPropertyExampleListFromSchema(propertiesFromSchema, definitions, visited).stream()) @@ -382,17 +380,54 @@ private List> buildPropertyExampleListFromSchemas( .toList(); } - private Optional> resolveSchemaFromRef(Schema schema, Map definitions) { + private Optional> resolveSchemaFromRef(Schema schema, Map definitions) { String ref = schema.get$ref(); if (ref != null) { String schemaName = ReferenceUtil.getLastSegment(ref); - Schema resolvedSchema = definitions.get(schemaName); + Object resolvedSchema = definitions.get(schemaName); if (resolvedSchema == null) { throw new ExampleGeneratingException( "Missing schema (name = %s) during example generation".formatted(schemaName)); } - return Optional.of(resolvedSchema); + if (resolvedSchema instanceof Schema swaggerSchema) { + return Optional.of(swaggerSchema); + } + throw new ExampleGeneratingException( + "Invalid schema (name = %s) during example generation".formatted(schemaName)); } return Optional.empty(); } + + private static List> schemasOf(List schemas) { + if (schemas == null) { + return List.of(); + } + + List> typedSchemas = new ArrayList<>(schemas.size()); + for (Object schema : schemas) { + if (schema instanceof Schema swaggerSchema) { + typedSchemas.add(swaggerSchema); + } else { + throw new IllegalStateException("Expected a Swagger Schema in composed schema"); + } + } + return typedSchemas; + } + + private static Map> getProperties(Schema schema) { + Map properties = schema.getProperties(); + if (properties == null) { + return null; + } + + Map> typedProperties = new HashMap<>(); + properties.forEach((name, property) -> { + if (name instanceof String propertyName && property instanceof Schema propertySchema) { + typedProperties.put(propertyName, propertySchema); + } else { + throw new IllegalStateException("Expected a named Swagger Schema property"); + } + }); + return typedProperties; + } } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/ExampleValueGenerator.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/ExampleValueGenerator.java similarity index 64% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/ExampleValueGenerator.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/ExampleValueGenerator.java index df4fe3adf..37a80ff60 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/ExampleValueGenerator.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/ExampleValueGenerator.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers; import io.swagger.v3.oas.models.media.Schema; @@ -21,24 +21,24 @@ public interface ExampleValueGenerator { */ default void initialize() {} - Optional lookupSchemaName(Schema schema); + Optional lookupSchemaName(Schema schema); /** * @return The serializable representation of the example (object for json and yaml, string for others) */ - R prepareForSerialization(Schema name, T exampleObject); + R prepareForSerialization(Schema name, T exampleObject); - Optional createIntegerExample(Integer value, Schema schema); + Optional createIntegerExample(Integer value, Schema schema); - Optional createDoubleExample(Double value, Schema schema); + Optional createDoubleExample(Double value, Schema schema); - Optional createBooleanExample(Boolean value, Schema schema); + Optional createBooleanExample(Boolean value, Schema schema); Optional createEmptyObjectExample(); - Optional createStringExample(String value, Schema schema); + Optional createStringExample(String value, Schema schema); - Optional createEnumExample(String anEnumValue, Schema schema); + Optional createEnumExample(String anEnumValue, Schema schema); Optional createUnknownSchemaStringTypeExample(String schemaType); @@ -54,5 +54,5 @@ default void endObject() {} T createRaw(Object exampleValueString); - T getExampleOrNull(Optional fieldName, Schema schema, Object example); + T getExampleOrNull(Optional fieldName, Schema schema, Object example); } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/PropertyExample.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/PropertyExample.java similarity index 56% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/PropertyExample.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/PropertyExample.java index 0f314edbc..d2b6da3f1 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/PropertyExample.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/PropertyExample.java @@ -1,4 +1,4 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers; public record PropertyExample(String name, T example) {} diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/SchemaWalker.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/SchemaWalker.java similarity index 85% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/SchemaWalker.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/SchemaWalker.java index bd0c634a6..bee5c6f23 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/SchemaWalker.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/SchemaWalker.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers; import io.swagger.v3.oas.models.media.Schema; import jakarta.annotation.Nullable; @@ -18,7 +18,7 @@ public interface SchemaWalker { * @return the example, null if no example can be generated */ @Nullable - R fromSchema(Schema schema, Map definitions); + R fromSchema(Schema schema, Map definitions); /** * Check if the walker can handle the given content type diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/json/ExampleJsonValueGenerator.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/json/ExampleJsonValueGenerator.java similarity index 87% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/json/ExampleJsonValueGenerator.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/json/ExampleJsonValueGenerator.java index 46639216a..c02e0fb67 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/json/ExampleJsonValueGenerator.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/json/ExampleJsonValueGenerator.java @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers.json; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json; -import io.github.springwolf.core.asyncapi.components.examples.walkers.ExampleValueGenerator; -import io.github.springwolf.core.asyncapi.components.examples.walkers.PropertyExample; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.ExampleValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.PropertyExample; import io.swagger.v3.oas.models.media.Schema; import jakarta.validation.constraints.NotNull; import lombok.extern.slf4j.Slf4j; @@ -35,33 +35,33 @@ public boolean canHandle(String contentType) { } @Override - public Optional lookupSchemaName(Schema schema) { + public Optional lookupSchemaName(Schema schema) { return Optional.ofNullable(schema.getName()); } @NotNull @Override - public Optional createBooleanExample(Boolean value, Schema schema) { + public Optional createBooleanExample(Boolean value, Schema schema) { return Optional.of(BooleanNode.valueOf(value)); } @Override - public Optional createIntegerExample(Integer value, Schema schema) { + public Optional createIntegerExample(Integer value, Schema schema) { return Optional.of(new IntNode(value)); } @Override - public Optional createDoubleExample(Double value, Schema schema) { + public Optional createDoubleExample(Double value, Schema schema) { return Optional.of(new DoubleNode(value)); } @Override - public Optional createStringExample(String value, Schema schema) { + public Optional createStringExample(String value, Schema schema) { return Optional.of(JsonNodeFactory.instance.stringNode(value)); } @Override - public Optional createEnumExample(String anEnumValue, Schema schema) { + public Optional createEnumExample(String anEnumValue, Schema schema) { return Optional.of(JsonNodeFactory.instance.stringNode(anEnumValue)); } @@ -83,7 +83,7 @@ public JsonNode createArrayExample(Optional name, JsonNode arrayItem) { } @Override - public JsonNode prepareForSerialization(Schema schema, JsonNode exampleObject) { + public JsonNode prepareForSerialization(Schema schema, JsonNode exampleObject) { return exampleObject; } @@ -98,7 +98,7 @@ public JsonNode createRaw(Object exampleValue) { } @Override - public JsonNode getExampleOrNull(Optional fieldName, Schema schema, Object example) { + public JsonNode getExampleOrNull(Optional fieldName, Schema schema, Object example) { if (example instanceof JsonNode node) { return node; } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/DefaultExampleXmlValueSerializer.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/DefaultExampleXmlValueSerializer.java similarity index 93% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/DefaultExampleXmlValueSerializer.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/DefaultExampleXmlValueSerializer.java index 26275f117..013505797 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/DefaultExampleXmlValueSerializer.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/DefaultExampleXmlValueSerializer.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers.xml; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml; import org.w3c.dom.Document; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/ExampleXmlValueGenerator.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/ExampleXmlValueGenerator.java similarity index 87% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/ExampleXmlValueGenerator.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/ExampleXmlValueGenerator.java index 22c38e0e7..5ccb03080 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/ExampleXmlValueGenerator.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/ExampleXmlValueGenerator.java @@ -1,9 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers.xml; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml; -import io.github.springwolf.core.asyncapi.components.examples.walkers.ExampleValueGenerator; -import io.github.springwolf.core.asyncapi.components.examples.walkers.PropertyExample; -import io.github.springwolf.core.asyncapi.components.examples.walkers.SchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.ExampleValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.PropertyExample; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.SchemaWalker; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import lombok.extern.slf4j.Slf4j; @@ -66,7 +66,7 @@ public void initialize() { } @Override - public Optional lookupSchemaName(Schema schema) { + public Optional lookupSchemaName(Schema schema) { if (schema.getXml() != null && schema.getXml().getName() != null) { return Optional.of(schema.getXml().getName()); } @@ -74,17 +74,17 @@ public Optional lookupSchemaName(Schema schema) { } @Override - public Optional createIntegerExample(Integer value, Schema schema) { + public Optional createIntegerExample(Integer value, Schema schema) { return createNodeOrAddAttribute(value.toString(), schema); } @Override - public Optional createDoubleExample(Double value, Schema schema) { + public Optional createDoubleExample(Double value, Schema schema) { return createNodeOrAddAttribute(value.toString(), schema); } @Override - public Optional createBooleanExample(Boolean value, Schema schema) { + public Optional createBooleanExample(Boolean value, Schema schema) { return createNodeOrAddAttribute(value.toString(), schema); } @@ -104,14 +104,8 @@ public void addPropertyExamples(Node object, List> propert if (object == null) { throw new IllegalArgumentException("Element to add properties must not be empty"); } - try { - - for (PropertyExample propertyExample : properties) { - object.appendChild(handlePropertyExample(propertyExample)); - } - - } catch (ParserConfigurationException e) { - throw new RuntimeException(e); + for (PropertyExample propertyExample : properties) { + object.appendChild(handlePropertyExample(propertyExample)); } } @@ -121,7 +115,7 @@ private Element wrapNode(String name, Node toWrap) { return rootElement; } - private Element handlePropertyExample(PropertyExample propertyExample) throws ParserConfigurationException { + private Element handlePropertyExample(PropertyExample propertyExample) { final Node exampleValue = propertyExample.example(); if (exampleValue instanceof Element element) { return element; @@ -134,12 +128,12 @@ private Element handlePropertyExample(PropertyExample propertyExample) thr } @Override - public Optional createStringExample(String value, Schema schema) { + public Optional createStringExample(String value, Schema schema) { return createNodeOrAddAttribute(value, schema); } @Override - public Optional createEnumExample(String anEnumValue, Schema schema) { + public Optional createEnumExample(String anEnumValue, Schema schema) { return createStringExample(anEnumValue, schema); } @@ -162,12 +156,17 @@ public Node createArrayExample(Optional arrayNameOptional, Node arrayIte } @Override - public String prepareForSerialization(Schema schema, Node exampleObject) { + public String prepareForSerialization(Schema schema, Node exampleObject) { final Optional objectToWrite; if (exampleObject instanceof Element) { objectToWrite = Optional.of(exampleObject); } else { - objectToWrite = lookupSchemaName(schema).map(name -> wrapNode(name, exampleObject)); + Optional schemaName = lookupSchemaName(schema); + if (schemaName.isEmpty()) { + throw new SchemaWalker.ExampleGeneratingException( + "Unable to generate XML example for schema without a name; raw values cannot be serialized as XML"); + } + objectToWrite = schemaName.map(name -> wrapNode(name, exampleObject)); } if (objectToWrite.isEmpty()) { @@ -197,7 +196,7 @@ public Node createRaw(Object exampleValue) { } @Override - public Node getExampleOrNull(Optional fieldName, Schema schema, Object example) { + public Node getExampleOrNull(Optional fieldName, Schema schema, Object example) { String name = getCacheKey(schema); if (example instanceof Node node) { @@ -230,7 +229,7 @@ public Optional createEmptyObjectExample() { return Optional.of(document.createTextNode("")); } - private String getCacheKey(Schema schema) { + private String getCacheKey(Schema schema) { return schema.getName(); } @@ -251,7 +250,7 @@ private Node readXmlString(String xmlString) { return null; } - private Optional createNodeOrAddAttribute(String value, Schema schema) { + private Optional createNodeOrAddAttribute(String value, Schema schema) { if (!nodeStack.isEmpty() && isAttribute(schema)) { Element currentParent = nodeStack.peek(); lookupSchemaName(schema).ifPresent(name -> currentParent.setAttribute(name, value)); @@ -261,7 +260,7 @@ private Optional createNodeOrAddAttribute(String value, Schema schema) { } } - private boolean isAttribute(Schema schema) { + private boolean isAttribute(Schema schema) { return schema.getXml() != null && schema.getXml().getAttribute() != null && schema.getXml().getAttribute(); diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/ExampleXmlValueSerializer.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/ExampleXmlValueSerializer.java similarity index 75% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/ExampleXmlValueSerializer.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/ExampleXmlValueSerializer.java index abc0f339c..7360d5721 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/ExampleXmlValueSerializer.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/ExampleXmlValueSerializer.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers.xml; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml; import org.w3c.dom.Document; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/yaml/DefaultExampleYamlValueSerializer.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/yaml/DefaultExampleYamlValueSerializer.java similarity index 87% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/yaml/DefaultExampleYamlValueSerializer.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/yaml/DefaultExampleYamlValueSerializer.java index 8c64bf91e..b039a5d6f 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/yaml/DefaultExampleYamlValueSerializer.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/yaml/DefaultExampleYamlValueSerializer.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers.yaml; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.yaml; import io.swagger.v3.core.util.ObjectMapperFactory; import tools.jackson.core.JacksonException; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/yaml/ExampleYamlValueGenerator.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/yaml/ExampleYamlValueGenerator.java similarity index 86% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/yaml/ExampleYamlValueGenerator.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/yaml/ExampleYamlValueGenerator.java index 323481698..e6a880f11 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/yaml/ExampleYamlValueGenerator.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/yaml/ExampleYamlValueGenerator.java @@ -1,9 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers.yaml; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.yaml; -import io.github.springwolf.core.asyncapi.components.examples.walkers.ExampleValueGenerator; -import io.github.springwolf.core.asyncapi.components.examples.walkers.PropertyExample; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.ExampleValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.PropertyExample; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; @@ -34,12 +34,12 @@ public boolean canHandle(String contentType) { } @Override - public Optional lookupSchemaName(Schema schema) { + public Optional lookupSchemaName(Schema schema) { return exampleJsonValueGenerator.lookupSchemaName(schema); } @Override - public String prepareForSerialization(Schema schema, JsonNode exampleObject) { + public String prepareForSerialization(Schema schema, JsonNode exampleObject) { final String name = schema.getName(); try { if (springwolfConfigProperties.isStudioCompatibility()) { @@ -57,17 +57,17 @@ public String prepareForSerialization(Schema schema, JsonNode exampleObject) { } @Override - public Optional createIntegerExample(Integer value, Schema schema) { + public Optional createIntegerExample(Integer value, Schema schema) { return this.exampleJsonValueGenerator.createIntegerExample(value, schema); } @Override - public Optional createDoubleExample(Double value, Schema schema) { + public Optional createDoubleExample(Double value, Schema schema) { return this.exampleJsonValueGenerator.createDoubleExample(value, schema); } @Override - public Optional createBooleanExample(Boolean value, Schema schema) { + public Optional createBooleanExample(Boolean value, Schema schema) { return this.exampleJsonValueGenerator.createBooleanExample(value, schema); } @@ -87,12 +87,12 @@ public Optional createEmptyObjectExample() { } @Override - public Optional createStringExample(String value, Schema schema) { + public Optional createStringExample(String value, Schema schema) { return this.exampleJsonValueGenerator.createStringExample(value, schema); } @Override - public Optional createEnumExample(String anEnumValue, Schema schema) { + public Optional createEnumExample(String anEnumValue, Schema schema) { return this.exampleJsonValueGenerator.createEnumExample(anEnumValue, schema); } @@ -117,7 +117,7 @@ public JsonNode createRaw(Object exampleValueString) { } @Override - public JsonNode getExampleOrNull(Optional fieldName, Schema schema, Object example) { + public JsonNode getExampleOrNull(Optional fieldName, Schema schema, Object example) { return this.exampleJsonValueGenerator.getExampleOrNull(fieldName, schema, example); } } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/yaml/ExampleYamlValueSerializer.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/yaml/ExampleYamlValueSerializer.java similarity index 75% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/yaml/ExampleYamlValueSerializer.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/yaml/ExampleYamlValueSerializer.java index cbccfbcd9..01c8c783d 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/examples/walkers/yaml/ExampleYamlValueSerializer.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/yaml/ExampleYamlValueSerializer.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers.yaml; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.yaml; import tools.jackson.core.JacksonException; import tools.jackson.databind.JsonNode; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/postprocessors/AvroSchemaPostProcessor.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/AvroSchemaPostProcessor.java similarity index 61% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/postprocessors/AvroSchemaPostProcessor.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/AvroSchemaPostProcessor.java index c752d6e55..2090fd567 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/postprocessors/AvroSchemaPostProcessor.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/AvroSchemaPostProcessor.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.postprocessors; +package io.github.springwolf.core.asyncapi.schemas.schema.postprocessors; import io.github.springwolf.asyncapi.v3.model.ReferenceUtil; import io.swagger.v3.oas.models.media.Schema; @@ -10,6 +10,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Set; /** * Removes internal avro fields and classes from the schema. @@ -26,13 +27,13 @@ public class AvroSchemaPostProcessor implements SchemasPostProcessor { private static final String SPECIFIC_DAT_REF = "org.apache.avro.specific.SpecificData"; @Override - public void process(Schema schema, Map definitions, String contentType) { + public void process(Schema schema, Map> definitions, String contentType) { removeSchemas(definitions); - Deque queue = new LinkedList<>(List.of(schema)); - HashSet visited = new HashSet<>(); + Deque> queue = new LinkedList<>(List.of(schema)); + Set> visited = new HashSet<>(); while (!queue.isEmpty()) { - Schema currentSchema = queue.pop(); + Schema currentSchema = queue.pop(); if (visited.contains(currentSchema)) { continue; } @@ -43,22 +44,23 @@ public void process(Schema schema, Map definitions, String conte } } - private void processRefSchema(Schema schema, Deque queue, Map definitions) { + private void processRefSchema(Schema schema, Deque> queue, Map> definitions) { if (schema.get$ref() != null) { String schemaName = ReferenceUtil.getLastSegment(schema.get$ref()); - Schema refedSchema = definitions.get(schemaName); + Schema refedSchema = definitions.get(schemaName); if (refedSchema != null) { queue.add(refedSchema); } } } - private void processProperties(Schema schema, Deque queue) { - Map properties = schema.getProperties(); + private void processProperties(Schema schema, Deque> queue) { + Map properties = schema.getProperties(); if (properties != null) { - Schema schemaPropertySchema = properties.getOrDefault(SCHEMA_PROPERTY, null); - Schema specificDataPropertySchema = properties.getOrDefault(SPECIFIC_DATA_PROPERTY, null); - if (schemaPropertySchema != null && specificDataPropertySchema != null) { + Object schemaProperty = properties.get(SCHEMA_PROPERTY); + Object specificDataProperty = properties.get(SPECIFIC_DATA_PROPERTY); + if (schemaProperty instanceof Schema schemaPropertySchema + && specificDataProperty instanceof Schema specificDataPropertySchema) { if (StringUtils.endsWithIgnoreCase(schemaPropertySchema.get$ref(), SCHEMA_REF) && StringUtils.endsWithIgnoreCase(specificDataPropertySchema.get$ref(), SPECIFIC_DAT_REF)) { properties.remove(SCHEMA_PROPERTY); @@ -66,11 +68,17 @@ private void processProperties(Schema schema, Deque queue) { } } - properties.forEach((key, value) -> queue.add(value)); + properties.forEach((key, value) -> { + if (value instanceof Schema propertySchema) { + queue.add(propertySchema); + } else { + throw new IllegalStateException("Expected a Swagger Schema for property " + key); + } + }); } } - private void removeSchemas(Map definitions) { + private void removeSchemas(Map> definitions) { definitions.entrySet().removeIf(entry -> StringUtils.startsWithIgnoreCase(entry.getKey(), SCHEMA_AVRO_PREFIX)); } } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/ExampleGeneratorPostProcessor.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/ExampleGeneratorPostProcessor.java new file mode 100644 index 000000000..da497d260 --- /dev/null +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/ExampleGeneratorPostProcessor.java @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 +package io.github.springwolf.core.asyncapi.schemas.schema.postprocessors; + +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.swagger.v3.oas.models.media.Schema; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +import java.util.Map; + +@RequiredArgsConstructor +@Slf4j +public class ExampleGeneratorPostProcessor implements SchemasPostProcessor { + + private final SchemaWalkerProvider schemaWalkerProvider; + + @Override + public void process(Schema schema, Map> definitions, String contentType) { + if (schema.getExample() == null) { + log.trace("Generate example for {}", schema.getName()); + + schemaWalkerProvider + .generatorFor(contentType) + .ifPresentOrElse( + schemaWalker -> schema.setExample(schemaWalker.fromSchema(schema, definitions)), + () -> log.debug( + "No matching SchemaWalker for contentType {} for example {}", + contentType, + schema.getName())); + } + } +} diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/postprocessors/SchemasPostProcessor.java b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/SchemasPostProcessor.java similarity index 67% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/postprocessors/SchemasPostProcessor.java rename to springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/SchemasPostProcessor.java index 45b811680..0ea898c9d 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/components/postprocessors/SchemasPostProcessor.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/SchemasPostProcessor.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.postprocessors; +package io.github.springwolf.core.asyncapi.schemas.schema.postprocessors; import io.swagger.v3.oas.models.media.Schema; @@ -11,5 +11,5 @@ * It is closely coupled with the data structure of the SchemasService. */ public interface SchemasPostProcessor { - void process(Schema schema, Map definitions, String contentType); + void process(Schema schema, Map> definitions, String contentType); } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfCoreConfiguration.java b/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfCoreConfiguration.java index d3f004d59..656bf61e1 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfCoreConfiguration.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfCoreConfiguration.java @@ -9,21 +9,8 @@ import io.github.springwolf.core.asyncapi.channels.DefaultChannelsService; import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.components.DefaultComponentsService; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.DefaultSchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.SchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; -import io.github.springwolf.core.asyncapi.components.examples.walkers.xml.DefaultExampleXmlValueSerializer; -import io.github.springwolf.core.asyncapi.components.examples.walkers.xml.ExampleXmlValueGenerator; -import io.github.springwolf.core.asyncapi.components.examples.walkers.xml.ExampleXmlValueSerializer; -import io.github.springwolf.core.asyncapi.components.examples.walkers.yaml.DefaultExampleYamlValueSerializer; -import io.github.springwolf.core.asyncapi.components.examples.walkers.yaml.ExampleYamlValueGenerator; -import io.github.springwolf.core.asyncapi.components.examples.walkers.yaml.ExampleYamlValueSerializer; -import io.github.springwolf.core.asyncapi.components.postprocessors.AvroSchemaPostProcessor; -import io.github.springwolf.core.asyncapi.components.postprocessors.ExampleGeneratorPostProcessor; -import io.github.springwolf.core.asyncapi.components.postprocessors.SchemasPostProcessor; -import io.github.springwolf.core.asyncapi.grouping.AsyncApiGroupService; -import io.github.springwolf.core.asyncapi.grouping.GroupingService; +import io.github.springwolf.core.asyncapi.messages.DefaultMessagesService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.operations.DefaultOperationsService; import io.github.springwolf.core.asyncapi.operations.OperationsService; import io.github.springwolf.core.asyncapi.scanners.ChannelsScanner; @@ -38,13 +25,30 @@ import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.TypeExtractor; import io.github.springwolf.core.asyncapi.scanners.common.utils.StringValueResolverProxy; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.DefaultSchemasService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; import io.github.springwolf.core.asyncapi.schemas.converters.SchemaTitleModelConverter; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.DefaultSchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.SchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml.DefaultExampleXmlValueSerializer; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml.ExampleXmlValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml.ExampleXmlValueSerializer; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.yaml.DefaultExampleYamlValueSerializer; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.yaml.ExampleYamlValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.yaml.ExampleYamlValueSerializer; +import io.github.springwolf.core.asyncapi.schemas.schema.postprocessors.AvroSchemaPostProcessor; +import io.github.springwolf.core.asyncapi.schemas.schema.postprocessors.ExampleGeneratorPostProcessor; +import io.github.springwolf.core.asyncapi.schemas.schema.postprocessors.SchemasPostProcessor; import io.github.springwolf.core.configuration.docket.AsyncApiDocketService; import io.github.springwolf.core.configuration.docket.DefaultAsyncApiDocketService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; +import io.github.springwolf.core.grouping.AsyncApiGroupService; +import io.github.springwolf.core.grouping.GroupingService; import io.github.springwolf.core.standalone.StandaloneConfiguration; import io.swagger.v3.core.converter.ModelConverter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -118,8 +122,20 @@ public SwaggerSchemaMapper swaggerSchemaUtil(SpringwolfConfigProperties springwo @Bean @ConditionalOnMissingBean - public ComponentsService componentsService(SwaggerSchemaService schemaService) { - return new DefaultComponentsService(schemaService); + public ComponentsService componentsService(SchemasService schemasService, MessagesService messagesService) { + return new DefaultComponentsService(schemasService, messagesService); + } + + @Bean + @ConditionalOnMissingBean + public MessagesService messageService() { + return new DefaultMessagesService(); + } + + @Bean + @ConditionalOnMissingBean + public SchemasService defaultSchemasService(SwaggerSchemaService schemaService) { + return new DefaultSchemasService(schemaService); } @Bean @@ -128,18 +144,18 @@ public SwaggerSchemaService schemasService( SpringwolfConfigProperties springwolfConfigProperties, List schemaPostProcessors, SwaggerSchemaMapper swaggerSchemaMapper, - ModelConvertersProvider modelConvertersProvider) { + ModelConvertersRegisterer modelConvertersRegisterer) { return new SwaggerSchemaService( - springwolfConfigProperties, schemaPostProcessors, swaggerSchemaMapper, modelConvertersProvider); + springwolfConfigProperties, schemaPostProcessors, swaggerSchemaMapper, modelConvertersRegisterer); } @Bean @ConditionalOnMissingBean - public ModelConvertersProvider modelConvertersProvider( + public ModelConvertersRegisterer modelConvertersProvider( SpringwolfConfigProperties springwolfConfigProperties, List modelConverters, List jacksonModules) { - return new ModelConvertersProvider(springwolfConfigProperties, modelConverters, jacksonModules); + return new ModelConvertersRegisterer(springwolfConfigProperties, modelConverters, jacksonModules); } @Bean @@ -171,13 +187,13 @@ public SchemaTitleModelConverter schemaTitleModelConverter() { @Bean @ConditionalOnMissingBean - public SchemaWalkerProvider schemaWalkerProvider(List schemaWalkers) { + public SchemaWalkerProvider schemaWalkerProvider(List> schemaWalkers) { return new SchemaWalkerProvider(schemaWalkers); } @Bean @ConditionalOnMissingBean(name = "jsonSchemaWalker") - public SchemaWalker jsonSchemaWalker() { + public SchemaWalker jsonSchemaWalker() { return new DefaultSchemaWalker<>(new ExampleJsonValueGenerator()); } @@ -189,7 +205,7 @@ public ExampleXmlValueSerializer exampleXmlValueSerializer() { @Bean @ConditionalOnMissingBean(name = "xmlSchemaWalker") - public SchemaWalker xmlSchemaWalker(ExampleXmlValueSerializer exampleXmlValueSerializer) { + public SchemaWalker xmlSchemaWalker(ExampleXmlValueSerializer exampleXmlValueSerializer) { return new DefaultSchemaWalker<>(new ExampleXmlValueGenerator(exampleXmlValueSerializer)); } @@ -201,7 +217,7 @@ public ExampleYamlValueSerializer exampleYamlValueSerializer() { @Bean @ConditionalOnMissingBean(name = "yamlSchemaWalker") - public SchemaWalker yamlSchemaWalker( + public SchemaWalker yamlSchemaWalker( ExampleYamlValueSerializer exampleYamlValueSerializer, SpringwolfConfigProperties springwolfConfigProperties) { return new DefaultSchemaWalker<>(new ExampleYamlValueGenerator( @@ -229,8 +245,8 @@ public HeaderClassExtractor headerClassExtractor(SwaggerSchemaService schemaServ @Bean @ConditionalOnMissingBean public PayloadService payloadService( - ComponentsService componentsService, SpringwolfConfigProperties springwolfConfigProperties) { - return new PayloadService(componentsService, springwolfConfigProperties); + SchemasService schemasService, SpringwolfConfigProperties springwolfConfigProperties) { + return new PayloadService(schemasService, springwolfConfigProperties); } @Bean @@ -262,11 +278,16 @@ public StringValueResolverProxy stringValueResolverProxy() { @Bean @ConditionalOnMissingBean public AsyncAnnotationMessageService asyncAnnotationMessageService( - ComponentsService componentsService, + MessagesService messagesService, + SchemasService schemasService, PayloadAsyncOperationService payloadAsyncOperationService, List messageBindingProcessors, StringValueResolverProxy stringValueResolver) { return new AsyncAnnotationMessageService( - payloadAsyncOperationService, componentsService, messageBindingProcessors, stringValueResolver); + payloadAsyncOperationService, + messagesService, + schemasService, + messageBindingProcessors, + stringValueResolver); } } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfUiResourceConfigurer.java b/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfUiResourceConfigurer.java index 9b3e7fae2..9dd138e3e 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfUiResourceConfigurer.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfUiResourceConfigurer.java @@ -4,6 +4,7 @@ import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.jspecify.annotations.NonNull; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; @@ -22,7 +23,7 @@ public class SpringwolfUiResourceConfigurer implements WebMvcConfigurer { private final SpringwolfConfigProperties springwolfConfigProperties; @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { + public void addResourceHandlers(@NonNull ResourceHandlerRegistry registry) { String springwolfBasePath = springwolfConfigProperties.getPath().getBase(); log.debug("Serving Springwolf with base-path: {}", springwolfBasePath); diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfWebConfiguration.java b/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfWebConfiguration.java index 0ff785ccd..c66a6edca 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfWebConfiguration.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/configuration/SpringwolfWebConfiguration.java @@ -5,12 +5,12 @@ import io.github.springwolf.asyncapi.v3.jackson.DefaultAsyncApiSerializerService; import io.github.springwolf.core.asyncapi.AsyncApiService; import io.github.springwolf.core.asyncapi.components.ComponentsService; -import io.github.springwolf.core.asyncapi.grouping.AsyncApiGroupService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.github.springwolf.core.controller.ActuatorAsyncApiController; import io.github.springwolf.core.controller.AsyncApiController; import io.github.springwolf.core.controller.PublishingPayloadCreator; import io.github.springwolf.core.controller.UiConfigController; +import io.github.springwolf.core.grouping.AsyncApiGroupService; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/configuration/properties/SpringwolfConfigProperties.java b/springwolf-core/src/main/java/io/github/springwolf/core/configuration/properties/SpringwolfConfigProperties.java index 5ca4e2977..9fd67b67c 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/configuration/properties/SpringwolfConfigProperties.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/configuration/properties/SpringwolfConfigProperties.java @@ -81,8 +81,7 @@ public enum InitMode { */ private UI ui = new UI(); - @Nullable - private Scanner scanner; + private Scanner scanner = new Scanner(); @Nullable private Payload payload = new Payload(); @@ -252,11 +251,9 @@ public static class Defaults { @Setter public static class Scanner { - @Nullable - private static AsyncListener asyncListener; + private AsyncListener asyncListener = new AsyncListener(); - @Nullable - private static AsyncPublisher asyncPublisher; + private AsyncPublisher asyncPublisher = new AsyncPublisher(); @Getter @Setter diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/controller/UiConfigController.java b/springwolf-core/src/main/java/io/github/springwolf/core/controller/UiConfigController.java index fddf91c1f..39733f479 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/controller/UiConfigController.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/controller/UiConfigController.java @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.core.controller; -import io.github.springwolf.core.asyncapi.grouping.AsyncApiGroupService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; +import io.github.springwolf.core.grouping.AsyncApiGroupService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.MediaType; @@ -43,9 +43,9 @@ private UiConfig.InitialConfig createInitialConfig() { return new UiConfig.InitialConfig(defaults.isShowBindings(), defaults.isShowHeaders()); } - private record UiConfig(InitialConfig initialConfig, List groups) { - private record InitialConfig(boolean showBindings, boolean showHeaders) {} + public record UiConfig(InitialConfig initialConfig, List groups) { + public record InitialConfig(boolean showBindings, boolean showHeaders) {} - private record UiConfigGroup(String name) {} + public record UiConfigGroup(String name) {} } } diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/grouping/AsyncApiGroupService.java b/springwolf-core/src/main/java/io/github/springwolf/core/grouping/AsyncApiGroupService.java similarity index 98% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/grouping/AsyncApiGroupService.java rename to springwolf-core/src/main/java/io/github/springwolf/core/grouping/AsyncApiGroupService.java index 431145e52..c40c806c9 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/grouping/AsyncApiGroupService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/grouping/AsyncApiGroupService.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.grouping; +package io.github.springwolf.core.grouping; import io.github.springwolf.asyncapi.v3.model.AsyncAPI; import io.github.springwolf.core.configuration.docket.AsyncApiGroup; diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/grouping/GroupingService.java b/springwolf-core/src/main/java/io/github/springwolf/core/grouping/GroupingService.java similarity index 95% rename from springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/grouping/GroupingService.java rename to springwolf-core/src/main/java/io/github/springwolf/core/grouping/GroupingService.java index d75b8feca..2f688973d 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/asyncapi/grouping/GroupingService.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/grouping/GroupingService.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.grouping; +package io.github.springwolf.core.grouping; import io.github.springwolf.asyncapi.v3.model.AsyncAPI; import io.github.springwolf.asyncapi.v3.model.ReferenceUtil; @@ -230,7 +230,7 @@ private static Set findUnmarkedNestedSchemas( } if ((schemaFormat.startsWith(SchemaFormat.OPENAPI_V3.toString()) || schemaFormat.startsWith(SchemaFormat.OPENAPI_V3_1.toString())) - && multiFormatSchema.getSchema() instanceof Schema openapiSchema) { + && multiFormatSchema.getSchema() instanceof Schema openapiSchema) { return findUnmarkedNestedSchemasForOpenAPISchema(markingContext, openapiSchema); } } @@ -289,21 +289,25 @@ private static Set findUnmarkedNestedSchemasForAsyncAPISchema( */ private static Set findUnmarkedNestedSchemasForOpenAPISchema( MarkingContext markingContext, Schema openapiSchema) { - Stream propertySchemas = openapiSchema.getProperties() == null + Stream> propertySchemas = openapiSchema.getProperties() == null ? Stream.empty() - : openapiSchema.getProperties().values().stream().flatMap(schema -> { - Stream base = Stream.of(schema); - Schema items = schema.getItems(); - return items != null ? Stream.concat(base, Stream.of(items)) : base; - }); + : openapiSchema.getProperties().values().stream() + .map(schema -> (Schema) schema) + .flatMap(schema -> { + Stream> base = Stream.of(schema); + Schema items = schema.getItems(); + return items != null ? Stream.concat(base, Stream.of(items)) : base; + }); - Stream referencedSchemas = Stream.of( + Stream> referencedSchemas = Stream.of( openapiSchema.getAllOf(), openapiSchema.getAnyOf(), openapiSchema.getOneOf()) .filter(Objects::nonNull) - .flatMap(List::stream); + .flatMap(List::stream) + .map(schema -> (Schema) schema); - Stream referencedSchemaElements = - Stream.of(openapiSchema.getNot(), openapiSchema.getItems()).filter(Objects::nonNull); + Stream> referencedSchemaElements = Stream.of(openapiSchema.getNot(), openapiSchema.getItems()) + .filter(Objects::nonNull) + .map(schema -> (Schema) schema); return Stream.concat(propertySchemas, Stream.concat(referencedSchemas, referencedSchemaElements)) .map(Schema::get$ref) diff --git a/springwolf-core/src/main/java/io/github/springwolf/core/standalone/DefaultStandaloneApplication.java b/springwolf-core/src/main/java/io/github/springwolf/core/standalone/DefaultStandaloneApplication.java index f8162fe92..27c741d32 100644 --- a/springwolf-core/src/main/java/io/github/springwolf/core/standalone/DefaultStandaloneApplication.java +++ b/springwolf-core/src/main/java/io/github/springwolf/core/standalone/DefaultStandaloneApplication.java @@ -26,8 +26,13 @@ private DefaultStandaloneApplication(ConfigurableEnvironment environment, List * Allows usage of Springwolf at build time, for example in unit test. */ -public interface StandaloneApplication { +public interface StandaloneApplication extends AutoCloseable { AsyncApiService getAsyncApiService(); + + @Override + void close(); } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/DefaultAsyncApiServiceIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/DefaultAsyncApiServiceIntegrationTest.java index 8a87b2c1d..e58a226a2 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/DefaultAsyncApiServiceIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/DefaultAsyncApiServiceIntegrationTest.java @@ -9,10 +9,10 @@ import io.github.springwolf.asyncapi.v3.model.server.Server; import io.github.springwolf.core.asyncapi.channels.ChannelsService; import io.github.springwolf.core.asyncapi.components.ComponentsService; -import io.github.springwolf.core.asyncapi.grouping.AsyncApiGroupService; import io.github.springwolf.core.asyncapi.operations.OperationsService; import io.github.springwolf.core.configuration.docket.DefaultAsyncApiDocketService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; +import io.github.springwolf.core.grouping.AsyncApiGroupService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/DefaultAsyncApiServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/DefaultAsyncApiServiceTest.java index 165c93c58..53c8959ae 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/DefaultAsyncApiServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/DefaultAsyncApiServiceTest.java @@ -4,11 +4,11 @@ import io.github.springwolf.asyncapi.v3.model.AsyncAPI; import io.github.springwolf.core.asyncapi.channels.ChannelsService; import io.github.springwolf.core.asyncapi.components.ComponentsService; -import io.github.springwolf.core.asyncapi.grouping.AsyncApiGroupService; import io.github.springwolf.core.asyncapi.operations.OperationsService; import io.github.springwolf.core.configuration.docket.AsyncApiDocket; import io.github.springwolf.core.configuration.docket.AsyncApiDocketService; import io.github.springwolf.core.fixtures.AsyncApiDocketFixture; +import io.github.springwolf.core.grouping.AsyncApiGroupService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,18 +30,15 @@ class DefaultAsyncApiServiceTest { private DefaultAsyncApiService defaultAsyncApiService; private AsyncApiDocketService asyncApiDocketService; - private ChannelsService channelsService; - private OperationsService operationsService; - private ComponentsService componentsService; - private List customizers = new ArrayList<>(); private AsyncApiGroupService groupService; @BeforeEach void setup() { asyncApiDocketService = mock(AsyncApiDocketService.class); - channelsService = mock(ChannelsService.class); - operationsService = mock(OperationsService.class); - componentsService = mock(ComponentsService.class); + ChannelsService channelsService = mock(ChannelsService.class); + OperationsService operationsService = mock(OperationsService.class); + ComponentsService componentsService = mock(ComponentsService.class); + List customizers = new ArrayList<>(); groupService = mock(AsyncApiGroupService.class); when(channelsService.findChannels()).thenReturn(Map.of()); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/channels/DefaultChannelsServiceIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/channels/DefaultChannelsServiceIntegrationTest.java index 4da24b6ad..cef6fbe07 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/channels/DefaultChannelsServiceIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/channels/DefaultChannelsServiceIntegrationTest.java @@ -12,6 +12,7 @@ import org.springframework.stereotype.Component; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; +import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; @@ -41,9 +42,8 @@ void getChannels() { @Component static class SimpleChannelScanner implements ChannelsScanner { @Override - public Map scan() { - return Map.of( - channelId, ChannelObject.builder().channelId(channelId).build()); + public List scan() { + return List.of(ChannelObject.builder().channelId(channelId).build()); } } @@ -67,13 +67,11 @@ static class SendChannelScanner implements ChannelsScanner { .build(); @Override - public Map scan() { - return Map.of( - channelId, - ChannelObject.builder() - .channelId(channelId) - .messages(Map.of("sendMessage", MessageReference.toComponentMessage("sendMessage"))) - .build()); + public List scan() { + return List.of(ChannelObject.builder() + .channelId(channelId) + .messages(Map.of("sendMessage", MessageReference.toComponentMessage("sendMessage"))) + .build()); } } @@ -85,14 +83,11 @@ static class ReceiveChannelScanner implements ChannelsScanner { .build(); @Override - public Map scan() { - return Map.of( - channelId, - ChannelObject.builder() - .channelId(channelId) - .messages( - Map.of("receiveMessage", MessageReference.toComponentMessage("receiveMessage"))) - .build()); + public List scan() { + return List.of(ChannelObject.builder() + .channelId(channelId) + .messages(Map.of("receiveMessage", MessageReference.toComponentMessage("receiveMessage"))) + .build()); } } } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultJsonComponentsServiceIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultJsonComponentsServiceIntegrationTest.java index 713595829..7845d9718 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultJsonComponentsServiceIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultJsonComponentsServiceIntegrationTest.java @@ -5,14 +5,17 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.DefaultSchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; -import io.github.springwolf.core.asyncapi.components.postprocessors.ExampleGeneratorPostProcessor; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.messages.DefaultMessagesService; +import io.github.springwolf.core.asyncapi.schemas.DefaultSchemasService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; import io.github.springwolf.core.asyncapi.schemas.converters.SchemaTitleModelConverter; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.DefaultSchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.postprocessors.ExampleGeneratorPostProcessor; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.github.springwolf.core.fixtures.ClasspathUtil; import io.github.springwolf.core.fixtures.JsonMapperTestConfiguration; @@ -51,70 +54,67 @@ class DefaultJsonComponentsServiceIntegrationTest { List.of(new ExampleGeneratorPostProcessor( new SchemaWalkerProvider(List.of(new DefaultSchemaWalker<>(new ExampleJsonValueGenerator()))))), new SwaggerSchemaMapper(springwolfConfigProperties), - new ModelConvertersProvider( + new ModelConvertersRegisterer( springwolfConfigProperties, List.of(new SchemaTitleModelConverter()), List.of())); - private final ComponentsService componentsService = new DefaultComponentsService(schemaService); + private final SchemasService schemasService = new DefaultSchemasService(schemaService); + private final ComponentsService componentsService = + new DefaultComponentsService(schemasService, new DefaultMessagesService()); private static final JsonMapper jsonMapper = JsonMapperTestConfiguration.jsonMapper; @Test void getSchemas() throws Exception { - componentsService.resolvePayloadSchema(CompositeFoo.class, CONTENT_TYPE_APPLICATION_JSON); - componentsService.resolvePayloadSchema(FooWithEnum.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(CompositeFoo.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(FooWithEnum.class, CONTENT_TYPE_APPLICATION_JSON); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/json/definitions.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getDocumentedDefinitions() throws Exception { - componentsService.resolvePayloadSchema(DocumentedSimpleFoo.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(DocumentedSimpleFoo.class, CONTENT_TYPE_APPLICATION_JSON); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/json/documented-definitions.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getArrayDefinitions() throws Exception { - componentsService.resolvePayloadSchema(ArrayFoo.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(ArrayFoo.class, CONTENT_TYPE_APPLICATION_JSON); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/json/array-definitions.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getComplexDefinitions() throws Exception { - componentsService.resolvePayloadSchema(ComplexFoo.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(ComplexFoo.class, CONTENT_TYPE_APPLICATION_JSON); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/json/complex-definitions.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getListWrapperDefinitions() throws Exception { - componentsService.resolvePayloadSchema(ListWrapper.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(ListWrapper.class, CONTENT_TYPE_APPLICATION_JSON); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/json/generics-wrapper-definitions.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @@ -232,13 +232,12 @@ private static class MyClass { class SchemaWithOneOf { @Test void schemaWithOneOf() throws Exception { - componentsService.resolvePayloadSchema(SchemaAnnotationFoo.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(SchemaAnnotationFoo.class, CONTENT_TYPE_APPLICATION_JSON); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/json/annotation-definitions.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @@ -279,7 +278,7 @@ public class ImplementationTwo { class JsonSubTypesRecursionTest { @Test void registerSchemaWithoutStackOverflowException() { - componentsService.resolvePayloadSchema(CriteriaMessage.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(CriteriaMessage.class, CONTENT_TYPE_APPLICATION_JSON); Map schemas = componentsService.getSchemas(); assertThat(schemas) @@ -312,13 +311,12 @@ public class LegacyCriteriaMessage extends CriteriaMessage { class JsonTypeTest { @Test void getJsonTypeDefinitions() throws Exception { - componentsService.resolvePayloadSchema(JsonTypeInfoPayloadDto.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(JsonTypeInfoPayloadDto.class, CONTENT_TYPE_APPLICATION_JSON); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/json/json-type-definitions.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultXmlComponentsServiceIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultXmlComponentsServiceIntegrationTest.java index 1a35694b5..54378d04c 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultXmlComponentsServiceIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultXmlComponentsServiceIntegrationTest.java @@ -1,15 +1,18 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.core.asyncapi.components; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.DefaultSchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.xml.DefaultExampleXmlValueSerializer; -import io.github.springwolf.core.asyncapi.components.examples.walkers.xml.ExampleXmlValueGenerator; -import io.github.springwolf.core.asyncapi.components.postprocessors.ExampleGeneratorPostProcessor; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.messages.DefaultMessagesService; +import io.github.springwolf.core.asyncapi.schemas.DefaultSchemasService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; import io.github.springwolf.core.asyncapi.schemas.converters.SchemaTitleModelConverter; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.DefaultSchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml.DefaultExampleXmlValueSerializer; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml.ExampleXmlValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.postprocessors.ExampleGeneratorPostProcessor; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.github.springwolf.core.fixtures.ClasspathUtil; import io.github.springwolf.core.fixtures.JsonMapperTestConfiguration; @@ -48,80 +51,76 @@ class DefaultXmlComponentsServiceIntegrationTest { List.of(new ExampleGeneratorPostProcessor(new SchemaWalkerProvider(List.of( new DefaultSchemaWalker<>(new ExampleXmlValueGenerator(new DefaultExampleXmlValueSerializer())))))), new SwaggerSchemaMapper(configProperties), - new ModelConvertersProvider(configProperties, List.of(new SchemaTitleModelConverter()), List.of())); - private final ComponentsService componentsService = new DefaultComponentsService(schemaService); + new ModelConvertersRegisterer(configProperties, List.of(new SchemaTitleModelConverter()), List.of())); + private final SchemasService schemasService = new DefaultSchemasService(schemaService); + private final ComponentsService componentsService = + new DefaultComponentsService(schemasService, new DefaultMessagesService()); @Test void getSchemas() throws Exception { - componentsService.resolvePayloadSchema(CompositeFoo.class, "text/xml"); - componentsService.resolvePayloadSchema(FooWithEnum.class, "text/xml"); + schemasService.registerType(CompositeFoo.class, "text/xml"); + schemasService.registerType(FooWithEnum.class, "text/xml"); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/xml/definitions-xml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getDocumentedDefinitions() throws Exception { - componentsService.resolvePayloadSchema(DocumentedSimpleFoo.class, "text/xml"); + schemasService.registerType(DocumentedSimpleFoo.class, "text/xml"); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/xml/documented-definitions-xml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getArrayDefinitions() throws Exception { - componentsService.resolvePayloadSchema(ArrayFoo.class, "text/xml"); + schemasService.registerType(ArrayFoo.class, "text/xml"); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/xml/array-definitions-xml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getComplexDefinitions() throws Exception { - componentsService.resolvePayloadSchema(ComplexFoo.class, "text/xml"); + schemasService.registerType(ComplexFoo.class, "text/xml"); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/xml/complex-definitions-xml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getComplexDefinitionsWithAttributes() throws Exception { - componentsService.resolvePayloadSchema(ComplexAttributesFoo.class, "text/xml"); + schemasService.registerType(ComplexAttributesFoo.class, "text/xml"); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/xml/complex-definitions-with-attributes-xml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getListWrapperDefinitions() throws Exception { - componentsService.resolvePayloadSchema(ListWrapper.class, "text/xml"); + schemasService.registerType(ListWrapper.class, "text/xml"); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/xml/generics-wrapper-definitions-xml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @@ -249,13 +248,12 @@ private static class MyClass { class SchemaWithOneOf { @Test void schemaWithOneOf() throws Exception { - componentsService.resolvePayloadSchema(SchemaAnnotationFoo.class, "text/xml"); + schemasService.registerType(SchemaAnnotationFoo.class, "text/xml"); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/xml/annotation-definitions-xml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @@ -349,14 +347,13 @@ private static class MyClassWithAttribute { class XmlSchemaName { @Test void schemasWithSharedProperty() throws Exception { - componentsService.resolvePayloadSchema(XmlSchemaName.ClassB.class, "text/xml"); - componentsService.resolvePayloadSchema(XmlSchemaName.ClassA.class, "text/xml"); + schemasService.registerType(XmlSchemaName.ClassB.class, "text/xml"); + schemasService.registerType(XmlSchemaName.ClassA.class, "text/xml"); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinition("/schemas/xml/schema-with-shared-property.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultYamlComponentsServiceIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultYamlComponentsServiceIntegrationTest.java index 9a9b050f9..80672bfa5 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultYamlComponentsServiceIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultYamlComponentsServiceIntegrationTest.java @@ -5,16 +5,19 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.DefaultSchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; -import io.github.springwolf.core.asyncapi.components.examples.walkers.yaml.DefaultExampleYamlValueSerializer; -import io.github.springwolf.core.asyncapi.components.examples.walkers.yaml.ExampleYamlValueGenerator; -import io.github.springwolf.core.asyncapi.components.postprocessors.ExampleGeneratorPostProcessor; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.messages.DefaultMessagesService; +import io.github.springwolf.core.asyncapi.schemas.DefaultSchemasService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; import io.github.springwolf.core.asyncapi.schemas.converters.SchemaTitleModelConverter; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.DefaultSchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.yaml.DefaultExampleYamlValueSerializer; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.yaml.ExampleYamlValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.postprocessors.ExampleGeneratorPostProcessor; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.github.springwolf.core.fixtures.ClasspathUtil; import io.github.springwolf.core.fixtures.JsonMapperTestConfiguration; @@ -55,70 +58,67 @@ class DefaultYamlComponentsServiceIntegrationTest { List.of(new ExampleGeneratorPostProcessor( new SchemaWalkerProvider(List.of(new DefaultSchemaWalker<>(exampleYamlValueGenerator))))), new SwaggerSchemaMapper(springwolfConfigProperties), - new ModelConvertersProvider( + new ModelConvertersRegisterer( springwolfConfigProperties, List.of(new SchemaTitleModelConverter()), List.of())); - private final ComponentsService componentsService = new DefaultComponentsService(schemaService); + private final SchemasService schemasService = new DefaultSchemasService(schemaService); + private final ComponentsService componentsService = + new DefaultComponentsService(schemasService, new DefaultMessagesService()); private static final JsonMapper jsonMapper = JsonMapperTestConfiguration.jsonMapper; @Test void getSchemas() throws Exception { - componentsService.resolvePayloadSchema(CompositeFoo.class, CONTENT_TYPE_APPLICATION_YAML); - componentsService.resolvePayloadSchema(FooWithEnum.class, CONTENT_TYPE_APPLICATION_YAML); + schemasService.registerType(CompositeFoo.class, CONTENT_TYPE_APPLICATION_YAML); + schemasService.registerType(FooWithEnum.class, CONTENT_TYPE_APPLICATION_YAML); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinitions("/schemas/yaml/definitions-yaml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getDocumentedDefinitions() throws Exception { - componentsService.resolvePayloadSchema(DocumentedSimpleFoo.class, CONTENT_TYPE_APPLICATION_YAML); + schemasService.registerType(DocumentedSimpleFoo.class, CONTENT_TYPE_APPLICATION_YAML); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinitions("/schemas/yaml/documented-definitions-yaml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getArrayDefinitions() throws Exception { - componentsService.resolvePayloadSchema(ArrayFoo.class, CONTENT_TYPE_APPLICATION_YAML); + schemasService.registerType(ArrayFoo.class, CONTENT_TYPE_APPLICATION_YAML); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinitions("/schemas/yaml/array-definitions-yaml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getComplexDefinitions() throws Exception { - componentsService.resolvePayloadSchema(ComplexFoo.class, CONTENT_TYPE_APPLICATION_YAML); + schemasService.registerType(ComplexFoo.class, CONTENT_TYPE_APPLICATION_YAML); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinitions("/schemas/yaml/complex-definitions-yaml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @Test void getListWrapperDefinitions() throws Exception { - componentsService.resolvePayloadSchema(ListWrapper.class, CONTENT_TYPE_APPLICATION_YAML); + schemasService.registerType(ListWrapper.class, CONTENT_TYPE_APPLICATION_YAML); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinitions("/schemas/yaml/generics-wrapper-definitions-yaml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @@ -236,13 +236,12 @@ private static class MyClass { class SchemaWithOneOf { @Test void schemaWithOneOf() throws Exception { - componentsService.resolvePayloadSchema(SchemaAnnotationFoo.class, CONTENT_TYPE_APPLICATION_YAML); + schemasService.registerType(SchemaAnnotationFoo.class, CONTENT_TYPE_APPLICATION_YAML); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinitions("/schemas/yaml/annotation-definitions-yaml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } @@ -283,7 +282,7 @@ public class ImplementationTwo { class JsonSubTypesRecursionTest { @Test void registerSchemaWithoutStackOverflowException() { - componentsService.resolvePayloadSchema(CriteriaMessage.class, CONTENT_TYPE_APPLICATION_YAML); + schemasService.registerType(CriteriaMessage.class, CONTENT_TYPE_APPLICATION_YAML); Map schemas = componentsService.getSchemas(); assertThat(schemas) @@ -316,14 +315,12 @@ public class LegacyCriteriaMessage extends CriteriaMessage { class JsonTypeTest { @Test void getJsonTypeDefinitions() throws Exception { - componentsService.resolvePayloadSchema( - JsonTypeTest.JsonTypeInfoPayloadDto.class, CONTENT_TYPE_APPLICATION_YAML); + schemasService.registerType(JsonTypeTest.JsonTypeInfoPayloadDto.class, CONTENT_TYPE_APPLICATION_YAML); String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getSchemas()); String expected = loadDefinitions("/schemas/yaml/json-type-definitions-yaml.json", actualDefinitions); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerTest.java deleted file mode 100644 index 3e2f3f6cb..000000000 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerTest.java +++ /dev/null @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers; - -import io.swagger.v3.oas.models.media.Schema; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.assertj.core.api.Assertions.assertThat; - -class DefaultSchemaWalkerTest { - - @Test - void getTypeForExampleValue() { - DefaultSchemaWalker schemaWalker = new DefaultSchemaWalker<>(null); - - Schema schema1 = new Schema(); // no types defined. - Schema schema2 = new Schema().type("string"); - Schema schema3 = new Schema().types(Set.of("string", "null")); - Schema schema4 = new Schema().types(Set.of("string", "integer")); - - assertThat(schemaWalker.getTypeForExampleValue(schema1)).isNull(); - assertThat(schemaWalker.getTypeForExampleValue(schema2)).isEqualTo("string"); - assertThat(schemaWalker.getTypeForExampleValue(schema3)).isEqualTo("string"); - assertThat(schemaWalker.getTypeForExampleValue(schema4)).isEqualTo("integer"); - } - - @Test - void getDefaultValue() { - DefaultSchemaWalker schemaWalker = new DefaultSchemaWalker<>(new DummyExampleValueGenerator()); - - Schema schema1 = new Schema().type("string"); - Schema schema2 = new Schema().type("string"); - schema2.setConst("constValue"); - Schema schema3 = new Schema().type("string"); - schema3.setEnum(List.of("example1", "example2")); - - assertThat(schemaWalker.fromSchema(schema1, Map.of())).isEqualTo("string"); - assertThat(schemaWalker.fromSchema(schema2, Map.of())).isEqualTo("constValue"); - assertThat(schemaWalker.fromSchema(schema3, Map.of())).isEqualTo("example1"); - } -} diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DummyExampleValueGenerator.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DummyExampleValueGenerator.java deleted file mode 100644 index 82d5c80e0..000000000 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DummyExampleValueGenerator.java +++ /dev/null @@ -1,88 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers; - -import io.swagger.v3.oas.models.media.Schema; - -import java.util.List; -import java.util.Optional; - -class DummyExampleValueGenerator implements ExampleValueGenerator { - - @Override - public boolean canHandle(String contentType) { - return true; - } - - @Override - public Optional lookupSchemaName(Schema schema) { - return Optional.empty(); - } - - @Override - public Object prepareForSerialization(Schema name, Object exampleObject) { - return exampleObject; - } - - @Override - public Optional createIntegerExample(Integer value, Schema schema) { - return Optional.of("integerExample"); - } - - @Override - public Optional createDoubleExample(Double value, Schema schema) { - return Optional.of("doubleExample"); - } - - @Override - public Optional createBooleanExample(Boolean value, Schema schema) { - return Optional.of("booleanExample"); - } - - @Override - public Optional createEmptyObjectExample() { - return Optional.of("emptyObjectExample"); - } - - @Override - public Optional createStringExample(String value, Schema schema) { - return Optional.of(value); - } - - @Override - public Optional createEnumExample(String anEnumValue, Schema schema) { - return Optional.of(anEnumValue); - } - - @Override - public Optional createUnknownSchemaStringTypeExample(String schemaType) { - return Optional.empty(); - } - - @Override - public Optional createUnknownSchemaStringFormatExample(String schemaFormat) { - return Optional.empty(); - } - - @Override - public Object createRaw(Object exampleValueString) { - return exampleValueString; - } - - @Override - public Object getExampleOrNull(Optional fieldName, Schema schema, Object example) { - return schema.getExample(); - } - - @Override - public Object createArrayExample(Optional name, Object arrayItem) { - return null; - } - - @Override - public void addPropertyExamples(Object object, List properties) {} - - @Override - public Object startObject(Optional name) { - return null; - } -} diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultComponentsServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/messages/DefaultMessagesServiceTest.java similarity index 68% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultComponentsServiceTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/messages/DefaultMessagesServiceTest.java index 517414ece..7a58b477a 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultComponentsServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/messages/DefaultMessagesServiceTest.java @@ -1,42 +1,37 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components; +package io.github.springwolf.core.asyncapi.messages; import io.github.springwolf.asyncapi.v3.model.channel.message.MessageObject; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; import io.github.springwolf.core.fixtures.JsonMapperTestConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import tools.jackson.databind.json.JsonMapper; import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(MockitoExtension.class) -class DefaultComponentsServiceTest { +class DefaultMessagesServiceTest { private static final JsonMapper jsonMapper = JsonMapperTestConfiguration.jsonMapper; - @Mock - private SwaggerSchemaService schemaService; - - private ComponentsService componentsService; + private MessagesService messagesService; @BeforeEach void setUp() { - componentsService = new DefaultComponentsService(schemaService); + messagesService = new DefaultMessagesService(); } @Test - void getMessages() throws Exception { - componentsService.registerMessage( + void getMessages() { + messagesService.registerMessage( MessageObject.builder().name("messageName1").build()); - componentsService.registerMessage( + messagesService.registerMessage( MessageObject.builder().name("messageName2").build()); String actualDefinitions = - jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(componentsService.getMessages()); + jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(messagesService.getMessages()); String expected = """ { "messageName1" : { @@ -47,7 +42,6 @@ void getMessages() throws Exception { } }""".stripIndent(); - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).isEqualTo(expected); } } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/operations/DefaultOperationsServiceIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/operations/DefaultOperationsServiceIntegrationTest.java index d888a8f6e..da755e664 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/operations/DefaultOperationsServiceIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/operations/DefaultOperationsServiceIntegrationTest.java @@ -10,6 +10,7 @@ import org.springframework.stereotype.Component; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; +import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; @@ -32,9 +33,10 @@ class DefaultOperationsServiceIntegrationTest { @Test void getOperations() { Map actualChannels = defaultOperationsService.findOperations(); + Operation simpleOperation = simpleOperationsScanner.scan().get(0); assertThat(actualChannels) - .containsAllEntriesOf(simpleOperationsScanner.scan()) + .containsEntry(simpleOperation.getOperationId(), simpleOperation) .containsEntry("receive", SameTopic.ReceiveOperationScanner.receiveOperation) .containsEntry("send", SameTopic.SendOperationScanner.sentOperation); } @@ -42,14 +44,14 @@ void getOperations() { @Component static class SimpleOperationScanner implements OperationsScanner { @Override - public Map scan() { + public List scan() { Operation operation = Operation.builder() .operationId("foo") .channel(ChannelReference.fromChannel("foo")) .action(OperationAction.RECEIVE) .build(); - return Map.of(operation.getOperationId(), operation); + return List.of(operation); } } @@ -65,8 +67,8 @@ static class SendOperationScanner implements OperationsScanner { .build(); @Override - public Map scan() { - return Map.of(sentOperation.getOperationId(), sentOperation); + public List scan() { + return List.of(sentOperation); } } @@ -79,8 +81,8 @@ static class ReceiveOperationScanner implements OperationsScanner { .build(); @Override - public Map scan() { - return Map.of(receiveOperation.getOperationId(), receiveOperation); + public List scan() { + return List.of(receiveOperation); } } } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/bindings/processor/TestAbstractChannelBindingProcessor.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/bindings/processor/TestAbstractChannelBindingProcessor.java index 718ee7e90..56b1dc206 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/bindings/processor/TestAbstractChannelBindingProcessor.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/bindings/processor/TestAbstractChannelBindingProcessor.java @@ -23,7 +23,7 @@ public class TestAbstractChannelBindingProcessor public static final ChannelBinding BINDING = new AbstractChannelBindingBinding(); public TestAbstractChannelBindingProcessor(StringValueResolver stringValueResolver) { - super(stringValueResolver); + super(stringValueResolver, TestChannelBinding.class); } @Override diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/bindings/processor/TestAbstractOperationBindingProcessor.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/bindings/processor/TestAbstractOperationBindingProcessor.java index c2f041182..c96556412 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/bindings/processor/TestAbstractOperationBindingProcessor.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/bindings/processor/TestAbstractOperationBindingProcessor.java @@ -23,7 +23,7 @@ public class TestAbstractOperationBindingProcessor public static final OperationBinding BINDING = new AbstractOperationBindingBinding(); public TestAbstractOperationBindingProcessor(StringValueResolver stringValueResolver) { - super(stringValueResolver); + super(stringValueResolver, TestOperationBinding.class); } @Override diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelsInClassScannerAdapterTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelsInClassScannerAdapterTest.java index a7ae7f67c..2968f576b 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelsInClassScannerAdapterTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/ChannelsInClassScannerAdapterTest.java @@ -6,7 +6,6 @@ import org.junit.jupiter.api.Test; import java.util.List; -import java.util.Map; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; @@ -25,7 +24,7 @@ class ChannelsInClassScannerAdapterTest { @Test void noClassFoundTest() { // when - Map channels = channelsInClassScannerAdapter.scan(); + List channels = channelsInClassScannerAdapter.scan(); // then assertThat(channels).isEmpty(); @@ -35,37 +34,30 @@ void noClassFoundTest() { void processClassTest() { // given when(classScanner.scan()).thenReturn(Set.of(String.class)); - Map.Entry channel1 = Map.entry( - "channel1", ChannelObject.builder().channelId("channel1").build()); - Map.Entry channel2 = Map.entry( - "channel2", ChannelObject.builder().channelId("channel2").build()); - when(channelsInClassScanner.scan(any())).thenReturn(List.of(channel1.getValue(), channel2.getValue())); + ChannelObject channel1 = ChannelObject.builder().channelId("channel1").build(); + ChannelObject channel2 = ChannelObject.builder().channelId("channel2").build(); + when(channelsInClassScanner.scan(any())).thenReturn(List.of(channel1, channel2)); // when - Map channels = channelsInClassScannerAdapter.scan(); + List channels = channelsInClassScannerAdapter.scan(); // then assertThat(channels).containsExactly(channel1, channel2); } @Test - void sameChannelsAreMergedTest() { + void sameChannelsAreReturnedUnmergedTest() { // given when(classScanner.scan()).thenReturn(Set.of(String.class)); - Map.Entry channel1 = Map.entry( - "channel1", ChannelObject.builder().channelId("channel1").build()); - Map.Entry channel2 = Map.entry( - "channel1", ChannelObject.builder().channelId("channel1").build()); - when(channelsInClassScanner.scan(any())).thenReturn(List.of(channel1.getValue(), channel2.getValue())); + ChannelObject channel1 = ChannelObject.builder().channelId("channel1").build(); + ChannelObject channel2 = ChannelObject.builder().channelId("channel1").build(); + when(channelsInClassScanner.scan(any())).thenReturn(List.of(channel1, channel2)); // when - Map channels = channelsInClassScannerAdapter.scan(); + List channels = channelsInClassScannerAdapter.scan(); // then - assertThat(channels) - .containsExactly(Map.entry( - "channel1", - ChannelObject.builder().channelId("channel1").build())); + assertThat(channels).containsExactly(channel1, channel2); } @Test @@ -75,7 +67,7 @@ void processEmptyClassTest() { when(channelsInClassScanner.scan(any())).thenReturn(List.of()); // when - Map channels = channelsInClassScannerAdapter.scan(); + List channels = channelsInClassScannerAdapter.scan(); // then assertThat(channels).isEmpty(); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/AsyncAnnotationClassLevelChannelsScannerTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/AsyncAnnotationClassLevelChannelsScannerTest.java index c835665b2..1fd1934ae 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/AsyncAnnotationClassLevelChannelsScannerTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/AsyncAnnotationClassLevelChannelsScannerTest.java @@ -42,8 +42,7 @@ public OperationAction getOperationType() { } }; - private final AsyncAnnotationChannelService asyncAnnotationChannelService = - mock(AsyncAnnotationChannelService.class); + private final AsyncAnnotationChannelService asyncAnnotationChannelService = mock(); AsyncAnnotationClassLevelChannelsScanner channelScanner = new AsyncAnnotationClassLevelChannelsScanner<>(asyncAnnotationProvider, asyncAnnotationChannelService); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/AsyncAnnotationMethodLevelChannelsScannerTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/AsyncAnnotationMethodLevelChannelsScannerTest.java index 8517de508..153760519 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/AsyncAnnotationMethodLevelChannelsScannerTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/AsyncAnnotationMethodLevelChannelsScannerTest.java @@ -44,8 +44,7 @@ public OperationAction getOperationType() { }; private final AsyncAnnotationMessageService asyncAnnotationMessageService = mock(AsyncAnnotationMessageService.class); - private final AsyncAnnotationChannelService asyncAnnotationChannelService = - mock(AsyncAnnotationChannelService.class); + private final AsyncAnnotationChannelService asyncAnnotationChannelService = mock(); AsyncAnnotationMethodLevelChannelsScanner channelScanner = new AsyncAnnotationMethodLevelChannelsScanner<>(asyncAnnotationProvider, asyncAnnotationChannelService); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationClassLevelChannelsScannerIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationClassLevelChannelsScannerIntegrationTest.java index b6f3aec57..3aad5d309 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationClassLevelChannelsScannerIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationClassLevelChannelsScannerIntegrationTest.java @@ -15,9 +15,9 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.components.DefaultComponentsService; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.DefaultSchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.messages.DefaultMessagesService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; +import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingFactory; import io.github.springwolf.core.asyncapi.scanners.common.channel.SpringAnnotationChannelService; import io.github.springwolf.core.asyncapi.scanners.common.headers.AsyncHeadersNotDocumented; @@ -29,9 +29,14 @@ import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.TypeExtractor; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.DefaultSchemasService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.DefaultSchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.oas.annotations.Hidden; import lombok.Data; @@ -57,6 +62,8 @@ classes = { SpringAnnotationClassLevelChannelsScannerIntegrationTest.TestBindingFactory.class, DefaultComponentsService.class, + DefaultSchemasService.class, + DefaultMessagesService.class, SwaggerSchemaService.class, SwaggerSchemaMapper.class, PayloadMethodParameterService.class, @@ -69,7 +76,7 @@ SchemaWalkerProvider.class, ExampleJsonValueGenerator.class, SpringwolfConfigProperties.class, - ModelConvertersProvider.class + ModelConvertersRegisterer.class }) class SpringAnnotationClassLevelChannelsScannerIntegrationTest { @@ -85,6 +92,12 @@ class SpringAnnotationClassLevelChannelsScannerIntegrationTest { @Autowired ComponentsService componentsService; + @Autowired + MessagesService messagesService; + + @Autowired + SchemasService schemasService; + private SpringAnnotationClassLevelChannelsScanner scanner; @BeforeEach @@ -97,7 +110,8 @@ void setUp() { new AsyncHeadersNotDocumented(), payloadMethodService, headerClassExtractor, - componentsService), + messagesService, + schemasService), new SpringAnnotationChannelService<>(this.bindingFactory)); } @@ -290,23 +304,23 @@ static class TestBindingFactory implements BindingFactory { Map.of(CHANNEL_ID, new TestBindingFactory.TestOperationBinding()); @Override - public String getChannelName(TestClassListener annotation) { + public String getChannelName(BindingContext bindingContext) { return CHANNEL; } @Override - public Map buildChannelBinding(TestClassListener annotation) { + public Map buildChannelBinding(BindingContext bindingContext) { return defaultChannelBinding; } @Override - public Map buildOperationBinding(TestClassListener annotation) { + public Map buildOperationBinding(BindingContext bindingContext) { return defaultOperationBinding; } @Override public Map buildMessageBinding( - TestClassListener annotation, SchemaObject headerSchema) { + BindingContext bindingContext, SchemaObject headerSchema) { return defaultMessageBinding; } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationClassLevelChannelsScannerTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationClassLevelChannelsScannerTest.java index 211d3f787..ac40c4d13 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationClassLevelChannelsScannerTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationClassLevelChannelsScannerTest.java @@ -25,10 +25,8 @@ class SpringAnnotationClassLevelChannelsScannerTest { - private final SpringAnnotationMessagesService springAnnotationMessagesService = - mock(SpringAnnotationMessagesService.class); - private final SpringAnnotationChannelService springAnnotationChannelService = - mock(SpringAnnotationChannelService.class); + private final SpringAnnotationMessagesService springAnnotationMessagesService = mock(); + private final SpringAnnotationChannelService springAnnotationChannelService = mock(); SpringAnnotationClassLevelChannelsScanner scanner = new SpringAnnotationClassLevelChannelsScanner<>( TestClassListener.class, diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationMethodLevelChannelsScannerIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationMethodLevelChannelsScannerIntegrationTest.java index be2c0faa4..c1e6a1ec4 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationMethodLevelChannelsScannerIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationMethodLevelChannelsScannerIntegrationTest.java @@ -15,9 +15,9 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.components.DefaultComponentsService; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.DefaultSchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.messages.DefaultMessagesService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; +import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingFactory; import io.github.springwolf.core.asyncapi.scanners.common.channel.SpringAnnotationChannelService; import io.github.springwolf.core.asyncapi.scanners.common.headers.AsyncHeadersNotDocumented; @@ -29,9 +29,14 @@ import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.TypeExtractor; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.DefaultSchemasService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.DefaultSchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.oas.annotations.Hidden; import lombok.Data; @@ -59,6 +64,8 @@ classes = { SpringAnnotationMethodLevelChannelsScannerIntegrationTest.TestBindingFactory.class, DefaultComponentsService.class, + DefaultSchemasService.class, + DefaultMessagesService.class, SwaggerSchemaService.class, SwaggerSchemaMapper.class, PayloadMethodParameterService.class, @@ -71,7 +78,7 @@ SchemaWalkerProvider.class, ExampleJsonValueGenerator.class, SpringwolfConfigProperties.class, - ModelConvertersProvider.class + ModelConvertersRegisterer.class }) class SpringAnnotationMethodLevelChannelsScannerIntegrationTest { @Autowired @@ -86,6 +93,12 @@ class SpringAnnotationMethodLevelChannelsScannerIntegrationTest { @Autowired ComponentsService componentsService; + @Autowired + MessagesService messagesService; + + @Autowired + SchemasService schemasService; + private SpringAnnotationMethodLevelChannelsScanner scanner; @BeforeEach @@ -96,7 +109,7 @@ void setUp() { headerClassExtractor, new SpringAnnotationChannelService<>(bindingFactory), new SpringAnnotationMessageService<>( - bindingFactory, new AsyncHeadersNotDocumented(), componentsService)); + bindingFactory, new AsyncHeadersNotDocumented(), messagesService, schemasService)); } @Nested @@ -310,23 +323,23 @@ static class TestBindingFactory implements BindingFactory { Map.of(CHANNEL_ID, new TestBindingFactory.TestOperationBinding()); @Override - public String getChannelName(TestChannelListener annotation) { + public String getChannelName(BindingContext bindingContext) { return CHANNEL; } @Override - public Map buildChannelBinding(TestChannelListener annotation) { + public Map buildChannelBinding(BindingContext bindingContext) { return defaultChannelBinding; } @Override - public Map buildOperationBinding(TestChannelListener annotation) { + public Map buildOperationBinding(BindingContext bindingContext) { return defaultOperationBinding; } @Override public Map buildMessageBinding( - TestChannelListener annotation, SchemaObject headerSchema) { + BindingContext bindingContext, SchemaObject headerSchema) { return defaultMessageBinding; } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationMethodLevelChannelsScannerTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationMethodLevelChannelsScannerTest.java index 17c8f3971..3ea19bc05 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationMethodLevelChannelsScannerTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/channels/annotations/SpringAnnotationMethodLevelChannelsScannerTest.java @@ -25,10 +25,8 @@ class SpringAnnotationMethodLevelChannelsScannerTest { private final PayloadMethodService payloadMethodService = mock(); private final HeaderClassExtractor headerClassExtractor = mock(HeaderClassExtractor.class); - private final SpringAnnotationMessageService springAnnotationMessageService = - mock(SpringAnnotationMessageService.class); - private final SpringAnnotationChannelService springAnnotationChannelService = - mock(SpringAnnotationChannelService.class); + private final SpringAnnotationMessageService springAnnotationMessageService = mock(); + private final SpringAnnotationChannelService springAnnotationChannelService = mock(); SpringAnnotationMethodLevelChannelsScanner scanner = new SpringAnnotationMethodLevelChannelsScanner<>( TestListener.class, payloadMethodService, diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/channel/AsyncAnnotationChannelServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/channel/AsyncAnnotationChannelServiceTest.java index cb670e65e..5b8db6e36 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/channel/AsyncAnnotationChannelServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/channel/AsyncAnnotationChannelServiceTest.java @@ -64,8 +64,7 @@ public OperationAction getOperationType() { private final AsyncAnnotationMessageService asyncAnnotationMessageService = mock(AsyncAnnotationMessageService.class); - private final AsyncAnnotationOperationService asyncAnnotationOperationService = - mock(AsyncAnnotationOperationService.class); + private final AsyncAnnotationOperationService asyncAnnotationOperationService = mock(); private final ChannelBindingProcessor channelBindingProcessor = mock(ChannelBindingProcessor.class); private final List channelBindingProcessors = List.of(channelBindingProcessor); private final StringValueResolver stringValueResolver = mock(StringValueResolver.class); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractorIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractorIntegrationTest.java index 8a1e1e993..5b6ee5eab 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractorIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractorIntegrationTest.java @@ -5,10 +5,10 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaType; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; import io.github.springwolf.core.asyncapi.schemas.converters.SchemaTitleModelConverter; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.core.converter.ModelConverters; import org.junit.jupiter.api.AfterAll; @@ -33,7 +33,7 @@ class HeaderClassExtractorIntegrationTest { configProperties, List.of(), new SwaggerSchemaMapper(configProperties), - new ModelConvertersProvider(configProperties, List.of(titleModelConverter), List.of())); + new ModelConvertersRegisterer(configProperties, List.of(titleModelConverter), List.of())); private final HeaderClassExtractor headerClassExtractor = new HeaderClassExtractor(schemaService); private final PayloadSchemaObject payloadSchemaName = new PayloadSchemaObject( @@ -127,7 +127,7 @@ void getHeaderWithNestedHeaderAnnotation() throws Exception { assertThat(result).isEqualTo(AsyncHeadersNotDocumented.NOT_DOCUMENTED); // currently not supported } - public static class TestClass { + static class TestClass { public void consumeWithoutHeadersAnnotation(String simpleValue) {} diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractorTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractorTest.java index 216fd30e2..a32bb5eeb 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractorTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/headers/HeaderClassExtractorTest.java @@ -5,8 +5,8 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaType; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; import io.github.springwolf.core.asyncapi.schemas.converters.SchemaTitleModelConverter; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; import io.swagger.v3.core.converter.ModelConverters; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/message/AsyncAnnotationMessageServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/message/AsyncAnnotationMessageServiceTest.java index 3f4446ca9..cce83892a 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/message/AsyncAnnotationMessageServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/message/AsyncAnnotationMessageServiceTest.java @@ -8,10 +8,11 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; import io.github.springwolf.core.asyncapi.annotations.AsyncMessage; import io.github.springwolf.core.asyncapi.annotations.AsyncOperation; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.bindings.messages.MessageBindingProcessor; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadAsyncOperationService; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.swagger.v3.oas.annotations.media.Schema; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; @@ -34,11 +35,16 @@ class AsyncAnnotationMessageServiceTest { private final PayloadAsyncOperationService payloadAsyncOperationService = mock(PayloadAsyncOperationService.class); - private final ComponentsService componentsService = mock(ComponentsService.class); + private final MessagesService messagesService = mock(MessagesService.class); + private final SchemasService schemasService = mock(SchemasService.class); private final MessageBindingProcessor messageBindingProcessor = mock(MessageBindingProcessor.class); private final StringValueResolver stringValueResolver = mock(StringValueResolver.class); AsyncAnnotationMessageService asyncAnnotationMessageService = new AsyncAnnotationMessageService( - payloadAsyncOperationService, componentsService, List.of(messageBindingProcessor), stringValueResolver); + payloadAsyncOperationService, + messagesService, + schemasService, + List.of(messageBindingProcessor), + stringValueResolver); private final PayloadSchemaObject payloadSchema = new PayloadSchemaObject("full.name", "name", null); @@ -48,7 +54,7 @@ void setUp() { .when(stringValueResolver) .resolveStringValue(any()); - when(componentsService.registerSchema(any())).thenReturn("headerSchemaName"); + when(schemasService.registerSchema(any())).thenReturn("headerSchemaName"); when(messageBindingProcessor.process(any())).thenReturn(Optional.empty()); when(payloadAsyncOperationService.extractSchema(any(), any())).thenReturn(payloadSchema); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/AsyncAnnotationOperationServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/AsyncAnnotationOperationServiceTest.java index bc50684a9..0456480ef 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/AsyncAnnotationOperationServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/AsyncAnnotationOperationServiceTest.java @@ -35,8 +35,7 @@ import static org.mockito.Mockito.when; class AsyncAnnotationOperationServiceTest { - private final AsyncAnnotationProvider asyncAnnotationProvider = - mock(AsyncAnnotationProvider.class); + private final AsyncAnnotationProvider asyncAnnotationProvider = mock(); private final OperationBindingProcessor operationBindingProcessor = mock(OperationBindingProcessor.class); private final List operationBindingProcessors = List.of(operationBindingProcessor); private final AsyncAnnotationMessageService asyncAnnotationMessageService = diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/SpringAnnotationOperationServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/SpringAnnotationOperationServiceTest.java index e11b9ccbc..38c98b401 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/SpringAnnotationOperationServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/SpringAnnotationOperationServiceTest.java @@ -30,9 +30,8 @@ import static org.mockito.Mockito.when; class SpringAnnotationOperationServiceTest { - private final BindingFactory bindingFactory = mock(BindingFactory.class); - private final SpringAnnotationMessageService springAnnotationMessageService = - mock(SpringAnnotationMessageService.class); + private final BindingFactory bindingFactory = mock(); + private final SpringAnnotationMessageService springAnnotationMessageService = mock(); SpringAnnotationOperationService springAnnotationOperationService = new SpringAnnotationOperationService<>(bindingFactory, springAnnotationMessageService); @@ -43,8 +42,8 @@ class SpringAnnotationOperationServiceTest { @BeforeEach void setUp() { // when - when(bindingFactory.getChannelId(any(BindingContext.class))).thenReturn(CHANNEL_ID); - doReturn(defaultOperationBinding).when(bindingFactory).buildOperationBinding(any(BindingContext.class)); + when(bindingFactory.getChannelId(any())).thenReturn(CHANNEL_ID); + doReturn(defaultOperationBinding).when(bindingFactory).buildOperationBinding(any()); } @Test @@ -53,7 +52,7 @@ void scan_componentHasTestListenerMethods() throws Exception { Method method = ClassWithTestListenerAnnotation.class.getDeclaredMethod("methodWithAnnotation", String.class); MethodAndAnnotation methodAndAnnotation = new MethodAndAnnotation<>(method, method.getAnnotation(TestMethodListener.class)); - BindingContext bindingContext = BindingContext.ofAnnotatedMethod( + BindingContext bindingContext = BindingContext.ofAnnotatedMethod( ClassWithTestListenerAnnotation.class, method, methodAndAnnotation.annotation()); PayloadSchemaObject payloadSchemaName = new PayloadSchemaObject("name", "full.name", null); SchemaObject headerSchema = new SchemaObject(); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/SpringAnnotationOperationsServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/SpringAnnotationOperationsServiceTest.java index ebaa002d0..2bc3ee52b 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/SpringAnnotationOperationsServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/operation/SpringAnnotationOperationsServiceTest.java @@ -24,9 +24,8 @@ import static org.mockito.Mockito.when; class SpringAnnotationOperationsServiceTest { - private final BindingFactory bindingFactory = mock(BindingFactory.class); - private final SpringAnnotationMessagesService springAnnotationMessageService = - mock(SpringAnnotationMessagesService.class); + private final BindingFactory bindingFactory = mock(); + private final SpringAnnotationMessagesService springAnnotationMessageService = mock(); SpringAnnotationOperationsService springAnnotationOperationsService = new SpringAnnotationOperationsService<>(bindingFactory, springAnnotationMessageService); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadAsyncOperationServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadAsyncOperationServiceTest.java index f157527b4..8b3e2fcce 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadAsyncOperationServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadAsyncOperationServiceTest.java @@ -5,9 +5,9 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.core.asyncapi.annotations.AsyncMessage; import io.github.springwolf.core.asyncapi.annotations.AsyncOperation; -import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -26,15 +26,14 @@ class PayloadAsyncOperationServiceTest { private PayloadExtractor payloadExtractor = mock(PayloadExtractor.class); - private ComponentsService componentsService = mock(ComponentsService.class); + private SchemasService schemasService = mock(SchemasService.class); private SpringwolfConfigProperties properties = mock(SpringwolfConfigProperties.class); - private PayloadService payloadService; private PayloadAsyncOperationService payloadAsyncOperationService; @BeforeEach void setUp() { - payloadService = new PayloadService(componentsService, properties); + PayloadService payloadService = new PayloadService(schemasService, properties); payloadAsyncOperationService = new PayloadAsyncOperationService(payloadExtractor, payloadService); } @@ -49,10 +48,10 @@ void shouldUsePayloadFromAsyncOperationAnnotation() { when(asyncOperation.message()).thenReturn(asyncMessage); String schemaName = "my-schema-name"; - when(componentsService.getSchemaName(String.class)).thenReturn(schemaName); + when(schemasService.getSchemaName(String.class)).thenReturn(schemaName); ComponentSchema schemaObject = ComponentSchema.of(SchemaObject.builder().build()); - when(componentsService.resolvePayloadSchema(eq(String.class), any())).thenReturn(schemaObject); + when(schemasService.registerType(eq(String.class), any())).thenReturn(schemaObject); // when var result = payloadAsyncOperationService.extractSchema(asyncOperation, null); @@ -76,10 +75,10 @@ void shouldExtractPayloadFromMethodWithAnnotation() { when(payloadExtractor.extractFrom(method)).thenReturn(Optional.of(String.class)); String schemaName = "my-schema-name"; - when(componentsService.getSchemaName(String.class)).thenReturn(schemaName); + when(schemasService.getSchemaName(String.class)).thenReturn(schemaName); ComponentSchema schemaObject = ComponentSchema.of(SchemaObject.builder().build()); - when(componentsService.resolvePayloadSchema(eq(String.class), any())).thenReturn(schemaObject); + when(schemasService.registerType(eq(String.class), any())).thenReturn(schemaObject); // when var result = payloadAsyncOperationService.extractSchema(asyncOperation, method); @@ -111,6 +110,6 @@ void shouldReturnPayloadNotUsed() { SchemaObject schema = result.schema().getSchema(); assertThat(schema.getTitle()).isEqualTo("PayloadNotUsed"); assertThat(schema.getDescription()).isEqualTo("No payload specified"); - verify(componentsService).registerSchema(PAYLOAD_NOT_USED.schema().getSchema()); + verify(schemasService).registerSchema(PAYLOAD_NOT_USED.schema().getSchema()); } } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadMethodParameterServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadMethodParameterServiceTest.java index 9e865627f..99d19bba4 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadMethodParameterServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadMethodParameterServiceTest.java @@ -3,9 +3,9 @@ import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; -import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,16 +21,15 @@ class PayloadMethodParameterServiceTest { private PayloadExtractor payloadExtractor = mock(PayloadExtractor.class); - private ComponentsService componentsService = mock(ComponentsService.class); + private SchemasService schemasService = mock(SchemasService.class); private SpringwolfConfigProperties.ConfigDocket docket = mock(SpringwolfConfigProperties.ConfigDocket.class); private SpringwolfConfigProperties properties = mock(SpringwolfConfigProperties.class); - private PayloadService payloadService; private PayloadMethodParameterService payloadMethodParameterService; @BeforeEach void setUp() { - payloadService = new PayloadService(componentsService, properties); + PayloadService payloadService = new PayloadService(schemasService, properties); payloadMethodParameterService = new PayloadMethodParameterService(payloadExtractor, payloadService); } @@ -44,10 +43,10 @@ void shouldExtractPayloadFromMethod() { when(payloadExtractor.extractFrom(method)).thenReturn(Optional.of(String.class)); String schemaName = "my-schema-name"; - when(componentsService.getSchemaName(String.class)).thenReturn(schemaName); + when(schemasService.getSchemaName(String.class)).thenReturn(schemaName); ComponentSchema schemaObject = ComponentSchema.of(SchemaObject.builder().build()); - when(componentsService.resolvePayloadSchema(eq(String.class), any())).thenReturn(schemaObject); + when(schemasService.registerType(eq(String.class), any())).thenReturn(schemaObject); // when var result = payloadMethodParameterService.extractSchema(method); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadMethodReturnServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadMethodReturnServiceTest.java index c62ba644f..90fa6f937 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadMethodReturnServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/PayloadMethodReturnServiceTest.java @@ -3,8 +3,8 @@ import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; -import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -19,16 +19,15 @@ import static org.mockito.Mockito.when; class PayloadMethodReturnServiceTest { - private ComponentsService componentsService = mock(ComponentsService.class); + private SchemasService schemasService = mock(SchemasService.class); private SpringwolfConfigProperties.ConfigDocket docket = mock(SpringwolfConfigProperties.ConfigDocket.class); private SpringwolfConfigProperties properties = mock(SpringwolfConfigProperties.class); - private PayloadService payloadService; private PayloadMethodReturnService payloadMethodReturnService; @BeforeEach void setUp() { - payloadService = new PayloadService(componentsService, properties); + PayloadService payloadService = new PayloadService(schemasService, properties); payloadMethodReturnService = new PayloadMethodReturnService(payloadService); } @@ -42,10 +41,10 @@ void shouldExtractPayloadFromMethod() { doReturn(String.class).when(method).getReturnType(); String schemaName = "my-schema-name"; - when(componentsService.getSchemaName(String.class)).thenReturn(schemaName); + when(schemasService.getSchemaName(String.class)).thenReturn(schemaName); ComponentSchema schemaObject = ComponentSchema.of(SchemaObject.builder().build()); - when(componentsService.resolvePayloadSchema(eq(String.class), any())).thenReturn(schemaObject); + when(schemasService.registerType(eq(String.class), any())).thenReturn(schemaObject); // when var result = payloadMethodReturnService.extractSchema(method); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/internal/PayloadServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/internal/PayloadServiceTest.java index e6fc20b8b..330b0916b 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/internal/PayloadServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/common/payload/internal/PayloadServiceTest.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.core.asyncapi.scanners.common.payload.internal; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import org.junit.jupiter.api.Test; @@ -11,10 +11,10 @@ class PayloadServiceTest { - private ComponentsService componentsService = mock(ComponentsService.class); + private SchemasService schemasService = mock(SchemasService.class); private SpringwolfConfigProperties.ConfigDocket docket = mock(SpringwolfConfigProperties.ConfigDocket.class); private SpringwolfConfigProperties properties = mock(SpringwolfConfigProperties.class); - private PayloadService payloadService = new PayloadService(componentsService, properties); + private PayloadService payloadService = new PayloadService(schemasService, properties); @Test void shouldExtractSchemaForInteger() { @@ -23,7 +23,7 @@ void shouldExtractSchemaForInteger() { when(docket.getDefaultContentType()).thenReturn("application/json"); String schemaName = "my-schema-name"; - when(componentsService.getSchemaName(Integer.class)).thenReturn(schemaName); + when(schemasService.getSchemaName(Integer.class)).thenReturn(schemaName); // when var result = payloadService.buildSchema(Integer.class); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationsInClassScannerAdapterTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationsInClassScannerAdapterTest.java index 939d5fe42..df67a2ed5 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationsInClassScannerAdapterTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/OperationsInClassScannerAdapterTest.java @@ -5,7 +5,7 @@ import io.github.springwolf.core.asyncapi.scanners.classes.ClassScanner; import org.junit.jupiter.api.Test; -import java.util.Map; +import java.util.List; import java.util.Set; import java.util.stream.Stream; @@ -25,7 +25,7 @@ class OperationsInClassScannerAdapterTest { @Test void noClassFoundTest() { // when - Map operations = operationsInClassScannerAdapter.scan(); + List operations = operationsInClassScannerAdapter.scan(); // then assertThat(operations).isEmpty(); @@ -40,15 +40,14 @@ void processClassTest() { when(classProcessor.scan(any())).thenReturn(Stream.of(operation1, operation2)); // when - Map operations = operationsInClassScannerAdapter.scan(); + List operations = operationsInClassScannerAdapter.scan(); // then - assertThat(operations) - .containsExactlyInAnyOrderEntriesOf(Map.of("operation1", operation1, "operation2", operation2)); + assertThat(operations).containsExactlyInAnyOrder(operation1, operation2); } @Test - void sameOperationsAreMergedTest() { + void sameOperationsAreReturnedUnmergedTest() { // given when(classScanner.scan()).thenReturn(Set.of(String.class)); Operation operation1 = @@ -58,10 +57,10 @@ void sameOperationsAreMergedTest() { when(classProcessor.scan(any())).thenReturn(Stream.of(operation1, operation2)); // when - Map operations = operationsInClassScannerAdapter.scan(); + List operations = operationsInClassScannerAdapter.scan(); // then - assertThat(operations).hasSize(1); + assertThat(operations).containsExactly(operation1, operation2); } @Test @@ -71,7 +70,7 @@ void processEmptyClassTest() { when(classProcessor.scan(any())).thenReturn(Stream.of()); // when - Map operations = operationsInClassScannerAdapter.scan(); + List operations = operationsInClassScannerAdapter.scan(); // then assertThat(operations).isEmpty(); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/AsyncAnnotationClassLevelOperationsScannerTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/AsyncAnnotationClassLevelOperationsScannerTest.java index a5d6d7e6c..62185fb47 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/AsyncAnnotationClassLevelOperationsScannerTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/AsyncAnnotationClassLevelOperationsScannerTest.java @@ -41,8 +41,7 @@ public OperationAction getOperationType() { return OperationAction.SEND; } }; - private final AsyncAnnotationOperationService asyncAnnotationOperationService = - mock(AsyncAnnotationOperationService.class); + private final AsyncAnnotationOperationService asyncAnnotationOperationService = mock(); private final OperationCustomizer operationCustomizer = mock(OperationCustomizer.class); private final AsyncAnnotationClassLevelOperationsScanner operationsScanner = diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/AsyncAnnotationMethodLevelOperationsScannerTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/AsyncAnnotationMethodLevelOperationsScannerTest.java index 5786dcf95..3e6720f1a 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/AsyncAnnotationMethodLevelOperationsScannerTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/AsyncAnnotationMethodLevelOperationsScannerTest.java @@ -44,8 +44,7 @@ public OperationAction getOperationType() { private final OperationCustomizer operationCustomizer = mock(OperationCustomizer.class); private final StringValueResolverProxy stringValueResolver = mock(StringValueResolverProxy.class); - private final AsyncAnnotationOperationService asyncAnnotationOperationService = - mock(AsyncAnnotationOperationService.class); + private final AsyncAnnotationOperationService asyncAnnotationOperationService = mock(); private final AsyncAnnotationMethodLevelOperationsScanner operationsScanner = new AsyncAnnotationMethodLevelOperationsScanner<>( diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/SpringAnnotationClassLevelOperationsScannerTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/SpringAnnotationClassLevelOperationsScannerTest.java index ee587fe22..5102b84fe 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/SpringAnnotationClassLevelOperationsScannerTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/SpringAnnotationClassLevelOperationsScannerTest.java @@ -20,8 +20,7 @@ class SpringAnnotationClassLevelOperationsScannerTest { private final OperationCustomizer operationCustomizer = mock(OperationCustomizer.class); - private final SpringAnnotationOperationsService springAnnotationOperationsService = - mock(SpringAnnotationOperationsService.class); + private final SpringAnnotationOperationsService springAnnotationOperationsService = mock(); SpringAnnotationClassLevelOperationsScanner scanner = new SpringAnnotationClassLevelOperationsScanner<>( TestClassListener.class, diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/SpringAnnotationMethodLevelOperationsScannerTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/SpringAnnotationMethodLevelOperationsScannerTest.java index 7b937d784..aded60e0c 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/SpringAnnotationMethodLevelOperationsScannerTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/scanners/operations/annotations/SpringAnnotationMethodLevelOperationsScannerTest.java @@ -23,8 +23,7 @@ class SpringAnnotationMethodLevelOperationsScannerTest { private final PayloadMethodParameterService payloadMethodParameterService = mock(); private final HeaderClassExtractor headerClassExtractor = mock(HeaderClassExtractor.class); private final OperationCustomizer operationCustomizer = mock(OperationCustomizer.class); - private final SpringAnnotationOperationService springAnnotationOperationService = - mock(SpringAnnotationOperationService.class); + private final SpringAnnotationOperationService springAnnotationOperationService = mock(); SpringAnnotationMethodLevelOperationsScanner scanner = new SpringAnnotationMethodLevelOperationsScanner<>( TestMethodListener.class, diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/ModelConvertersProviderTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/converters/ModelConvertersRegistererTest.java similarity index 84% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/ModelConvertersProviderTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/converters/ModelConvertersRegistererTest.java index 774ff8de1..7e186505e 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/ModelConvertersProviderTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/converters/ModelConvertersRegistererTest.java @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.schemas; +package io.github.springwolf.core.asyncapi.schemas.converters; +import io.github.springwolf.core.asyncapi.schemas.schema.SpringwolfTypeNameResolver; import io.github.springwolf.core.configuration.properties.PayloadSchemaFormat; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.core.converter.ModelConverter; @@ -17,13 +18,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -class ModelConvertersProviderTest { +class ModelConvertersRegistererTest { @ParameterizedTest @ValueSource(booleans = {true, false}) void createsSpringwolfTypeNameResolverWithUseFqnSetting(boolean useFqn) { // given - ModelConvertersProvider provider = new ModelConvertersProvider( + ModelConvertersRegisterer provider = new ModelConvertersRegisterer( configProperties(useFqn, PayloadSchemaFormat.ASYNCAPI_V3), List.of(), List.of()); // when @@ -39,8 +40,8 @@ void createsSpringwolfTypeNameResolverWithUseFqnSetting(boolean useFqn) { void createsModelConvertersWithExpectedOpenapi31Flag( PayloadSchemaFormat payloadSchemaFormat, boolean expectedOpenapi31) { // given - ModelConvertersProvider provider = - new ModelConvertersProvider(configProperties(true, payloadSchemaFormat), List.of(), List.of()); + ModelConvertersRegisterer provider = + new ModelConvertersRegisterer(configProperties(true, payloadSchemaFormat), List.of(), List.of()); // when ModelConverters modelConverters = provider.getModelConverters(); @@ -55,7 +56,7 @@ void createsModelConvertersWithExpectedOpenapi31Flag( void addsExternalModelConvertersToTheCreatedModelConverters() { // given ModelConverter externalModelConverter = mock(ModelConverter.class); - ModelConvertersProvider provider = new ModelConvertersProvider( + ModelConvertersRegisterer provider = new ModelConvertersRegisterer( configProperties(false, PayloadSchemaFormat.OPENAPI_V3_1), List.of(externalModelConverter), List.of()); // when diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultComponentsServiceIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/DefaultSchemasServiceTest.java similarity index 88% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultComponentsServiceIntegrationTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/DefaultSchemasServiceTest.java index 850edd90e..d26026ec0 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/DefaultComponentsServiceIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/DefaultSchemasServiceTest.java @@ -1,13 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components; +package io.github.springwolf.core.asyncapi.schemas.schema; import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaType; import io.github.springwolf.core.asyncapi.annotations.AsyncApiPayload; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.DefaultSchemasService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; import io.github.springwolf.core.asyncapi.schemas.converters.SchemaTitleModelConverter; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.oas.annotations.media.ArraySchema; @@ -25,7 +25,7 @@ import static org.assertj.core.api.Assertions.assertThat; -class DefaultComponentsServiceIntegrationTest { +class DefaultSchemasServiceTest { private final String CONTENT_TYPE_APPLICATION_JSON = "does-not-matter"; private final SpringwolfConfigProperties configProperties = new SpringwolfConfigProperties(); @@ -36,17 +36,17 @@ class DefaultComponentsServiceIntegrationTest { configProperties, List.of(), new SwaggerSchemaMapper(configProperties), - new ModelConvertersProvider(configProperties, List.of(titleModelConverter), List.of())); + new ModelConvertersRegisterer(configProperties, List.of(titleModelConverter), List.of())); - private final ComponentsService componentsService = new DefaultComponentsService(schemaService); + private final SchemasService schemasService = new DefaultSchemasService(schemaService); @Nested class AllSchemaFields { @Test void getStringSchemas() { - componentsService.resolvePayloadSchema(StringFoo.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(StringFoo.class, CONTENT_TYPE_APPLICATION_JSON); - Map schemas = componentsService.getSchemas(); + Map schemas = schemasService.getSchemas(); assertThat(schemas).hasSize(1); ComponentSchema componentSchema = schemas.get(StringFoo.class.getName().replace("$", ".")); @@ -87,9 +87,9 @@ void getOpenApi31NullTypeSchemas() { @Test void getArraySchemas() { - componentsService.resolvePayloadSchema(ArrayFoo.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(ArrayFoo.class, CONTENT_TYPE_APPLICATION_JSON); - Map schemas = componentsService.getSchemas(); + Map schemas = schemasService.getSchemas(); assertThat(schemas).hasSize(1); ComponentSchema componentSchema = schemas.get(ArrayFoo.class.getName().replace("$", ".")); @@ -117,9 +117,9 @@ void getArraySchemas() { @Test void getRefSchemas() { - componentsService.resolvePayloadSchema(RefFoo.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(RefFoo.class, CONTENT_TYPE_APPLICATION_JSON); - Map schemas = componentsService.getSchemas(); + Map schemas = schemasService.getSchemas(); assertThat(schemas).hasSize(1); ComponentSchema componentSchema = schemas.get(RefFoo.class.getName().replace("$", ".")); @@ -149,9 +149,9 @@ void getRefSchemas() { @Test void getNumberSchemas() { - componentsService.resolvePayloadSchema(NumberFoo.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(NumberFoo.class, CONTENT_TYPE_APPLICATION_JSON); - Map schemas = componentsService.getSchemas(); + Map schemas = schemasService.getSchemas(); assertThat(schemas).hasSize(1); ComponentSchema componentSchema = schemas.get(NumberFoo.class.getName().replace("$", ".")); @@ -175,9 +175,9 @@ void getNumberSchemas() { @Test void getNotSupportedSchemas() { - componentsService.resolvePayloadSchema(NotSupportedFoo.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(NotSupportedFoo.class, CONTENT_TYPE_APPLICATION_JSON); - Map schemas = componentsService.getSchemas(); + Map schemas = schemasService.getSchemas(); assertThat(schemas).hasSize(1); ComponentSchema componentSchema = schemas.get(NotSupportedFoo.class.getName().replace("$", ".")); @@ -269,9 +269,9 @@ private static class NotSupportedFoo { class AsyncApiPayloadTest { @Test void stringEnvelopTest() { - componentsService.resolvePayloadSchema(StringEnvelop.class, CONTENT_TYPE_APPLICATION_JSON); + schemasService.registerType(StringEnvelop.class, CONTENT_TYPE_APPLICATION_JSON); - Map schemas = componentsService.getSchemas(); + Map schemas = schemasService.getSchemas(); assertThat(schemas).hasSize(1); ComponentSchema componentSchema = @@ -286,10 +286,10 @@ void stringEnvelopTest() { @Test void illegalEnvelopTest() { - componentsService.resolvePayloadSchema( + schemasService.registerType( EnvelopWithMultipleAsyncApiPayloadAnnotations.class, CONTENT_TYPE_APPLICATION_JSON); - Map schemas = componentsService.getSchemas(); + Map schemas = schemasService.getSchemas(); assertThat(schemas).hasSize(1); // fallback to EnvelopWithMultipleAsyncApiPayloadAnnotations, because it has multiple AsyncApiPayload diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/SwaggerSchemaMapperTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaMapperTest.java similarity index 99% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/SwaggerSchemaMapperTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaMapperTest.java index bf9217c9e..943668ba4 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/SwaggerSchemaMapperTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaMapperTest.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components; +package io.github.springwolf.core.asyncapi.schemas.schema; import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; import io.github.springwolf.asyncapi.v3.model.schema.MultiFormatSchema; @@ -7,7 +7,6 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; import io.github.springwolf.asyncapi.v3.model.schema.SchemaType; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; import io.github.springwolf.core.configuration.properties.PayloadSchemaFormat; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.oas.models.ExternalDocumentation; diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaServicePostProcessorExecutionTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaServicePostProcessorExecutionTest.java similarity index 86% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaServicePostProcessorExecutionTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaServicePostProcessorExecutionTest.java index af494aa8e..991d9bf18 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaServicePostProcessorExecutionTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaServicePostProcessorExecutionTest.java @@ -1,12 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.schemas; +package io.github.springwolf.core.asyncapi.schemas.schema; import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.DefaultSchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; -import io.github.springwolf.core.asyncapi.components.postprocessors.AvroSchemaPostProcessor; -import io.github.springwolf.core.asyncapi.components.postprocessors.ExampleGeneratorPostProcessor; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.DefaultSchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.postprocessors.AvroSchemaPostProcessor; +import io.github.springwolf.core.asyncapi.schemas.schema.postprocessors.ExampleGeneratorPostProcessor; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import org.apache.avro.Schema; import org.apache.avro.specific.SpecificData; @@ -34,7 +35,7 @@ class SwaggerSchemaServicePostProcessorExecutionTest { new ExampleGeneratorPostProcessor(new SchemaWalkerProvider( List.of(new DefaultSchemaWalker<>(new ExampleJsonValueGenerator()))))), new SwaggerSchemaMapper(springwolfConfigProperties), - new ModelConvertersProvider(springwolfConfigProperties, List.of(), List.of())); + new ModelConvertersRegisterer(springwolfConfigProperties, List.of(), List.of())); @Test void happyPath_AvroGamma_having_multiple_AvroDelta() { diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaServiceTest.java similarity index 92% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaServiceTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaServiceTest.java index 7fc612d56..14d592327 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/SwaggerSchemaServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/SwaggerSchemaServiceTest.java @@ -1,10 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.schemas; +package io.github.springwolf.core.asyncapi.schemas.schema; import io.github.springwolf.asyncapi.v3.model.components.ComponentSchema; import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; import io.github.springwolf.asyncapi.v3.model.schema.SchemaType; -import io.github.springwolf.core.asyncapi.components.postprocessors.SchemasPostProcessor; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; +import io.github.springwolf.core.asyncapi.schemas.schema.postprocessors.SchemasPostProcessor; import io.github.springwolf.core.configuration.properties.PayloadSchemaFormat; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.core.converter.AnnotatedType; @@ -53,7 +54,7 @@ void setUp() { configProperties, List.of(schemasPostProcessor, schemasPostProcessor2), new SwaggerSchemaMapper(configProperties), - new ModelConvertersProvider( + new ModelConvertersRegisterer( configProperties, List.of(new ModelConverterNativeClass.Converter()), List.of())); } @@ -72,7 +73,7 @@ void classWithSchemaAnnotationWithAsyncapiSchemaformat() { } @Test - void getDefinitionWithoutFqnClassName() throws Exception { + void getDefinitionWithoutFqnClassName() { // given SpringwolfConfigProperties properties = new SpringwolfConfigProperties(); properties.setUseFqn(false); @@ -81,7 +82,7 @@ void getDefinitionWithoutFqnClassName() throws Exception { properties, List.of(), new SwaggerSchemaMapper(properties), - new ModelConvertersProvider(properties, List.of(), List.of())); + new ModelConvertersRegisterer(properties, List.of(), List.of())); // when Class clazz = @@ -92,7 +93,6 @@ void getDefinitionWithoutFqnClassName() throws Exception { String actualDefinitions = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schemas); // then - System.out.println("Got: " + actualDefinitions); assertThat(actualDefinitions).contains(clazz.getSimpleName()); assertThat(actualDefinitions).doesNotContain(clazz.getCanonicalName()); } @@ -116,7 +116,7 @@ void postProcessorsAreCalledWithOpenapiSchemaformat() { @Test void postProcessorIsSkippedWhenSchemaWasRemoved() { doAnswer(invocationOnMock -> { - Map schemas = invocationOnMock.getArgument(1); + Map schemas = invocationOnMock.getArgument(1); schemas.clear(); return null; }) @@ -153,7 +153,7 @@ void ignoreNonSerializableClassesInOpenApi31() { configProperties, List.of(schemasPostProcessor, schemasPostProcessor2), new SwaggerSchemaMapper(configProperties), - new ModelConvertersProvider( + new ModelConvertersRegisterer( configProperties, List.of(new ModelConverterNativeClass.Converter()), List.of())); // when @@ -165,7 +165,7 @@ void ignoreNonSerializableClassesInOpenApi31() { .isEqualTo( ComponentSchema.of( new SchemaReference( - "#/components/schemas/io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaServiceTest.NonSerializableClass"))); + "#/components/schemas/io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaServiceTest.NonSerializableClass"))); assertThat(resolvedSchemas.referencedSchemas()).isEmpty(); } @@ -212,7 +212,7 @@ private static class ModelConverterActualClass { public static class Converter implements ModelConverter { @Override - public io.swagger.v3.oas.models.media.Schema resolve( + public io.swagger.v3.oas.models.media.Schema resolve( AnnotatedType type, ModelConverterContext context, Iterator chain) { Class rawClass = getRawClass(type); boolean isNativeType = isNativeType(rawClass); @@ -235,7 +235,7 @@ private Class getRawClass(AnnotatedType type) { return javaType != null ? javaType.getRawClass() : null; } - private io.swagger.v3.oas.models.media.Schema proceedWithChain( + private io.swagger.v3.oas.models.media.Schema proceedWithChain( AnnotatedType type, ModelConverterContext context, Iterator chain) { return (chain.hasNext()) ? chain.next().resolve(type, context, chain) : null; } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/formatter/ExampleFormatterTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/formatter/ExampleFormatterTest.java similarity index 94% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/formatter/ExampleFormatterTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/formatter/ExampleFormatterTest.java index 0edadcc48..f4d42880a 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/formatter/ExampleFormatterTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/formatter/ExampleFormatterTest.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.formatter; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.formatter; import org.junit.jupiter.api.Test; diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerJsonIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerJsonIntegrationTest.java similarity index 86% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerJsonIntegrationTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerJsonIntegrationTest.java index 71e61cfa2..97c92203f 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerJsonIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerJsonIntegrationTest.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; import io.github.springwolf.core.fixtures.JsonMapperTestConfiguration; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.BinarySchema; @@ -63,7 +63,7 @@ void shouldNotHandleOtherContentType() { class FromSchema { @Test - void build(TestInfo testInfo) throws Exception { + void build(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); @@ -78,7 +78,7 @@ void failWhenMissingDefinition(TestInfo testInfo) { ObjectSchema compositeSchema = new ObjectSchema(); compositeSchema.setName(testInfo.getDisplayName()); - Schema referenceSchema = new Schema(); + Schema referenceSchema = new Schema<>(); referenceSchema.set$ref("#/components/schemas/Nested"); compositeSchema.addProperty("f", referenceSchema); @@ -90,7 +90,7 @@ void failWhenMissingDefinition(TestInfo testInfo) { @Nested class TestSimpleSchema { @Test - void type_boolean(TestInfo testInfo) throws Exception { + void type_boolean(TestInfo testInfo) { BooleanSchema schema = new BooleanSchema(); schema.setName(testInfo.getDisplayName()); @@ -101,7 +101,7 @@ void type_boolean(TestInfo testInfo) throws Exception { } @Test - void type_boolean_default_set(TestInfo testInfo) throws Exception { + void type_boolean_default_set(TestInfo testInfo) { BooleanSchema schema = new BooleanSchema(); schema.setName(testInfo.getDisplayName()); schema.setDefault(Boolean.FALSE); @@ -113,7 +113,7 @@ void type_boolean_default_set(TestInfo testInfo) throws Exception { } @Test - void type_boolean_example_set(TestInfo testInfo) throws Exception { + void type_boolean_example_set(TestInfo testInfo) { BooleanSchema schema = new BooleanSchema(); schema.setName(testInfo.getDisplayName()); schema.setExample(Boolean.FALSE); @@ -125,7 +125,7 @@ void type_boolean_example_set(TestInfo testInfo) throws Exception { } @Test - void type_integer(TestInfo testInfo) throws Exception { + void type_integer(TestInfo testInfo) { IntegerSchema schema = new IntegerSchema(); schema.setName(testInfo.getDisplayName()); @@ -136,7 +136,7 @@ void type_integer(TestInfo testInfo) throws Exception { } @Test - void type_integer_default_set(TestInfo testInfo) throws Exception { + void type_integer_default_set(TestInfo testInfo) { IntegerSchema schema = new IntegerSchema(); schema.setName(testInfo.getDisplayName()); schema.setDefault(Integer.parseInt("123")); @@ -148,7 +148,7 @@ void type_integer_default_set(TestInfo testInfo) throws Exception { } @Test - void type_integer_example_set(TestInfo testInfo) throws Exception { + void type_integer_example_set(TestInfo testInfo) { IntegerSchema schema = new IntegerSchema(); schema.setName(testInfo.getDisplayName()); schema.setExample(Integer.parseInt("123")); @@ -160,7 +160,7 @@ void type_integer_example_set(TestInfo testInfo) throws Exception { } @Test - void type_integer_format_long(TestInfo testInfo) throws Exception { + void type_integer_format_long(TestInfo testInfo) { IntegerSchema schema = new IntegerSchema(); schema.setName(testInfo.getDisplayName()); schema.setFormat("int64"); @@ -172,7 +172,7 @@ void type_integer_format_long(TestInfo testInfo) throws Exception { } @Test - void type_number_format_float(TestInfo testInfo) throws Exception { + void type_number_format_float(TestInfo testInfo) { Schema schema = new NumberSchema(); schema.setName(testInfo.getDisplayName()); schema.setFormat("float"); @@ -184,7 +184,7 @@ void type_number_format_float(TestInfo testInfo) throws Exception { } @Test - void type_number_format_double(TestInfo testInfo) throws Exception { + void type_number_format_double(TestInfo testInfo) { Schema schema = new NumberSchema(); schema.setName(testInfo.getDisplayName()); schema.setFormat("double"); @@ -196,7 +196,7 @@ void type_number_format_double(TestInfo testInfo) throws Exception { } @Test - void type_number_default_set(TestInfo testInfo) throws Exception { + void type_number_default_set(TestInfo testInfo) { Schema schema = new NumberSchema(); schema.setName(testInfo.getDisplayName()); schema.setDefault(new BigDecimal("123.45")); @@ -208,7 +208,7 @@ void type_number_default_set(TestInfo testInfo) throws Exception { } @Test - void type_number_example_set(TestInfo testInfo) throws Exception { + void type_number_example_set(TestInfo testInfo) { Schema schema = new NumberSchema(); schema.setName(testInfo.getDisplayName()); schema.setExample(new BigDecimal("123.45")); @@ -220,7 +220,7 @@ void type_number_example_set(TestInfo testInfo) throws Exception { } @Test - void type_string(TestInfo testInfo) throws Exception { + void type_string(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); @@ -231,7 +231,7 @@ void type_string(TestInfo testInfo) throws Exception { } @Test - void type_string_default_set(TestInfo testInfo) throws Exception { + void type_string_default_set(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); schema.setDefault("custom-example-value"); @@ -243,7 +243,7 @@ void type_string_default_set(TestInfo testInfo) throws Exception { } @Test - void type_string_example_set(TestInfo testInfo) throws Exception { + void type_string_example_set(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); schema.setExample("custom-example-value"); @@ -255,7 +255,7 @@ void type_string_example_set(TestInfo testInfo) throws Exception { } @Test - void type_string_from_enum(TestInfo testInfo) throws Exception { + void type_string_from_enum(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); schema.addEnumItem("EnumItem1"); @@ -268,7 +268,7 @@ void type_string_from_enum(TestInfo testInfo) throws Exception { } @Test - void type_string_format_byte(TestInfo testInfo) throws Exception { + void type_string_format_byte(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); schema.setFormat("byte"); @@ -280,7 +280,7 @@ void type_string_format_byte(TestInfo testInfo) throws Exception { } @Test - void type_string_format_binary(TestInfo testInfo) throws Exception { + void type_string_format_binary(TestInfo testInfo) { BinarySchema schema = new BinarySchema(); schema.setName(testInfo.getDisplayName()); @@ -293,7 +293,7 @@ void type_string_format_binary(TestInfo testInfo) throws Exception { } @Test - void type_string_format_date(TestInfo testInfo) throws Exception { + void type_string_format_date(TestInfo testInfo) { DateSchema schema = new DateSchema(); schema.setName(testInfo.getDisplayName()); @@ -304,7 +304,7 @@ void type_string_format_date(TestInfo testInfo) throws Exception { } @Test - void type_string_format_datetime(TestInfo testInfo) throws Exception { + void type_string_format_datetime(TestInfo testInfo) { DateTimeSchema schema = new DateTimeSchema(); schema.setName(testInfo.getDisplayName()); @@ -315,7 +315,7 @@ void type_string_format_datetime(TestInfo testInfo) throws Exception { } @Test - void type_string_format_email(TestInfo testInfo) throws Exception { + void type_string_format_email(TestInfo testInfo) { EmailSchema schema = new EmailSchema(); schema.setName(testInfo.getDisplayName()); @@ -326,7 +326,7 @@ void type_string_format_email(TestInfo testInfo) throws Exception { } @Test - void type_string_format_password(TestInfo testInfo) throws Exception { + void type_string_format_password(TestInfo testInfo) { PasswordSchema schema = new PasswordSchema(); schema.setName(testInfo.getDisplayName()); @@ -337,7 +337,7 @@ void type_string_format_password(TestInfo testInfo) throws Exception { } @Test - void type_string_format_uuid(TestInfo testInfo) throws Exception { + void type_string_format_uuid(TestInfo testInfo) { UUIDSchema schema = new UUIDSchema(); schema.setName(testInfo.getDisplayName()); @@ -348,7 +348,7 @@ void type_string_format_uuid(TestInfo testInfo) throws Exception { } @Test - void type_string_format_int32(TestInfo testInfo) throws Exception { + void type_string_format_int32(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); schema.setFormat("int32"); @@ -360,7 +360,7 @@ void type_string_format_int32(TestInfo testInfo) throws Exception { } @Test - void type_string_format_int64(TestInfo testInfo) throws Exception { + void type_string_format_int64(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); schema.setFormat("int32"); @@ -372,7 +372,7 @@ void type_string_format_int64(TestInfo testInfo) throws Exception { } @Test - void type_string_format_float(TestInfo testInfo) throws Exception { + void type_string_format_float(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); schema.setFormat("float"); @@ -384,7 +384,7 @@ void type_string_format_float(TestInfo testInfo) throws Exception { } @Test - void type_string_format_double(TestInfo testInfo) throws Exception { + void type_string_format_double(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); schema.setFormat("double"); @@ -396,7 +396,7 @@ void type_string_format_double(TestInfo testInfo) throws Exception { } @Test - void type_string_format_unknown(TestInfo testInfo) throws Exception { + void type_string_format_unknown(TestInfo testInfo) { StringSchema schema = new StringSchema(); schema.setName(testInfo.getDisplayName()); schema.setFormat("unknown"); @@ -408,7 +408,7 @@ void type_string_format_unknown(TestInfo testInfo) throws Exception { } @Test - void type_unknown_schema(TestInfo testInfo) throws Exception { + void type_unknown_schema(TestInfo testInfo) { class TestSchema extends Schema { TestSchema() { super("test-schema", null); @@ -425,7 +425,7 @@ class TestSchema extends Schema { } @Test - void type_primitive_array(TestInfo testInfo) throws Exception { + void type_primitive_array(TestInfo testInfo) { ArraySchema schema = new ArraySchema(); schema.setName(testInfo.getDisplayName()); schema.setItems(new StringSchema()); @@ -440,7 +440,7 @@ void type_primitive_array(TestInfo testInfo) throws Exception { @Nested class TestObjectSchema { @Test - void type_object_array(TestInfo testInfo) throws Exception { + void type_object_array(TestInfo testInfo) { ObjectSchema itemSchema = new ObjectSchema(); itemSchema.addProperty("s", new StringSchema()); itemSchema.addProperty("b", new BooleanSchema()); @@ -456,7 +456,7 @@ void type_object_array(TestInfo testInfo) throws Exception { } @Test - void composite_object_without_references(TestInfo testInfo) throws Exception { + void composite_object_without_references(TestInfo testInfo) { ObjectSchema schema = new ObjectSchema(); schema.setName(testInfo.getDisplayName()); schema.addProperty("s", new StringSchema()); @@ -469,8 +469,8 @@ void composite_object_without_references(TestInfo testInfo) throws Exception { } @Test - void composite_object_with_references(TestInfo testInfo) throws Exception { - Schema referenceSchema = new Schema(); + void composite_object_with_references(TestInfo testInfo) { + Schema referenceSchema = new Schema<>(); referenceSchema.set$ref("#/components/schemas/Nested"); ObjectSchema compositeSchema = new ObjectSchema(); @@ -488,11 +488,11 @@ void composite_object_with_references(TestInfo testInfo) throws Exception { } @Test - void object_with_anyOf(TestInfo testInfo) throws Exception { + void object_with_anyOf(TestInfo testInfo) { ObjectSchema compositeSchema = new ObjectSchema(); compositeSchema.setName(testInfo.getDisplayName()); - Schema propertySchema = new ObjectSchema(); + Schema propertySchema = new ObjectSchema(); propertySchema.setAnyOf(List.of(new StringSchema(), new NumberSchema())); compositeSchema.addProperty("anyOfField", propertySchema); @@ -503,11 +503,11 @@ void object_with_anyOf(TestInfo testInfo) throws Exception { } @Test - void object_with_oneOf(TestInfo testInfo) throws Exception { + void object_with_oneOf(TestInfo testInfo) { ObjectSchema compositeSchema = new ObjectSchema(); compositeSchema.setName(testInfo.getDisplayName()); - Schema propertySchema = new ObjectSchema(); + Schema propertySchema = new ObjectSchema(); propertySchema.setOneOf(List.of(new StringSchema(), new NumberSchema())); compositeSchema.addProperty("oneOfField", propertySchema); @@ -518,7 +518,7 @@ void object_with_oneOf(TestInfo testInfo) throws Exception { } @Test - void object_with_allOf(TestInfo testInfo) throws Exception { + void object_with_allOf(TestInfo testInfo) { ObjectSchema compositeSchema = new ObjectSchema(); compositeSchema.setName(testInfo.getDisplayName()); @@ -528,7 +528,7 @@ void object_with_allOf(TestInfo testInfo) throws Exception { schema2.setProperties(Map.of("field2", new NumberSchema())); StringSchema skippedSchemaSinceObjectIsRequired = new StringSchema(); - Schema propertySchema = new ObjectSchema(); + Schema propertySchema = new ObjectSchema(); propertySchema.setAllOf(List.of(schema1, schema2, skippedSchemaSinceObjectIsRequired)); compositeSchema.addProperty("allOfField", propertySchema); @@ -539,11 +539,11 @@ void object_with_allOf(TestInfo testInfo) throws Exception { } @Test - void object_with_map(TestInfo testInfo) throws Exception { + void object_with_map(TestInfo testInfo) { MapSchema mapSchema = new MapSchema(); mapSchema.setName(testInfo.getDisplayName()); - Schema propertySchema = new StringSchema(); + Schema propertySchema = new StringSchema(); mapSchema.setAdditionalProperties(propertySchema); JsonNode actual = jsonSchemaWalker.fromSchema(mapSchema, Map.of()); @@ -553,7 +553,7 @@ void object_with_map(TestInfo testInfo) throws Exception { } @Test - void object_with_map_and_set(TestInfo testInfo) throws Exception { + void object_with_map_and_set(TestInfo testInfo) { // Example: Map> Schema objectSchema = new ObjectSchema(); objectSchema.setName("objectName"); @@ -573,7 +573,7 @@ void object_with_map_and_set(TestInfo testInfo) throws Exception { } @Test - void schema_with_problematic_object_toString_example(TestInfo testInfo) throws Exception { + void schema_with_problematic_object_toString_example(TestInfo testInfo) { ObjectSchema schema = new ObjectSchema(); schema.setName(testInfo.getDisplayName()); schema.setExample(new ClassWithToString()); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerTest.java new file mode 100644 index 000000000..43be36268 --- /dev/null +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerTest.java @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers; + +import io.swagger.v3.oas.models.media.Schema; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +class DefaultSchemaWalkerTest { + + @Test + void getTypeForExampleValue() { + DefaultSchemaWalker schemaWalker = new DefaultSchemaWalker<>(null); + + Schema schema1 = new Schema<>(); // no types defined. + Schema schema2 = new Schema<>(); + schema2.setType("string"); + Schema schema3 = new Schema<>(); + schema3.setTypes(Set.of("string", "null")); + Schema schema4 = new Schema<>(); + schema4.setTypes(Set.of("string", "integer")); + + assertThat(schemaWalker.getTypeForExampleValue(schema1)).isNull(); + assertThat(schemaWalker.getTypeForExampleValue(schema2)).isEqualTo("string"); + assertThat(schemaWalker.getTypeForExampleValue(schema3)).isEqualTo("string"); + assertThat(schemaWalker.getTypeForExampleValue(schema4)).isEqualTo("integer"); + } + + @Test + void getDefaultValue() { + DefaultSchemaWalker schemaWalker = new DefaultSchemaWalker<>(new DummyExampleValueGenerator()); + + Schema schema1 = new Schema<>(); + schema1.setType("string"); + Schema schema2 = new Schema<>(); + schema2.setType("string"); + schema2.setConst("constValue"); + Schema schema3 = new Schema<>(); + schema3.setType("string"); + schema3.setEnum(List.of("example1", "example2")); + + assertThat(schemaWalker.fromSchema(schema1, Map.of())).isEqualTo("string"); + assertThat(schemaWalker.fromSchema(schema2, Map.of())).isEqualTo("constValue"); + assertThat(schemaWalker.fromSchema(schema3, Map.of())).isEqualTo("example1"); + } + + @Test + void getDefaultValueForNonStringEnum() { + DefaultSchemaWalker schemaWalker = new DefaultSchemaWalker<>(new DummyExampleValueGenerator()); + Schema schema = new Schema<>(); + schema.setEnum(List.of(7)); + + assertThat(schemaWalker.fromSchema(schema, Map.of())).isEqualTo("7"); + } +} diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerXmlIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerXmlIntegrationTest.java similarity index 95% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerXmlIntegrationTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerXmlIntegrationTest.java index 5d878ac24..274d25c6f 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerXmlIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerXmlIntegrationTest.java @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers; -import io.github.springwolf.core.asyncapi.components.examples.walkers.xml.DefaultExampleXmlValueSerializer; -import io.github.springwolf.core.asyncapi.components.examples.walkers.xml.ExampleXmlValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml.DefaultExampleXmlValueSerializer; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml.ExampleXmlValueGenerator; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.BinarySchema; import io.swagger.v3.oas.models.media.BooleanSchema; @@ -73,20 +73,36 @@ class FromSchema { void build() { StringSchema schema = new StringSchema(); schema.setName("build_schema_test"); - // TODO should throw exception, just a raw value does not work in xml - // TODO duplicate with number schema String actualXmlString = xmlSchemaWalker.fromSchema(schema, emptyMap()).trim(); assertThat(actualXmlString).isEqualTo("string"); } + @Test + void buildWithoutNameReturnsNull() { + StringSchema schema = new StringSchema(); + + Object actualXmlString = xmlSchemaWalker.fromSchema(schema, emptyMap()); + + assertThat(actualXmlString).isNull(); + } + + @Test + void buildNumberWithoutNameReturnsNull() { + NumberSchema schema = new NumberSchema(); + + Object actualXmlString = xmlSchemaWalker.fromSchema(schema, emptyMap()); + + assertThat(actualXmlString).isNull(); + } + @Test void failWhenMissingDefinition() { ObjectSchema compositeSchema = new ObjectSchema(); compositeSchema.setName("composite-schema"); - Schema referenceSchema = new Schema(); + Schema referenceSchema = new Schema<>(); referenceSchema.set$ref("#/components/schemas/Nested"); compositeSchema.addProperty("f", referenceSchema); @@ -453,7 +469,7 @@ void composite_object_with_references() { nestedSchema.addProperty("s", new StringSchema()); nestedSchema.addProperty("b", new BooleanSchema()); - Schema referenceSchema = new Schema(); + Schema referenceSchema = new Schema<>(); referenceSchema.set$ref("#/components/schemas/Nested"); ObjectSchema compositeSchema = new ObjectSchema(); @@ -502,7 +518,7 @@ void object_with_anyOf() { ObjectSchema compositeSchema = new ObjectSchema(); compositeSchema.setName("object_with_anyOf"); - Schema propertySchema = new ObjectSchema(); + Schema propertySchema = new ObjectSchema(); propertySchema.setAnyOf(List.of(new StringSchema(), new NumberSchema())); compositeSchema.addProperty("anyOfField", propertySchema); @@ -521,7 +537,7 @@ void object_with_oneOf() { ObjectSchema compositeSchema = new ObjectSchema(); compositeSchema.setName("object_with_oneOf"); - Schema propertySchema = new ObjectSchema(); + Schema propertySchema = new ObjectSchema(); propertySchema.setOneOf(List.of(new StringSchema(), new NumberSchema())); compositeSchema.addProperty("oneOfField", propertySchema); @@ -541,7 +557,7 @@ void object_with_allOf() { schema2.setProperties(Map.of("field2", new NumberSchema())); StringSchema skippedSchemaSinceObjectIsRequired = new StringSchema(); - Schema propertySchema = new ObjectSchema(); + Schema propertySchema = new ObjectSchema(); propertySchema.setAllOf(List.of(schema1, schema2, skippedSchemaSinceObjectIsRequired)); compositeSchema.addProperty("allOfField", propertySchema); @@ -557,7 +573,7 @@ void object_with_map() { MapSchema mapSchema = new MapSchema(); mapSchema.setName("object_with_map"); - Schema propertySchema = new StringSchema(); + Schema propertySchema = new StringSchema(); mapSchema.setAdditionalProperties(propertySchema); String actual = xmlSchemaWalker.fromSchema(mapSchema, Map.of()); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerYamlIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerYamlIntegrationTest.java similarity index 96% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerYamlIntegrationTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerYamlIntegrationTest.java index 9e3255010..71c04a05a 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/DefaultSchemaWalkerYamlIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DefaultSchemaWalkerYamlIntegrationTest.java @@ -1,9 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; -import io.github.springwolf.core.asyncapi.components.examples.walkers.yaml.DefaultExampleYamlValueSerializer; -import io.github.springwolf.core.asyncapi.components.examples.walkers.yaml.ExampleYamlValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.yaml.DefaultExampleYamlValueSerializer; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.yaml.ExampleYamlValueGenerator; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.BinarySchema; @@ -80,7 +80,7 @@ void failWhenMissingDefinition(TestInfo testInfo) { ObjectSchema compositeSchema = new ObjectSchema(); compositeSchema.setName(testInfo.getDisplayName()); - Schema referenceSchema = new Schema(); + Schema referenceSchema = new Schema<>(); referenceSchema.set$ref("#/components/schemas/Nested"); compositeSchema.addProperty("f", referenceSchema); @@ -451,7 +451,7 @@ void composite_object_without_references(TestInfo testInfo) { @Test void composite_object_with_references(TestInfo testInfo) { - Schema referenceSchema = new Schema(); + Schema referenceSchema = new Schema<>(); referenceSchema.set$ref("#/components/schemas/Nested"); ObjectSchema compositeSchema = new ObjectSchema(); @@ -477,7 +477,7 @@ void object_with_anyOf(TestInfo testInfo) { ObjectSchema compositeSchema = new ObjectSchema(); compositeSchema.setName(testInfo.getDisplayName()); - Schema propertySchema = new ObjectSchema(); + Schema propertySchema = new ObjectSchema(); propertySchema.setAnyOf(List.of(new StringSchema(), new NumberSchema())); compositeSchema.addProperty("anyOfField", propertySchema); @@ -493,7 +493,7 @@ void object_with_oneOf(TestInfo testInfo) { ObjectSchema compositeSchema = new ObjectSchema(); compositeSchema.setName(testInfo.getDisplayName()); - Schema propertySchema = new ObjectSchema(); + Schema propertySchema = new ObjectSchema(); propertySchema.setOneOf(List.of(new StringSchema(), new NumberSchema())); compositeSchema.addProperty("oneOfField", propertySchema); @@ -515,7 +515,7 @@ void object_with_allOf(TestInfo testInfo) { schema2.setProperties(Map.of("field2", new NumberSchema())); StringSchema skippedSchemaSinceObjectIsRequired = new StringSchema(); - Schema propertySchema = new ObjectSchema(); + Schema propertySchema = new ObjectSchema(); propertySchema.setAllOf(List.of(schema1, schema2, skippedSchemaSinceObjectIsRequired)); compositeSchema.addProperty("allOfField", propertySchema); @@ -533,7 +533,7 @@ void object_with_map(TestInfo testInfo) { MapSchema mapSchema = new MapSchema(); mapSchema.setName(testInfo.getDisplayName()); - Schema propertySchema = new StringSchema(); + Schema propertySchema = new StringSchema(); mapSchema.setAdditionalProperties(propertySchema); String actualString = jsonSchemaWalker.fromSchema(mapSchema, Map.of()); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DummyExampleValueGenerator.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DummyExampleValueGenerator.java new file mode 100644 index 000000000..1cab0eb9b --- /dev/null +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/DummyExampleValueGenerator.java @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers; + +import io.swagger.v3.oas.models.media.Schema; + +import java.util.List; +import java.util.Optional; + +class DummyExampleValueGenerator implements ExampleValueGenerator { + + @Override + public boolean canHandle(String contentType) { + return true; + } + + @Override + public Optional lookupSchemaName(Schema schema) { + return Optional.empty(); + } + + @Override + public Object prepareForSerialization(Schema name, Object exampleObject) { + return exampleObject; + } + + @Override + public Optional createIntegerExample(Integer value, Schema schema) { + return Optional.of("integerExample"); + } + + @Override + public Optional createDoubleExample(Double value, Schema schema) { + return Optional.of("doubleExample"); + } + + @Override + public Optional createBooleanExample(Boolean value, Schema schema) { + return Optional.of("booleanExample"); + } + + @Override + public Optional createEmptyObjectExample() { + return Optional.of("emptyObjectExample"); + } + + @Override + public Optional createStringExample(String value, Schema schema) { + return Optional.of(value); + } + + @Override + public Optional createEnumExample(String anEnumValue, Schema schema) { + return Optional.of(anEnumValue); + } + + @Override + public Optional createUnknownSchemaStringTypeExample(String schemaType) { + return Optional.empty(); + } + + @Override + public Optional createUnknownSchemaStringFormatExample(String schemaFormat) { + return Optional.empty(); + } + + @Override + public Object createRaw(Object exampleValueString) { + return exampleValueString; + } + + @Override + public Object getExampleOrNull(Optional fieldName, Schema schema, Object example) { + return schema.getExample(); + } + + @Override + public Object createArrayExample(Optional name, Object arrayItem) { + return null; + } + + @Override + public void addPropertyExamples(Object object, List> properties) {} + + @Override + public Object startObject(Optional name) { + return null; + } +} diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/SchemaWalkerProviderTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/SchemaWalkerProviderTest.java similarity index 58% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/SchemaWalkerProviderTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/SchemaWalkerProviderTest.java index 637c0aa7a..cde8f1e1a 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/SchemaWalkerProviderTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/SchemaWalkerProviderTest.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; import org.junit.jupiter.api.Test; import java.util.List; @@ -16,15 +16,15 @@ class SchemaWalkerProviderTest { @Test void returnsSchemaWalkerForContentType() { // given - SchemaWalker schemaWalker1 = mock(SchemaWalker.class); - SchemaWalker schemaWalker2 = mock(SchemaWalker.class); - SchemaWalker schemaWalker3 = mock(SchemaWalker.class); + SchemaWalker schemaWalker1 = mock(SchemaWalker.class); + SchemaWalker schemaWalker2 = mock(SchemaWalker.class); + SchemaWalker schemaWalker3 = mock(SchemaWalker.class); SchemaWalkerProvider provider = new SchemaWalkerProvider(List.of(schemaWalker1, schemaWalker2, schemaWalker3)); when(schemaWalker2.canHandle("content-type")).thenReturn(true); // when - Optional schemaWalker = provider.generatorFor("content-type"); + Optional> schemaWalker = provider.generatorFor("content-type"); // then assertThat(schemaWalker.isPresent()).isTrue(); @@ -34,13 +34,13 @@ void returnsSchemaWalkerForContentType() { @Test void doesNotReturnWalkerForUnknownContentType() { // given - SchemaWalker schemaWalker1 = mock(SchemaWalker.class); - SchemaWalker schemaWalker2 = mock(SchemaWalker.class); - SchemaWalker schemaWalker3 = mock(SchemaWalker.class); + SchemaWalker schemaWalker1 = mock(SchemaWalker.class); + SchemaWalker schemaWalker2 = mock(SchemaWalker.class); + SchemaWalker schemaWalker3 = mock(SchemaWalker.class); SchemaWalkerProvider provider = new SchemaWalkerProvider(List.of(schemaWalker1, schemaWalker2, schemaWalker3)); // when - Optional schemaWalker = provider.generatorFor("content-type"); + Optional> schemaWalker = provider.generatorFor("content-type"); // then assertThat(schemaWalker.isPresent()).isFalse(); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/ExampleXmlValueGeneratorTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/ExampleXmlValueGeneratorTest.java similarity index 98% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/ExampleXmlValueGeneratorTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/ExampleXmlValueGeneratorTest.java index 3a1a14d6e..c8e4826de 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/examples/walkers/xml/ExampleXmlValueGeneratorTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/examples/walkers/xml/ExampleXmlValueGeneratorTest.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.examples.walkers.xml; +package io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.xml; import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.media.XML; diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/postprocessors/AvroSchemaPostProcessorTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/AvroSchemaPostProcessorTest.java similarity index 70% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/postprocessors/AvroSchemaPostProcessorTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/AvroSchemaPostProcessorTest.java index ca09832b0..1b93b357f 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/components/postprocessors/AvroSchemaPostProcessorTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/schemas/schema/postprocessors/AvroSchemaPostProcessorTest.java @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.components.postprocessors; +package io.github.springwolf.core.asyncapi.schemas.schema.postprocessors; +import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import org.junit.jupiter.api.Test; @@ -16,21 +17,21 @@ class AvroSchemaPostProcessorTest { @Test void avroSchemasAreRemovedTest() { // given - var avroSchema = new io.swagger.v3.oas.models.media.Schema(); + Schema avroSchema = new Schema<>(); avroSchema.set$ref("#/components/schemas/org.apache.avro.Schema"); - var avroSpecificData = new io.swagger.v3.oas.models.media.Schema(); + Schema avroSpecificData = new Schema<>(); avroSpecificData.set$ref("#/components/schemas/org.apache.avro.specific.SpecificData"); - var schema = new io.swagger.v3.oas.models.media.Schema(); + Schema schema = new Schema<>(); schema.setProperties(new HashMap<>( Map.of("foo", new StringSchema(), "schema", avroSchema, "specificData", avroSpecificData))); - var definitions = new HashMap(); + var definitions = new HashMap>(); definitions.put("schema", schema); definitions.put("customClassRefUnusedInThisTest", new StringSchema()); - definitions.put("org.apache.avro.Schema", new io.swagger.v3.oas.models.media.Schema()); - definitions.put("org.apache.avro.ConversionJava.lang.Object", new io.swagger.v3.oas.models.media.Schema()); + definitions.put("org.apache.avro.Schema", new Schema<>()); + definitions.put("org.apache.avro.ConversionJava.lang.Object", new Schema<>()); // when processor.process(schema, definitions, "content-type-ignored"); @@ -44,27 +45,27 @@ void avroSchemasAreRemovedTest() { @Test void avroSchemasAreRemovedInRefsTest() { // given - var avroSchema = new io.swagger.v3.oas.models.media.Schema(); + Schema avroSchema = new Schema<>(); avroSchema.set$ref("#/components/schemas/org.apache.avro.Schema"); - var avroSpecificData = new io.swagger.v3.oas.models.media.Schema(); + Schema avroSpecificData = new Schema<>(); avroSpecificData.set$ref("#/components/schemas/org.apache.avro.specific.SpecificData"); - var refSchema = new io.swagger.v3.oas.models.media.Schema(); + Schema refSchema = new Schema<>(); refSchema.setProperties(new HashMap<>( Map.of("foo", new StringSchema(), "schema", avroSchema, "specificData", avroSpecificData))); - var refProperty = new io.swagger.v3.oas.models.media.Schema(); + Schema refProperty = new Schema<>(); refProperty.set$ref("#/components/schemas/refSchema"); - var schema = new io.swagger.v3.oas.models.media.Schema(); + Schema schema = new Schema<>(); schema.setProperties(new HashMap<>(Map.of("ref", refProperty))); - var definitions = new HashMap(); + var definitions = new HashMap>(); definitions.put("schema", schema); definitions.put("refSchema", refSchema); definitions.put("customClassRefUnusedInThisTest", new StringSchema()); - definitions.put("org.apache.avro.Schema", new io.swagger.v3.oas.models.media.Schema()); - definitions.put("org.apache.avro.ConversionJava.lang.Object", new io.swagger.v3.oas.models.media.Schema()); + definitions.put("org.apache.avro.Schema", new Schema<>()); + definitions.put("org.apache.avro.ConversionJava.lang.Object", new Schema<>()); // when processor.process(schema, definitions, "content-type-ignored"); @@ -84,13 +85,13 @@ void avroSchemasAreRemovedInRefsTest() { @Test void handleRecursiveSchemasTest() { - var schema = new io.swagger.v3.oas.models.media.Schema(); + Schema schema = new Schema<>(); schema.set$ref("#/components/schemas/intermediateSchema"); - var intermediateSchema = new io.swagger.v3.oas.models.media.Schema(); + Schema intermediateSchema = new Schema<>(); intermediateSchema.set$ref("#/components/schemas/schema"); - var definitions = new HashMap(); + var definitions = new HashMap>(); definitions.put("schema", schema); definitions.put("intermediateSchema", new StringSchema()); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/configuration/properties/SpringwolfConfigPropertiesIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/configuration/properties/SpringwolfConfigPropertiesIntegrationTest.java index 286e42032..b4cc9e084 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/configuration/properties/SpringwolfConfigPropertiesIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/configuration/properties/SpringwolfConfigPropertiesIntegrationTest.java @@ -195,6 +195,26 @@ void uiConfigIsMappedCorrectly() { } } + @Nested + @ExtendWith(SpringExtension.class) + @EnableConfigurationProperties(SpringwolfConfigProperties.class) + @TestPropertySource( + properties = { + "springwolf.scanner.async-listener.enabled=false", + "springwolf.scanner.async-publisher.enabled=false" + }) + class ScannerConfigTest { + + @Autowired + private SpringwolfConfigProperties properties; + + @Test + void scannerConfigIsMappedCorrectly() { + assertThat(properties.getScanner().getAsyncListener().isEnabled()).isFalse(); + assertThat(properties.getScanner().getAsyncPublisher().isEnabled()).isFalse(); + } + } + @Nested @ExtendWith(SpringExtension.class) @EnableConfigurationProperties(SpringwolfConfigProperties.class) @@ -211,6 +231,8 @@ void uiConfigIsMappedCorrectly() { // then assertThat(actual.getDefaults().isShowBindings()).isTrue(); assertThat(actual.getDefaults().isShowHeaders()).isTrue(); + assertThat(properties.getScanner().getAsyncListener().isEnabled()).isTrue(); + assertThat(properties.getScanner().getAsyncPublisher().isEnabled()).isTrue(); } } } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/controller/PublishingPayloadCreatorTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/controller/PublishingPayloadCreatorTest.java index 8cbb61b6d..c6aaa1bd8 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/controller/PublishingPayloadCreatorTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/controller/PublishingPayloadCreatorTest.java @@ -50,7 +50,7 @@ void shouldResolveEmptyPayload() { } @Test - void shouldResolveBooleanPayload() throws Exception { + void shouldResolveBooleanPayload() { // given String type = Boolean.class.getName(); String payload = "true"; @@ -75,7 +75,7 @@ void shouldResolveBooleanPayload() throws Exception { } @Test - void shouldResolveIntegerPayload() throws Exception { + void shouldResolveIntegerPayload() { // given String type = Integer.class.getName(); String payload = "12345678"; @@ -100,7 +100,7 @@ void shouldResolveIntegerPayload() throws Exception { } @Test - void shouldResolveLongPayload() throws Exception { + void shouldResolveLongPayload() { // given String type = Long.class.getName(); String payload = Long.valueOf(Long.MAX_VALUE).toString(); @@ -125,7 +125,7 @@ void shouldResolveLongPayload() throws Exception { } @Test - void shouldResolveFloatPayload() throws Exception { + void shouldResolveFloatPayload() { // given String type = Float.class.getName(); String payload = "12345678.123"; @@ -150,7 +150,7 @@ void shouldResolveFloatPayload() throws Exception { } @Test - void shouldResolveDoublePayload() throws Exception { + void shouldResolveDoublePayload() { // given String type = Double.class.getName(); String payload = Double.valueOf(Double.MAX_VALUE).toString(); @@ -175,7 +175,7 @@ void shouldResolveDoublePayload() throws Exception { } @Test - void shouldResolveObjectPayload() throws Exception { + void shouldResolveObjectPayload() { // given String type = ObjectClass.class.getName(); String payload = "{\"value\":\"test\"}"; @@ -200,7 +200,7 @@ void shouldResolveObjectPayload() throws Exception { } @Test - void shouldResolveStringPayload() throws Exception { + void shouldResolveStringPayload() { // given String type = String.class.getName(); String payload = "\"test\""; @@ -249,7 +249,7 @@ void shouldReturnEmptyPayloadForUnknownClass() { } @Test - void shouldReturnEmptyPayloadForInvalidJson() throws Exception { + void shouldReturnEmptyPayloadForInvalidJson() { // given String type = ObjectClass.class.getName(); String payload = "---invalid-json---"; diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/controller/SpringContextControllerIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/controller/SpringContextControllerIntegrationTest.java similarity index 87% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/controller/SpringContextControllerIntegrationTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/controller/SpringContextControllerIntegrationTest.java index 17e1f3219..b3a038d57 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/controller/SpringContextControllerIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/controller/SpringContextControllerIntegrationTest.java @@ -1,9 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.controller; +package io.github.springwolf.core.controller; import io.github.springwolf.core.configuration.SpringwolfWebConfiguration; -import io.github.springwolf.core.controller.ActuatorAsyncApiController; -import io.github.springwolf.core.controller.AsyncApiController; import io.github.springwolf.core.fixtures.SpringwolfApplicationIntegrationTest; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -33,7 +31,7 @@ class SpringwolfOnApplicationPortConfigurationTest { private Optional actuatorAsyncApiController; @Test - void contextWithApplicationProperties() throws Exception { + void contextWithApplicationProperties() { assertThat(context).isNotNull(); assertThat(asyncApiController).isPresent(); @@ -60,7 +58,7 @@ class SpringwolfOnManagementPortConfigurationTest { private Optional actuatorAsyncApiController; @Test - void contextWithApplicationProperties() throws Exception { + void contextWithApplicationProperties() { assertThat(context).isNotNull(); assertThat(asyncApiController).isNotPresent(); diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/controller/dtos/MessageDtoTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/controller/dtos/MessageDtoTest.java similarity index 89% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/controller/dtos/MessageDtoTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/controller/dtos/MessageDtoTest.java index e0909fcb0..1421e7e2f 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/controller/dtos/MessageDtoTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/controller/dtos/MessageDtoTest.java @@ -1,7 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.controller.dtos; +package io.github.springwolf.core.controller.dtos; -import io.github.springwolf.core.controller.dtos.MessageDto; import org.junit.jupiter.api.Test; import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; @@ -14,7 +13,7 @@ class MessageDtoTest { private static final JsonMapper jsonMapper = JsonMapper.builder().build(); @Test - void canBeSerialized() throws Exception { + void canBeSerialized() { String content = "{" + "\"headers\": { \"some-header-key\" : \"some-header-value\" }, " + "\"payload\": \"{\\\"some-payload-key\\\":\\\"some-payload-value\\\"}\", " + "\"type\": \"" @@ -31,7 +30,7 @@ void canBeSerialized() throws Exception { } @Test - void serializationWithDifferentNamingStrategiesIsIndifferent() throws Exception { + void serializationWithDifferentNamingStrategiesIsIndifferent() { // https://github.com/springwolf/springwolf-core/issues/1535 MessageDto messageDto = MessageDto.builder() .headers(singletonMap("some-header-key", new MessageDto.HeaderValue("some-header-value"))) @@ -46,7 +45,7 @@ void serializationWithDifferentNamingStrategiesIsIndifferent() throws Exception } @Test - void canDeserializeStringHeaderValue() throws Exception { + void canDeserializeStringHeaderValue() { // given String content = "\"12345\""; @@ -58,7 +57,7 @@ void canDeserializeStringHeaderValue() throws Exception { } @Test - void canDeserializeNumericHeaderValue() throws Exception { + void canDeserializeNumericHeaderValue() { // given String content = "12345"; diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/grouping/AsyncApiGroupServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/grouping/AsyncApiGroupServiceTest.java similarity index 99% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/grouping/AsyncApiGroupServiceTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/grouping/AsyncApiGroupServiceTest.java index ea23f6e8d..3bee56ee1 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/grouping/AsyncApiGroupServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/grouping/AsyncApiGroupServiceTest.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.grouping; +package io.github.springwolf.core.grouping; import io.github.springwolf.asyncapi.v3.model.AsyncAPI; import io.github.springwolf.asyncapi.v3.model.info.Info; diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/grouping/GroupingServiceTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/grouping/GroupingServiceTest.java similarity index 99% rename from springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/grouping/GroupingServiceTest.java rename to springwolf-core/src/test/java/io/github/springwolf/core/grouping/GroupingServiceTest.java index fe561d090..ef56a3afd 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/asyncapi/grouping/GroupingServiceTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/grouping/GroupingServiceTest.java @@ -1,5 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -package io.github.springwolf.core.asyncapi.grouping; +package io.github.springwolf.core.grouping; import io.github.springwolf.asyncapi.v3.model.AsyncAPI; import io.github.springwolf.asyncapi.v3.model.channel.ChannelObject; diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/ApplicationIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/ApplicationIntegrationTest.java index c1291d238..e05fc3a6e 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/ApplicationIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/ApplicationIntegrationTest.java @@ -65,14 +65,10 @@ void asyncListenerAnnotationIsFound() throws Exception { @Test void ensureThatStandaloneResultIsIdentical() { // given - AsyncApiService asyncApiService = - createStandaloneAsyncApiService(environment, ListenerApplication.class.getPackageName()); + AsyncAPI standaloneAsyncAPI = + createStandaloneAsyncAPI(environment, ListenerApplication.class.getPackageName()); - // when - AsyncAPI asyncApi = asyncApiService.getAsyncAPI(); - - // then - assertThat(asyncApi).isEqualTo(asyncApiService.getAsyncAPI()); + assertThat(standaloneAsyncAPI).isEqualTo(asyncApiService.getAsyncAPI()); } } @@ -111,14 +107,10 @@ void asyncPublisherAnnotationIsFound() throws Exception { @Test void ensureThatStandaloneResultIsIdentical() { // given - AsyncApiService asyncApiService = - createStandaloneAsyncApiService(environment, PublisherApplication.class.getPackageName()); + AsyncAPI standaloneAsyncAPI = + createStandaloneAsyncAPI(environment, PublisherApplication.class.getPackageName()); - // when - AsyncAPI asyncApi = asyncApiService.getAsyncAPI(); - - // then - assertThat(asyncApi).isEqualTo(asyncApiService.getAsyncAPI()); + assertThat(standaloneAsyncAPI).isEqualTo(asyncApiService.getAsyncAPI()); } } @@ -150,7 +142,7 @@ void matchesCheckedInArtifact() throws Exception { } @Test - void allClassesHaveSimpleNameNotFullQualifiedTest() throws Exception { + void allClassesHaveSimpleNameNotFullQualifiedTest() { AsyncAPI asyncAPI = asyncApiService.getAsyncAPI(); String serialized = asyncApiSerializerService.toJsonString(asyncAPI); @@ -266,7 +258,7 @@ class OneOfPayloadTest { private AsyncApiSerializerService asyncApiSerializerService; @Test - void oneOfPropertyIsGeneratedFromTheApplication() throws Exception { + void oneOfPropertyIsGeneratedFromTheApplication() { // when AsyncAPI asyncAPI = asyncApiService.getAsyncAPI(); @@ -345,11 +337,12 @@ void enumAsRefIsHandled() { } } - private AsyncApiService createStandaloneAsyncApiService(ConfigurableEnvironment environment, String basePackage) { - DefaultStandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() + private AsyncAPI createStandaloneAsyncAPI(ConfigurableEnvironment environment, String basePackage) { + try (DefaultStandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() .addScanPackage(basePackage) .setEnvironment(environment) - .buildAndStart(); - return standaloneApplication.getAsyncApiService(); + .buildAndStart()) { + return standaloneApplication.getAsyncApiService().getAsyncAPI(); + } } } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/PayloadSchemaFormatIntegrationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/PayloadSchemaFormatIntegrationTest.java index 1d2686649..8b409ebc0 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/PayloadSchemaFormatIntegrationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/PayloadSchemaFormatIntegrationTest.java @@ -33,24 +33,28 @@ void openApi3ArtifactTest() throws Exception { "openapi_v3", "springwolf.docket.base-package", "io.github.springwolf.core.integrationtests.application.listener"))); - StandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() + try (StandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() .setEnvironment(environment) - .buildAndStart(); + .buildAndStart()) { - // when - AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); + // when + AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); - // then - assertThat(asyncApi).isNotNull(); + // then + assertThat(asyncApi).isNotNull(); - AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); - String actual = serializerService.toJsonString(asyncApi); - Files.writeString(Path.of("src", "test", "resources", "application", "asyncapi.openapiv3.actual.json"), actual); + AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); + String actual = serializerService.toJsonString(asyncApi); + Files.writeString( + Path.of("src", "test", "resources", "application", "asyncapi.openapiv3.actual.json"), actual); - // then - InputStream s = this.getClass().getResourceAsStream("/application/asyncapi.openapiv3.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); - assertThat(actual).isEqualTo(expected); + // then + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/application/asyncapi.openapiv3.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + assertThat(actual).isEqualTo(expected); + } } @Test @@ -66,24 +70,27 @@ void openApi31ArtifactTest() throws Exception { "openapi_v3_1", "springwolf.docket.base-package", "io.github.springwolf.core.integrationtests.application.listener"))); - StandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() + try (StandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() .setEnvironment(environment) - .buildAndStart(); + .buildAndStart()) { - // when - AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); + // when + AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); - // then - assertThat(asyncApi).isNotNull(); + // then + assertThat(asyncApi).isNotNull(); - AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); - String actual = serializerService.toJsonString(asyncApi); - Files.writeString( - Path.of("src", "test", "resources", "application", "asyncapi.openapiv31.actual.json"), actual); + AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); + String actual = serializerService.toJsonString(asyncApi); + Files.writeString( + Path.of("src", "test", "resources", "application", "asyncapi.openapiv31.actual.json"), actual); - // then - InputStream s = this.getClass().getResourceAsStream("/application/asyncapi.openapiv31.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); - assertThat(actual).isEqualTo(expected); + // then + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/application/asyncapi.openapiv31.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + assertThat(actual).isEqualTo(expected); + } } } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/fqn/FqnApplication.java b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/fqn/FqnApplication.java index 43d349766..92f25f5cc 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/fqn/FqnApplication.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/fqn/FqnApplication.java @@ -15,7 +15,7 @@ public Listener listener() { return new Listener(); } - static class Listener { + public static class Listener { @AsyncListener(operation = @AsyncOperation(channelName = "listener-channel")) public void listen(String payload) {} diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/listener/ListenerApplication.java b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/listener/ListenerApplication.java index ddd76d965..9ee185242 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/listener/ListenerApplication.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/listener/ListenerApplication.java @@ -20,7 +20,7 @@ public ClassListener classListener() { return new ClassListener(); } - static class Listener { + public static class Listener { @AsyncListener(operation = @AsyncOperation(channelName = "listener-channel")) public void listen(String payload) {} diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/oneof/OneOfPayloadApplication.java b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/oneof/OneOfPayloadApplication.java index e646e8b5b..feadd9b41 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/oneof/OneOfPayloadApplication.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/oneof/OneOfPayloadApplication.java @@ -14,7 +14,7 @@ public Listener listener() { return new Listener(); } - static class Listener { + public static class Listener { @AsyncListener(operation = @AsyncOperation(channelName = "oneof-channel")) public void listen(Payload payload) {} } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/polymorphic/PolymorphicPayloadApplication.java b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/polymorphic/PolymorphicPayloadApplication.java index 83b246b7a..068f2d75b 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/polymorphic/PolymorphicPayloadApplication.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/polymorphic/PolymorphicPayloadApplication.java @@ -17,7 +17,7 @@ public Listener listener() { return new Listener(); } - static class Listener { + public static class Listener { @AsyncListener(operation = @AsyncOperation(channelName = "listener-channel")) public void listen(Payload payload) {} } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/publisher/PublisherApplication.java b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/publisher/PublisherApplication.java index 69134400b..e4ba86c35 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/publisher/PublisherApplication.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/publisher/PublisherApplication.java @@ -21,7 +21,7 @@ public ClassPublisher classPublisher() { return new ClassPublisher(); } - static class Publisher { + public static class Publisher { @AsyncPublisher(operation = @AsyncOperation(channelName = "publisher-channel")) public void publish(String payload) {} @@ -36,7 +36,7 @@ public void publish4(List payload) {} } @AsyncPublisher(operation = @AsyncOperation(channelName = "publisher-class-channel")) - static class ClassPublisher { + public static class ClassPublisher { public void publish(Integer payload) {} } } diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/ref/SchemaEnumAsRefApplication.java b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/ref/SchemaEnumAsRefApplication.java index 388776b3b..7389804db 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/ref/SchemaEnumAsRefApplication.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/integrationtests/application/ref/SchemaEnumAsRefApplication.java @@ -14,12 +14,12 @@ public Listener listener() { return new Listener(); } - static class Listener { + public static class Listener { @AsyncListener(operation = @AsyncOperation(channelName = "enum-channel")) public void listen(Schemas.MyEnumRoot payload) {} } - public class Schemas { + public static class Schemas { public record MyEnumRoot(MyEnumObject myEnumObjectField) {} @Schema(enumAsRef = true) diff --git a/springwolf-core/src/test/java/io/github/springwolf/core/standalone/DefaultStandaloneApplicationTest.java b/springwolf-core/src/test/java/io/github/springwolf/core/standalone/DefaultStandaloneApplicationTest.java index 6527a14d9..ce1acea17 100644 --- a/springwolf-core/src/test/java/io/github/springwolf/core/standalone/DefaultStandaloneApplicationTest.java +++ b/springwolf-core/src/test/java/io/github/springwolf/core/standalone/DefaultStandaloneApplicationTest.java @@ -25,20 +25,20 @@ void shouldCreateStandaloneFactoryWithBasePackageFromProperties() { Map.of( "springwolf.docket.base-package", "io.github.springwolf.core.integrationtests.application.listener"))); - DefaultStandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() + try (DefaultStandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() .setEnvironment(environment) - .buildAndStart(); - - // then - assertThat(standaloneApplication.getAsyncApiService().getAsyncAPI()).isNotNull(); - assertThat(standaloneApplication - .getAsyncApiService() - .getAsyncAPI() - .getInfo() - .getTitle()) - .isEqualTo("springwolf-core-test-properties-file"); - assertThat(standaloneApplication.getAsyncApiService().getAsyncAPI().getChannels()) - .containsKey("listener-channel"); + .buildAndStart()) { + // then + assertThat(standaloneApplication.getAsyncApiService().getAsyncAPI()).isNotNull(); + assertThat(standaloneApplication + .getAsyncApiService() + .getAsyncAPI() + .getInfo() + .getTitle()) + .isEqualTo("springwolf-core-test-properties-file"); + assertThat(standaloneApplication.getAsyncApiService().getAsyncAPI().getChannels()) + .containsKey("listener-channel"); + } } @Test @@ -51,14 +51,14 @@ void shouldCreateStandaloneFactoryWithScanPackage() { "env", Map.of("springwolf.docket.base-package", "none.existing.package"))); CustomizerMarkerConfiguration.hasCustomized = false; - DefaultStandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() + try (DefaultStandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() .addScanPackage(CustomizerMarkerConfiguration.class.getPackageName()) .setEnvironment(environment) - .buildAndStart(); - - // then - assertThat(standaloneApplication.getAsyncApiService().getAsyncAPI()).isNotNull(); - assertThat(CustomizerMarkerConfiguration.hasCustomized).isTrue(); + .buildAndStart()) { + // then + assertThat(standaloneApplication.getAsyncApiService().getAsyncAPI()).isNotNull(); + assertThat(CustomizerMarkerConfiguration.hasCustomized).isTrue(); + } } @Test @@ -67,20 +67,20 @@ void shouldCreateStandaloneFactoryForBasicApplicationWithProfile() { ConfigurableEnvironment environment = StandaloneEnvironmentLoader.load(List.of("standalone", "base-package")); // when - DefaultStandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() + try (DefaultStandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() .setEnvironment(environment) - .buildAndStart(); - - // then - assertThat(standaloneApplication.getAsyncApiService().getAsyncAPI()).isNotNull(); - assertThat(standaloneApplication - .getAsyncApiService() - .getAsyncAPI() - .getInfo() - .getTitle()) - .isEqualTo("springwolf-core-standalone"); - assertThat(standaloneApplication.getAsyncApiService().getAsyncAPI().getChannels()) - .containsKey("listener-channel"); + .buildAndStart()) { + // then + assertThat(standaloneApplication.getAsyncApiService().getAsyncAPI()).isNotNull(); + assertThat(standaloneApplication + .getAsyncApiService() + .getAsyncAPI() + .getInfo() + .getTitle()) + .isEqualTo("springwolf-core-standalone"); + assertThat(standaloneApplication.getAsyncApiService().getAsyncAPI().getChannels()) + .containsKey("listener-channel"); + } } @Test @@ -98,11 +98,11 @@ void shouldThrowWhenConfigurationsAreMissing() { @Test void shouldThrowWhenNoBasePackageConfigured() { // when - DefaultStandaloneApplication standaloneApplication = - DefaultStandaloneApplication.builder().buildAndStart(); - - // then - assertThatRuntimeException() - .isThrownBy(() -> standaloneApplication.getAsyncApiService().getAsyncAPI()); + try (DefaultStandaloneApplication standaloneApplication = + DefaultStandaloneApplication.builder().buildAndStart()) { + // then + assertThatRuntimeException() + .isThrownBy(() -> standaloneApplication.getAsyncApiService().getAsyncAPI()); + } } } diff --git a/springwolf-examples/springwolf-amqp-example/src/main/java/io/github/springwolf/examples/amqp/configuration/RabbitConfiguration.java b/springwolf-examples/springwolf-amqp-example/src/main/java/io/github/springwolf/examples/amqp/configuration/RabbitConfiguration.java index d4decbe3b..c3395086c 100644 --- a/springwolf-examples/springwolf-amqp-example/src/main/java/io/github/springwolf/examples/amqp/configuration/RabbitConfiguration.java +++ b/springwolf-examples/springwolf-amqp-example/src/main/java/io/github/springwolf/examples/amqp/configuration/RabbitConfiguration.java @@ -2,7 +2,7 @@ package io.github.springwolf.examples.amqp.configuration; import io.github.springwolf.examples.amqp.AmqpConstants; -import io.github.springwolf.examples.amqp.dtos.AnotherPayloadDto; +import io.github.springwolf.examples.amqp.dtos.ExamplePayloadDto; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Exchange; @@ -51,7 +51,7 @@ public Queue multiPayloadQueue() { } /** - * Defined by @RabbitListener annotation in {@link io.github.springwolf.examples.amqp.consumers.ExampleConsumer#bindingsExample(AnotherPayloadDto)} + * Defined by @RabbitListener annotation in {@link io.github.springwolf.examples.amqp.consumers.ExampleConsumer#bindingsExample(ExamplePayloadDto)} */ @Bean public Queue exampleBindingsQueue() { @@ -59,7 +59,7 @@ public Queue exampleBindingsQueue() { } /** - * Defined by @RabbitListener annotation in {@link io.github.springwolf.examples.amqp.consumers.ExampleConsumer#bindingsExample(AnotherPayloadDto)} + * Defined by @RabbitListener annotation in {@link io.github.springwolf.examples.amqp.consumers.ExampleConsumer#bindingsExample(ExamplePayloadDto)} */ @Bean public Binding exampleTopicBinding(Queue exampleBindingsQueue, Exchange exampleTopicExchange) { diff --git a/springwolf-examples/springwolf-amqp-example/src/main/java/io/github/springwolf/examples/amqp/configuration/RabbitMqReadinessVerifier.java b/springwolf-examples/springwolf-amqp-example/src/main/java/io/github/springwolf/examples/amqp/configuration/RabbitMqReadinessVerifier.java index 4813a9aca..6d78fc833 100644 --- a/springwolf-examples/springwolf-amqp-example/src/main/java/io/github/springwolf/examples/amqp/configuration/RabbitMqReadinessVerifier.java +++ b/springwolf-examples/springwolf-amqp-example/src/main/java/io/github/springwolf/examples/amqp/configuration/RabbitMqReadinessVerifier.java @@ -8,6 +8,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.LockSupport; + @Configuration(proxyBeanMethods = false) @Profile("!test") public class RabbitMqReadinessVerifier { @@ -23,8 +26,8 @@ public RabbitMqReadinessVerifier(ConnectionFactory connectionFactory) { } private void verifyRabbitMqIsUp() { - long startTime = System.currentTimeMillis(); - while (System.currentTimeMillis() - startTime < RABBITMQ_MAX_CONNECT_TIMEOUT_MS) { + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(RABBITMQ_MAX_CONNECT_TIMEOUT_MS); + while (System.nanoTime() < deadline) { try { RabbitAdmin admin = new RabbitAdmin(connectionFactory); admin.afterPropertiesSet(); @@ -32,15 +35,15 @@ private void verifyRabbitMqIsUp() { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.execute(channel -> null); // dummy operation throws exception when amqp is not up - break; + return; } catch (AmqpConnectException e) { - try { - Thread.sleep(RABBITMQ_INTERVAL_WAIT_MS); - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("RabbitMQ is not running", ie); + LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(RABBITMQ_INTERVAL_WAIT_MS)); + if (Thread.currentThread().isInterrupted()) { + throw new IllegalStateException("RabbitMQ is not running", new InterruptedException()); } } } + + throw new IllegalStateException("Timed out waiting for RabbitMQ to become available"); } } diff --git a/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/AmqpProducerSystemTest.java b/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/AmqpProducerSystemTest.java index 0b39154af..0e85b1b9a 100644 --- a/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/AmqpProducerSystemTest.java +++ b/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/AmqpProducerSystemTest.java @@ -11,7 +11,6 @@ import org.junit.jupiter.api.TestMethodOrder; import org.springframework.amqp.AmqpIOException; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; -import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; @@ -76,12 +75,17 @@ static void registerActiveMqBroker(DynamicPropertyRegistry registry) { @Test @Order(1) void verifyAmqpIsAvailable() { - ConnectionFactory factory = new CachingConnectionFactory("localhost"); + CachingConnectionFactory factory = new CachingConnectionFactory("localhost"); - await().atMost(60, SECONDS) - .ignoreException(AmqpIOException.class) - .untilAsserted( - () -> assertThat(factory.createConnection().isOpen()).isTrue()); + try { + await().atMost(60, SECONDS).ignoreException(AmqpIOException.class).untilAsserted(() -> { + try (var connection = factory.createConnection()) { + assertThat(connection.isOpen()).isTrue(); + } + }); + } finally { + factory.destroy(); + } } @Test diff --git a/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/ApiSystemTest.java b/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/ApiSystemTest.java index 5429c8e03..62e2ee235 100644 --- a/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/ApiSystemTest.java +++ b/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/ApiSystemTest.java @@ -50,8 +50,10 @@ void asyncapiDocsShouldReturnTheCorrectJsonResponse() throws Exception { String url = baseUrl() + "/springwolf/docs"; String actual = restTemplate.getForObject(url, String.class); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/PayloadSchemaFormatIntegrationTest.java b/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/PayloadSchemaFormatIntegrationTest.java index 5bba51913..229e4ec46 100644 --- a/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/PayloadSchemaFormatIntegrationTest.java +++ b/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/PayloadSchemaFormatIntegrationTest.java @@ -28,24 +28,26 @@ void asyncApiStandaloneArtifactTest() throws Exception { .getPropertySources() .addFirst(new MapPropertySource( "env", Map.of("springwolf.docket.payload-schema-format", "openapi_v3_1"))); - StandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() + try (StandaloneApplication standaloneApplication = DefaultStandaloneApplication.builder() .setEnvironment(environment) - .buildAndStart(); - - // when - AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); - - // then - assertThat(asyncApi).isNotNull(); - - AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); - String actual = serializerService.toJsonString(asyncApi); - String actualPatched = actual.replace("localhost:5672", "amqp:5672"); - Files.writeString(Path.of("src", "test", "resources", "asyncapi.openapiv31.actual.json"), actualPatched); - - // then - InputStream s = this.getClass().getResourceAsStream("/asyncapi.openapiv31.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); - assertThat(actualPatched).isEqualTo(expected); + .buildAndStart()) { + // when + AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); + + // then + assertThat(asyncApi).isNotNull(); + + AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); + String actual = serializerService.toJsonString(asyncApi); + String actualPatched = actual.replace("localhost:5672", "amqp:5672"); + Files.writeString(Path.of("src", "test", "resources", "asyncapi.openapiv31.actual.json"), actualPatched); + + // then + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.openapiv31.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + assertThat(actualPatched).isEqualTo(expected); + } } } diff --git a/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/StandaloneTest.java b/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/StandaloneTest.java index dd91245fc..830d9b42b 100644 --- a/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/StandaloneTest.java +++ b/springwolf-examples/springwolf-amqp-example/src/test/java/io/github/springwolf/examples/amqp/StandaloneTest.java @@ -23,26 +23,27 @@ class StandaloneTest { @Test void asyncApiStandaloneArtifactTest() throws Exception { // given - StandaloneApplication standaloneApplication = - DefaultStandaloneApplication.builder().buildAndStart(); - - // when - AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); - - // then - assertThat(asyncApi).isNotNull(); - - AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); - String actual = serializerService.toJsonString(asyncApi); - String actualPatched = actual.replace("localhost:5672", "amqp:5672"); - Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actualPatched); - - // then - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); - - assertThat(removeDifferencesDueToAmqpSpringBeans(serializerService, actualPatched)) - .isEqualTo(removeDifferencesDueToAmqpSpringBeans(serializerService, expected)); + try (StandaloneApplication standaloneApplication = + DefaultStandaloneApplication.builder().buildAndStart()) { + // when + AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); + + // then + assertThat(asyncApi).isNotNull(); + + AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); + String actual = serializerService.toJsonString(asyncApi); + String actualPatched = actual.replace("localhost:5672", "amqp:5672"); + Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actualPatched); + + // then + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + assertThat(removeDifferencesDueToAmqpSpringBeans(serializerService, actualPatched)) + .isEqualTo(removeDifferencesDueToAmqpSpringBeans(serializerService, expected)); + } } /** diff --git a/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/ApiIntegrationTest.java b/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/ApiIntegrationTest.java index 21358eae5..8083c987d 100644 --- a/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/ApiIntegrationTest.java +++ b/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/ApiIntegrationTest.java @@ -39,8 +39,10 @@ void asyncApiResourceArtifactTest() throws Exception { String actualPatched = actual.replace(bootstrapServers, "kafka:29092"); Files.writeString(Path.of("src", "test", "resources", "asyncapi.actual.json"), actualPatched); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actualPatched).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/ApiSystemTest.java b/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/ApiSystemTest.java index 89b6b3c31..5f56c3169 100644 --- a/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/ApiSystemTest.java +++ b/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/ApiSystemTest.java @@ -50,8 +50,10 @@ void asyncapiDocsShouldReturnTheCorrectJsonResponse() throws Exception { String url = baseUrl() + "/springwolf/docs"; String actual = restTemplate.getForObject(url, String.class); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/StandaloneTest.java b/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/StandaloneTest.java index 0b42b6b72..28510e970 100644 --- a/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/StandaloneTest.java +++ b/springwolf-examples/springwolf-cloud-stream-example/src/test/java/io/github/springwolf/examples/cloudstream/StandaloneTest.java @@ -33,23 +33,25 @@ static void beforeAll() { @Test void asyncApiStandaloneArtifactTest() throws Exception { // given - StandaloneApplication standaloneApplication = - DefaultStandaloneApplication.builder().buildAndStart(); - - // when - AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); - - // then - assertThat(asyncApi).isNotNull(); - - AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); - String actual = serializerService.toJsonString(asyncApi); - String actualPatched = actual.replace("localhost:9095", "kafka:29092"); - Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actualPatched); - - // then - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); - assertThat(actualPatched).isEqualTo(expected); + try (StandaloneApplication standaloneApplication = + DefaultStandaloneApplication.builder().buildAndStart()) { + // when + AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); + + // then + assertThat(asyncApi).isNotNull(); + + AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); + String actual = serializerService.toJsonString(asyncApi); + String actualPatched = actual.replace("localhost:9095", "kafka:29092"); + Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actualPatched); + + // then + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + assertThat(actualPatched).isEqualTo(expected); + } } } diff --git a/springwolf-examples/springwolf-jms-example/build.gradle b/springwolf-examples/springwolf-jms-example/build.gradle index 259deb12f..c26b4cc7b 100644 --- a/springwolf-examples/springwolf-jms-example/build.gradle +++ b/springwolf-examples/springwolf-jms-example/build.gradle @@ -56,6 +56,8 @@ dependencies { testImplementation libs.testcontainers testImplementation libs.testcontainers.junit.jupiter + testImplementation libs.jspecify + testAnnotationProcessor libs.lombok testCompileOnly libs.lombok diff --git a/springwolf-examples/springwolf-jms-example/src/main/java/io/github/springwolf/examples/jms/producers/AnotherProducer.java b/springwolf-examples/springwolf-jms-example/src/main/java/io/github/springwolf/examples/jms/producers/AnotherProducer.java index 2511084f0..fd1d14ed5 100644 --- a/springwolf-examples/springwolf-jms-example/src/main/java/io/github/springwolf/examples/jms/producers/AnotherProducer.java +++ b/springwolf-examples/springwolf-jms-example/src/main/java/io/github/springwolf/examples/jms/producers/AnotherProducer.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.examples.jms.producers; -import io.github.springwolf.bindings.generic.annotation.AsyncGenericOperationBinding; +import io.github.springwolf.bindings.generic.annotations.AsyncGenericOperationBinding; import io.github.springwolf.bindings.jms.annotations.JmsAsyncOperationBinding; import io.github.springwolf.core.asyncapi.annotations.AsyncOperation; import io.github.springwolf.core.asyncapi.annotations.AsyncPublisher; diff --git a/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/ApiIntegrationTest.java b/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/ApiIntegrationTest.java index e76e1e5fc..4288f1887 100644 --- a/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/ApiIntegrationTest.java +++ b/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/ApiIntegrationTest.java @@ -36,8 +36,10 @@ void asyncApiResourceArtifactTest() throws Exception { String actualPatched = actual.replace("localhost:61616", "activemq:61616"); Files.writeString(Path.of("src", "test", "resources", "asyncapi.actual.json"), actualPatched); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actualPatched).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/ApiSystemTest.java b/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/ApiSystemTest.java index 515bd1599..fd64a17fc 100644 --- a/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/ApiSystemTest.java +++ b/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/ApiSystemTest.java @@ -50,8 +50,10 @@ void asyncapiDocsShouldReturnTheCorrectJsonResponse() throws Exception { String url = baseUrl() + "/springwolf/docs"; String actual = restTemplate.getForObject(url, String.class); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/JmsTestContainerExtension.java b/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/JmsTestContainerExtension.java index 839722889..cece7f97b 100644 --- a/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/JmsTestContainerExtension.java +++ b/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/JmsTestContainerExtension.java @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.examples.jms; +import org.jspecify.annotations.NonNull; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.testcontainers.containers.GenericContainer; @@ -21,7 +22,7 @@ public class JmsTestContainerExtension implements BeforeAllCallback, AutoCloseab .withExposedPorts(61616); @Override - public void beforeAll(ExtensionContext extensionContext) { + public void beforeAll(@NonNull ExtensionContext extensionContext) { if (!started) { started = true; diff --git a/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/StandaloneTest.java b/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/StandaloneTest.java index bd5a11f8e..ba8bc5e06 100644 --- a/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/StandaloneTest.java +++ b/springwolf-examples/springwolf-jms-example/src/test/java/io/github/springwolf/examples/jms/StandaloneTest.java @@ -20,23 +20,25 @@ class StandaloneTest { @Test void asyncApiStandaloneArtifactTest() throws Exception { // given - StandaloneApplication standaloneApplication = - DefaultStandaloneApplication.builder().buildAndStart(); - - // when - AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); - - // then - assertThat(asyncApi).isNotNull(); - - AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); - String actual = serializerService.toJsonString(asyncApi); - String actualPatched = actual.replace("localhost:61616", "activemq:61616"); - Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actualPatched); - - // then - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); - assertThat(actualPatched).isEqualTo(expected); + try (StandaloneApplication standaloneApplication = + DefaultStandaloneApplication.builder().buildAndStart()) { + // when + AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); + + // then + assertThat(asyncApi).isNotNull(); + + AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); + String actual = serializerService.toJsonString(asyncApi); + String actualPatched = actual.replace("localhost:61616", "activemq:61616"); + Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actualPatched); + + // then + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + assertThat(actualPatched).isEqualTo(expected); + } } } diff --git a/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/configuration/CustomWebSecurityConfigurerAdapter.java b/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/configuration/CustomWebSecurityConfigurerAdapter.java index 9d9f15728..dd620cca2 100644 --- a/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/configuration/CustomWebSecurityConfigurerAdapter.java +++ b/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/configuration/CustomWebSecurityConfigurerAdapter.java @@ -19,7 +19,7 @@ public class CustomWebSecurityConfigurerAdapter { private static final String UI_RESOURCES = "/springwolf/**"; @Bean - public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + public SecurityFilterChain filterChain(HttpSecurity http) { return http.authorizeHttpRequests(it -> it // allow anonymous access to all actuator endpoint .requestMatchers("/actuator/**") diff --git a/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/configuration/ProtobufModelConverter.java b/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/configuration/ProtobufModelConverter.java index 8587783e0..5e9a27326 100644 --- a/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/configuration/ProtobufModelConverter.java +++ b/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/configuration/ProtobufModelConverter.java @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.examples.kafka.configuration; +import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Message; @@ -32,7 +33,8 @@ class ProtobufModelConverter implements ModelConverter { } @Override - public Schema resolve(AnnotatedType annotatedType, ModelConverterContext context, Iterator chain) { + public Schema resolve( + AnnotatedType annotatedType, ModelConverterContext context, Iterator chain) { if (annotatedType == null) { return null; } @@ -43,19 +45,22 @@ public Schema resolve(AnnotatedType annotatedType, ModelConverterContext context return chain.hasNext() ? chain.next().resolve(annotatedType, context, chain) : null; } Descriptor descriptor = defaultInstance(rawClass).getDescriptorForType(); - Schema wellKnownTypeSchema = wellKnownTypeSchema(descriptor); + Schema wellKnownTypeSchema = wellKnownTypeSchema(descriptor); if (wellKnownTypeSchema != null) { return wellKnownTypeSchema; } String name = modelName(rawClass); - Schema model = new Schema<>().name(name).title(rawClass.getSimpleName()).type("object"); + Schema model = new Schema<>(); + model.setName(name); + model.setTitle(rawClass.getSimpleName()); + model.setType("object"); model.setProperties(new LinkedHashMap<>()); for (FieldDescriptor field : descriptor.getFields()) { Method getter = getter(rawClass, field); Class javaType = valueClass(getter, field); - Schema property = schema(field, javaType, context); + Schema property = schema(field, javaType, context); if (field.isRepeated() && !field.isMapField()) { property = new ArraySchema().items(property); } else if (field.isMapField()) { @@ -73,7 +78,7 @@ public Schema resolve(AnnotatedType annotatedType, ModelConverterContext context return model; } - private Schema schema(FieldDescriptor field, Class javaType, ModelConverterContext context) { + private Schema schema(FieldDescriptor field, Class javaType, ModelConverterContext context) { return switch (field.getType()) { case BOOL -> new BooleanSchema(); case BYTES -> new StringSchema().format("byte"); @@ -87,7 +92,7 @@ private Schema schema(FieldDescriptor field, Class javaType, ModelConverterCo }; } - private Schema enumSchema(FieldDescriptor field, Class enumClass) { + private Schema enumSchema(FieldDescriptor field, Class enumClass) { StringSchema schema = new StringSchema(); schema.setTitle(field.getEnumType().getName()); if (enumClass.isEnum()) { @@ -96,13 +101,13 @@ private Schema enumSchema(FieldDescriptor field, Class enumClass) { .toList()); } else { schema.setEnum(field.getEnumType().getValues().stream() - .map(value -> value.getName()) + .map(Descriptors.EnumValueDescriptor::getName) .toList()); } return schema; } - private Schema messageSchema(FieldDescriptor field, Class messageClass, ModelConverterContext context) { + private Schema messageSchema(FieldDescriptor field, Class messageClass, ModelConverterContext context) { String fullName = field.getMessageType().getFullName(); if ("google.protobuf.Timestamp".equals(fullName)) { return new StringSchema().format("date-time"); @@ -148,7 +153,7 @@ private Message defaultInstance(Class type) { } } - private Schema wellKnownTypeSchema(Descriptor descriptor) { + private Schema wellKnownTypeSchema(Descriptor descriptor) { return switch (descriptor.getFullName()) { case "google.protobuf.Timestamp" -> new StringSchema().format("date-time"); case "google.protobuf.Duration", "google.protobuf.FieldMask" -> new StringSchema(); diff --git a/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/consumers/BeanRefConsumer.java b/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/consumers/BeanRefConsumer.java index 5130e4739..81e63dd62 100644 --- a/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/consumers/BeanRefConsumer.java +++ b/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/consumers/BeanRefConsumer.java @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.examples.kafka.consumers; +import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.kafka.annotation.KafkaListener; @@ -9,6 +10,7 @@ @Component @RequiredArgsConstructor @Slf4j +@Getter public class BeanRefConsumer { private final String topic = "bean-ref-topic"; @@ -18,12 +20,4 @@ public class BeanRefConsumer { public void listen(Object message) { log.debug("Received new message in {}: {}", this.topic, message.toString()); } - - public String getTopic() { - return this.topic; - } - - public String getGroup() { - return this.group; - } } diff --git a/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/producers/AnotherProducer.java b/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/producers/AnotherProducer.java index ae331ddab..12b771d64 100644 --- a/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/producers/AnotherProducer.java +++ b/springwolf-examples/springwolf-kafka-example/src/main/java/io/github/springwolf/examples/kafka/producers/AnotherProducer.java @@ -7,17 +7,17 @@ import io.github.springwolf.core.asyncapi.annotations.AsyncPublisher; import io.github.springwolf.examples.kafka.configuration.KafkaConfiguration; import io.github.springwolf.examples.kafka.dtos.AnotherPayloadDto; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Component; import static org.springframework.kafka.support.mapping.DefaultJacksonJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME; @Component +@RequiredArgsConstructor public class AnotherProducer { - @Autowired - private KafkaTemplate kafkaTemplate; + private final KafkaTemplate kafkaTemplate; @AsyncPublisher( operation = diff --git a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiIntegrationTest.java b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiIntegrationTest.java index 5a5a363df..b8212b474 100644 --- a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiIntegrationTest.java +++ b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiIntegrationTest.java @@ -40,8 +40,10 @@ void asyncApiResourceArtifactTest() throws Exception { String actualPatched = actual.replace(bootstrapServers, "kafka:29092"); Files.writeString(Path.of("src", "test", "resources", "asyncapi.actual.json"), actualPatched); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actualPatched).isEqualTo(expected); } @@ -59,8 +61,10 @@ void asyncApiResourceArtifactYamlTest() throws Exception { String actualPatched = actual.replace(bootstrapServers, "kafka:29092").trim(); Files.writeString(Path.of("src", "test", "resources", "asyncapi.actual.yaml"), actualPatched); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.yaml"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.yaml")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actualPatched).isEqualTo(expected); } @@ -73,8 +77,10 @@ void asyncApiResourceForVehicleGroupArtifactTest() throws Exception { String actualPatched = actual.replace(bootstrapServers, "kafka:29092").trim(); Files.writeString(Path.of("src", "test", "resources", "groups", "vehicles.actual.json"), actualPatched); - InputStream s = this.getClass().getResourceAsStream("/groups/vehicles.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/groups/vehicles.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actualPatched).isEqualTo(expected); } @@ -85,8 +91,10 @@ void uiConfigTest() throws Exception { String actual = restTemplate.getForObject(url, String.class); Files.writeString(Path.of("src", "test", "resources", "ui-config.actual.json"), actual); - InputStream s = this.getClass().getResourceAsStream("/ui-config.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/ui-config.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiIntegrationWithActuatorIntegrationTest.java b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiIntegrationWithActuatorIntegrationTest.java index 37625fa74..6001a9cb6 100644 --- a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiIntegrationWithActuatorIntegrationTest.java +++ b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiIntegrationWithActuatorIntegrationTest.java @@ -38,8 +38,10 @@ void asyncApiResourceArtifactTest() throws Exception { String url = "http://localhost:" + managementPort + "/actuator/springwolf"; String actual = restTemplate.getForObject(url, String.class); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expectedWithoutServersKafkaUrlPatch = new String(s.readAllBytes(), StandardCharsets.UTF_8); + String expectedWithoutServersKafkaUrlPatch; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expectedWithoutServersKafkaUrlPatch = new String(s.readAllBytes(), StandardCharsets.UTF_8); + } // When running with EmbeddedKafka, the kafka bootstrap server does run on random ports String expected = expectedWithoutServersKafkaUrlPatch .replace("kafka:29092", bootstrapServers) diff --git a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiSystemTest.java b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiSystemTest.java index 639bdc19a..ec73b6e65 100644 --- a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiSystemTest.java +++ b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/ApiSystemTest.java @@ -50,8 +50,10 @@ void asyncapiDocsShouldReturnTheCorrectJsonResponse() throws Exception { String url = baseUrl() + "/springwolf/docs"; String actual = restTemplate.getForObject(url, String.class); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/KafkaProducerSystemTest.java b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/KafkaProducerSystemTest.java index 38dac2510..0ee731ffb 100644 --- a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/KafkaProducerSystemTest.java +++ b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/KafkaProducerSystemTest.java @@ -64,7 +64,7 @@ private String baseUrl() { } @Test - void producerCanUseSpringwolfConfigurationToSendMessage() throws Exception { + void producerCanUseSpringwolfConfigurationToSendMessage() { // given HttpHeaders headers = new HttpHeaders(); headers.put("Content-Type", List.of("application/json")); @@ -102,7 +102,7 @@ void producerCanUseSpringwolfConfigurationToSendMessage() throws Exception { @DisabledIf( value = "withoutSchemaRegistry", disabledReason = "because it requires a running kafka-schema-registry instance (docker image= ~1GB).") - void producerCanUseSpringwolfConfigurationToSendAvroMessage() throws Exception { + void producerCanUseSpringwolfConfigurationToSendAvroMessage() { // given HttpHeaders headers = new HttpHeaders(); headers.put("Content-Type", List.of("application/json")); diff --git a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/OpenApiGeneratorSystemTest.java b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/OpenApiGeneratorSystemTest.java index 8b9e4f56d..17ab9ec02 100644 --- a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/OpenApiGeneratorSystemTest.java +++ b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/OpenApiGeneratorSystemTest.java @@ -20,12 +20,14 @@ class OpenApiGeneratorSystemTest { @Test void asyncApiResourceArtifactTest() throws Exception { - InputStream expectedStream = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = IOUtils.toString(expectedStream, StandardCharsets.UTF_8); - - InputStream actualStream = this.getClass().getResourceAsStream("/openapi-generated.json"); - String actual = IOUtils.toString(actualStream, StandardCharsets.UTF_8) - .replace("\\u003c", "<") // openapi generator replaces "<" with its unicode representation + String expected; + String actual; + try (InputStream expectedStream = this.getClass().getResourceAsStream("/asyncapi.json"); + InputStream actualStream = this.getClass().getResourceAsStream("/openapi-generated.json")) { + expected = IOUtils.toString(expectedStream, StandardCharsets.UTF_8); + actual = IOUtils.toString(actualStream, StandardCharsets.UTF_8); + } + actual = actual.replace("\\u003c", "<") // openapi generator replaces "<" with its unicode representation .replace("\\u003d", "=") // openapi generator replaces equal (=) with its unicode representation .replace("\\u003e", ">") // openapi generator replaces ">" with its unicode representation .replace( diff --git a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/SpringContextIntegrationTest.java b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/SpringContextIntegrationTest.java index a7e436817..799409a59 100644 --- a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/SpringContextIntegrationTest.java +++ b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/SpringContextIntegrationTest.java @@ -63,7 +63,7 @@ void allChannelsAreFound() { } @Test - void protobufSchemaContainsOnlyProtobufFields() throws Exception { + void protobufSchemaContainsOnlyProtobufFields() { var protobufSchemaName = ExamplePayloadProtobufDto.Message.class.getName().replace("$", "."); assertThat(asyncApiService diff --git a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/StandaloneTest.java b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/StandaloneTest.java index 2cfb60e71..f4d564093 100644 --- a/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/StandaloneTest.java +++ b/springwolf-examples/springwolf-kafka-example/src/test/java/io/github/springwolf/examples/kafka/StandaloneTest.java @@ -20,23 +20,25 @@ class StandaloneTest { @Test void asyncApiStandaloneArtifactTest() throws Exception { // given - StandaloneApplication standaloneApplication = - DefaultStandaloneApplication.builder().buildAndStart(); - - // when - AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); - - // then - assertThat(asyncApi).isNotNull(); - - AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); - String actual = serializerService.toJsonString(asyncApi); - String actualPatched = actual.replace("localhost:9092", "kafka:29092"); - Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.actual.json"), actualPatched); - - // then - InputStream s = this.getClass().getResourceAsStream("/asyncapi.standalone.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); - assertThat(actualPatched).isEqualTo(expected); + try (StandaloneApplication standaloneApplication = + DefaultStandaloneApplication.builder().buildAndStart()) { + // when + AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); + + // then + assertThat(asyncApi).isNotNull(); + + AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); + String actual = serializerService.toJsonString(asyncApi); + String actualPatched = actual.replace("localhost:9092", "kafka:29092"); + Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.actual.json"), actualPatched); + + // then + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.standalone.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + assertThat(actualPatched).isEqualTo(expected); + } } } diff --git a/springwolf-examples/springwolf-sns-example/build.gradle b/springwolf-examples/springwolf-sns-example/build.gradle index 80f20a27a..5469f57fa 100644 --- a/springwolf-examples/springwolf-sns-example/build.gradle +++ b/springwolf-examples/springwolf-sns-example/build.gradle @@ -52,6 +52,8 @@ dependencies { testImplementation libs.testcontainers.junit.jupiter testImplementation libs.testcontainers.localstack + testImplementation libs.jspecify + testAnnotationProcessor libs.lombok testCompileOnly libs.lombok diff --git a/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/ApiIntegrationTest.java b/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/ApiIntegrationTest.java index 3a5b2cc30..9a1b605a4 100644 --- a/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/ApiIntegrationTest.java +++ b/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/ApiIntegrationTest.java @@ -42,8 +42,10 @@ void asyncApiResourceArtifactTest() throws Exception { String actual = restTemplate.getForObject(url, String.class); Files.writeString(Path.of("src", "test", "resources", "asyncapi.actual.json"), actual); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/ApiSystemTest.java b/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/ApiSystemTest.java index 5384ee5c7..84682111f 100644 --- a/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/ApiSystemTest.java +++ b/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/ApiSystemTest.java @@ -50,8 +50,10 @@ void asyncapiDocsShouldReturnTheCorrectJsonResponse() throws Exception { String url = baseUrl() + "/springwolf/docs"; String actual = restTemplate.getForObject(url, String.class); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/SnsTestContainerExtension.java b/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/SnsTestContainerExtension.java index 363735674..ba1bb945c 100644 --- a/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/SnsTestContainerExtension.java +++ b/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/SnsTestContainerExtension.java @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.examples.sns; +import org.jspecify.annotations.NonNull; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.springframework.test.context.DynamicPropertyRegistry; @@ -24,7 +25,7 @@ public class SnsTestContainerExtension implements BeforeAllCallback, AutoCloseab new LocalStackContainer(DockerImageName.parse("localstack/localstack:3.7.2")).withServices(SNS); @Override - public void beforeAll(ExtensionContext extensionContext) throws Exception { + public void beforeAll(@NonNull ExtensionContext extensionContext) throws Exception { if (!started) { started = true; diff --git a/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/StandaloneTest.java b/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/StandaloneTest.java index f0d8ceae9..9a6c80e0c 100644 --- a/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/StandaloneTest.java +++ b/springwolf-examples/springwolf-sns-example/src/test/java/io/github/springwolf/examples/sns/StandaloneTest.java @@ -20,22 +20,24 @@ class StandaloneTest { @Test void asyncApiStandaloneArtifactTest() throws Exception { // given - StandaloneApplication standaloneApplication = - DefaultStandaloneApplication.builder().buildAndStart(); - - // when - AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); - - // then - assertThat(asyncApi).isNotNull(); - - AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); - String actual = serializerService.toJsonString(asyncApi); - Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actual); - - // then - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); - org.assertj.core.api.Assertions.assertThat(actual).isEqualTo(expected); + try (StandaloneApplication standaloneApplication = + DefaultStandaloneApplication.builder().buildAndStart()) { + // when + AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); + + // then + assertThat(asyncApi).isNotNull(); + + AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); + String actual = serializerService.toJsonString(asyncApi); + Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actual); + + // then + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + assertThat(actual).isEqualTo(expected); + } } } diff --git a/springwolf-examples/springwolf-sqs-example/build.gradle b/springwolf-examples/springwolf-sqs-example/build.gradle index 206462a96..71774bd37 100644 --- a/springwolf-examples/springwolf-sqs-example/build.gradle +++ b/springwolf-examples/springwolf-sqs-example/build.gradle @@ -58,6 +58,8 @@ dependencies { testAnnotationProcessor libs.lombok testCompileOnly libs.lombok + testImplementation libs.jspecify + testImplementation libs.junit.jupiter.api testRuntimeOnly libs.junit.jupiter testRuntimeOnly libs.junit.plattform.launcher diff --git a/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/ApiIntegrationTest.java b/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/ApiIntegrationTest.java index e1bc5fc9e..c8fcaa31e 100644 --- a/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/ApiIntegrationTest.java +++ b/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/ApiIntegrationTest.java @@ -38,8 +38,10 @@ void asyncApiResourceArtifactTest() throws Exception { String actual = restTemplate.getForObject(url, String.class); Files.writeString(Path.of("src", "test", "resources", "asyncapi.actual.json"), actual); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/ApiSystemTest.java b/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/ApiSystemTest.java index 46d60e040..a37fd9a9d 100644 --- a/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/ApiSystemTest.java +++ b/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/ApiSystemTest.java @@ -50,8 +50,10 @@ void asyncapiDocsShouldReturnTheCorrectJsonResponse() throws Exception { String url = baseUrl() + "/springwolf/docs"; String actual = restTemplate.getForObject(url, String.class); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/SqsTestContainerExtension.java b/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/SqsTestContainerExtension.java index 28b4ce52b..e6645098c 100644 --- a/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/SqsTestContainerExtension.java +++ b/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/SqsTestContainerExtension.java @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.examples.sqs; +import org.jspecify.annotations.NonNull; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.springframework.test.context.DynamicPropertyRegistry; @@ -24,7 +25,7 @@ public class SqsTestContainerExtension implements BeforeAllCallback, AutoCloseab new LocalStackContainer(DockerImageName.parse("localstack/localstack:3.7.2")).withServices(SQS); @Override - public void beforeAll(ExtensionContext extensionContext) throws Exception { + public void beforeAll(@NonNull ExtensionContext extensionContext) throws Exception { if (!started) { started = true; diff --git a/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/StandaloneTest.java b/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/StandaloneTest.java index cbee876db..cb2a93904 100644 --- a/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/StandaloneTest.java +++ b/springwolf-examples/springwolf-sqs-example/src/test/java/io/github/springwolf/examples/sqs/StandaloneTest.java @@ -20,22 +20,24 @@ class StandaloneTest { @Test void asyncApiStandaloneArtifactTest() throws Exception { // given - StandaloneApplication standaloneApplication = - DefaultStandaloneApplication.builder().buildAndStart(); - - // when - AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); - - // then - assertThat(asyncApi).isNotNull(); - - AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); - String actual = serializerService.toJsonString(asyncApi); - Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actual); - - // then - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); - org.assertj.core.api.Assertions.assertThat(actual).isEqualTo(expected); + try (StandaloneApplication standaloneApplication = + DefaultStandaloneApplication.builder().buildAndStart()) { + // when + AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); + + // then + assertThat(asyncApi).isNotNull(); + + AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); + String actual = serializerService.toJsonString(asyncApi); + Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actual); + + // then + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + assertThat(actual).isEqualTo(expected); + } } } diff --git a/springwolf-examples/springwolf-stomp-example/build.gradle b/springwolf-examples/springwolf-stomp-example/build.gradle index 6309ff3a5..4fc350867 100644 --- a/springwolf-examples/springwolf-stomp-example/build.gradle +++ b/springwolf-examples/springwolf-stomp-example/build.gradle @@ -40,6 +40,7 @@ dependencies { implementation libs.swagger.annotations implementation libs.commons.logging + implementation libs.jspecify implementation libs.slf4j.api testImplementation libs.assertj.core diff --git a/springwolf-examples/springwolf-stomp-example/src/main/java/io/github/springwolf/examples/stomp/config/WebSocketConfig.java b/springwolf-examples/springwolf-stomp-example/src/main/java/io/github/springwolf/examples/stomp/config/WebSocketConfig.java index 1f3d3a251..d1724e407 100644 --- a/springwolf-examples/springwolf-stomp-example/src/main/java/io/github/springwolf/examples/stomp/config/WebSocketConfig.java +++ b/springwolf-examples/springwolf-stomp-example/src/main/java/io/github/springwolf/examples/stomp/config/WebSocketConfig.java @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.examples.stomp.config; +import org.jspecify.annotations.NonNull; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; @@ -18,7 +19,7 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override - public void configureMessageBroker(MessageBrokerRegistry registry) { + public void configureMessageBroker(@NonNull MessageBrokerRegistry registry) { WebSocketMessageBrokerConfigurer.super.configureMessageBroker(registry); registry.enableSimpleBroker(WEBSOCKET_BROKER_TOPIC, WEBSOCKET_BROKER_QUEUE); @@ -27,7 +28,7 @@ public void configureMessageBroker(MessageBrokerRegistry registry) { } @Override - public void registerStompEndpoints(StompEndpointRegistry registry) { + public void registerStompEndpoints(@NonNull StompEndpointRegistry registry) { WebSocketMessageBrokerConfigurer.super.registerStompEndpoints(registry); registry.addEndpoint(WEBSOCKET_ENDPOINT) diff --git a/springwolf-examples/springwolf-stomp-example/src/main/java/io/github/springwolf/examples/stomp/config/WebSocketHandshake.java b/springwolf-examples/springwolf-stomp-example/src/main/java/io/github/springwolf/examples/stomp/config/WebSocketHandshake.java index 38ecc18b1..5fa62da6c 100644 --- a/springwolf-examples/springwolf-stomp-example/src/main/java/io/github/springwolf/examples/stomp/config/WebSocketHandshake.java +++ b/springwolf-examples/springwolf-stomp-example/src/main/java/io/github/springwolf/examples/stomp/config/WebSocketHandshake.java @@ -2,6 +2,7 @@ package io.github.springwolf.examples.stomp.config; import com.sun.security.auth.UserPrincipal; +import org.jspecify.annotations.NonNull; import org.springframework.http.server.ServerHttpRequest; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; @@ -14,7 +15,7 @@ public class WebSocketHandshake extends DefaultHandshakeHandler { @Override protected Principal determineUser( - ServerHttpRequest request, WebSocketHandler wsHandler, Map attributes) { + ServerHttpRequest request, @NonNull WebSocketHandler wsHandler, @NonNull Map attributes) { Principal principal = request.getPrincipal(); if (principal == null) { final var uniqueName = UUID.randomUUID().toString(); diff --git a/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/ApiIntegrationTest.java b/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/ApiIntegrationTest.java index 5bc64b2f3..2dd6ccf72 100644 --- a/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/ApiIntegrationTest.java +++ b/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/ApiIntegrationTest.java @@ -29,8 +29,10 @@ void asyncApiResourceArtifactTest() throws Exception { String actual = restTemplate.getForObject(url, String.class); Files.writeString(Path.of("src", "test", "resources", "asyncapi.actual.json"), actual); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/ApiSystemTest.java b/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/ApiSystemTest.java index 2a9b6507d..2328a6f46 100644 --- a/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/ApiSystemTest.java +++ b/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/ApiSystemTest.java @@ -48,8 +48,10 @@ void asyncapiDocsShouldReturnTheCorrectJsonResponse() throws Exception { String url = baseUrl() + "/springwolf/docs"; String actual = restTemplate.getForObject(url, String.class); - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } assertThat(actual).isEqualTo(expected); } diff --git a/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/StandaloneTest.java b/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/StandaloneTest.java index aef12a204..d0165170f 100644 --- a/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/StandaloneTest.java +++ b/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/StandaloneTest.java @@ -20,22 +20,24 @@ class StandaloneTest { @Test void asyncApiStandaloneArtifactTest() throws Exception { // given - StandaloneApplication standaloneApplication = - DefaultStandaloneApplication.builder().buildAndStart(); - - // when - AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); - - // then - assertThat(asyncApi).isNotNull(); - - AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); - String actual = serializerService.toJsonString(asyncApi); - Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actual); - - // then - InputStream s = this.getClass().getResourceAsStream("/asyncapi.json"); - String expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); - org.assertj.core.api.Assertions.assertThat(actual).isEqualTo(expected); + try (StandaloneApplication standaloneApplication = + DefaultStandaloneApplication.builder().buildAndStart()) { + // when + AsyncAPI asyncApi = standaloneApplication.getAsyncApiService().getAsyncAPI(); + + // then + assertThat(asyncApi).isNotNull(); + + AsyncApiSerializerService serializerService = new DefaultAsyncApiSerializerService(); + String actual = serializerService.toJsonString(asyncApi); + Files.writeString(Path.of("src", "test", "resources", "asyncapi.standalone.json"), actual); + + // then + String expected; + try (InputStream s = this.getClass().getResourceAsStream("/asyncapi.json")) { + expected = new String(s.readAllBytes(), StandardCharsets.UTF_8).trim(); + } + assertThat(actual).isEqualTo(expected); + } } } diff --git a/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/util/BaseStompUtil.java b/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/util/BaseStompUtil.java index 4c5c175ff..ebd37d6e4 100644 --- a/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/util/BaseStompUtil.java +++ b/springwolf-examples/springwolf-stomp-example/src/test/java/io/github/springwolf/examples/stomp/util/BaseStompUtil.java @@ -2,6 +2,7 @@ package io.github.springwolf.examples.stomp.util; import lombok.extern.slf4j.Slf4j; +import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; import org.springframework.messaging.converter.JacksonJsonMessageConverter; import org.springframework.messaging.simp.stomp.StompCommand; @@ -22,34 +23,34 @@ @Slf4j public class BaseStompUtil { - private final JacksonJsonMessageConverter converter = new JacksonJsonMessageConverter(); + private static final JacksonJsonMessageConverter CONVERTER = new JacksonJsonMessageConverter(); private final StompSession session; private final BlockingQueue blockingQueue = new ArrayBlockingQueue<>(1); public BaseStompUtil( WebSocketStompClient webSocketStompClient, String wsPath, List subscriptions, Type responseType) throws ExecutionException, InterruptedException, TimeoutException { - webSocketStompClient.setMessageConverter(converter); + webSocketStompClient.setMessageConverter(CONVERTER); StompSessionHandler sessionHandler = new StompSessionHandlerAdapter() { @Override - public void afterConnected(StompSession session, StompHeaders connectedHeaders) { + public void afterConnected(@NonNull StompSession session, @NonNull StompHeaders connectedHeaders) { log.info("Connected to Stomp session"); } @Override public void handleException( - StompSession session, + @NonNull StompSession session, @org.jspecify.annotations.Nullable StompCommand command, - StompHeaders headers, - byte[] payload, - Throwable exception) { + @NonNull StompHeaders headers, + byte @NonNull [] payload, + @NonNull Throwable exception) { log.error("handleException", exception); super.handleException(session, command, headers, payload, exception); } @Override - public void handleTransportError(StompSession session, Throwable exception) { + public void handleTransportError(@NonNull StompSession session, @NonNull Throwable exception) { log.error("handleTransportError", exception); super.handleTransportError(session, exception); } @@ -59,15 +60,17 @@ public void handleTransportError(StompSession session, Throwable exception) { subscriptions.forEach(subscription -> session.subscribe(subscription, new StompFrameHandler() { @Override - public Type getPayloadType(StompHeaders headers) { + public @NonNull Type getPayloadType(@NonNull StompHeaders headers) { return responseType; } @Override @SuppressWarnings("unchecked") - public void handleFrame(StompHeaders headers, @Nullable Object payload) { + public void handleFrame(@NonNull StompHeaders headers, @Nullable Object payload) { log.info("handleFrame {} with headers {}", payload, headers); - blockingQueue.add((R) payload); + if (payload != null) { + blockingQueue.add((R) payload); + } } })); } diff --git a/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/bindings/AmqpBindingFactory.java b/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/bindings/AmqpBindingFactory.java index 80c53ebbd..67c638c95 100644 --- a/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/bindings/AmqpBindingFactory.java +++ b/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/bindings/AmqpBindingFactory.java @@ -5,6 +5,7 @@ import io.github.springwolf.asyncapi.v3.bindings.MessageBinding; import io.github.springwolf.asyncapi.v3.bindings.OperationBinding; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; +import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingFactory; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.Exchange; @@ -29,27 +30,28 @@ public AmqpBindingFactory( } @Override - public String getChannelName(RabbitListener annotation) { - return RabbitListenerUtil.getChannelName(annotation, stringValueResolver); + public String getChannelName(BindingContext bindingContext) { + return RabbitListenerUtil.getChannelName(bindingContext.annotation(), stringValueResolver); } @Override - public String getChannelId(RabbitListener annotation) { - return RabbitListenerUtil.getChannelId(annotation, stringValueResolver); + public String getChannelId(BindingContext bindingContext) { + return RabbitListenerUtil.getChannelId(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildChannelBinding(RabbitListener annotation) { - return RabbitListenerUtil.buildChannelBinding(annotation, stringValueResolver, context); + public Map buildChannelBinding(BindingContext bindingContext) { + return RabbitListenerUtil.buildChannelBinding(bindingContext.annotation(), stringValueResolver, context); } @Override - public Map buildOperationBinding(RabbitListener annotation) { - return RabbitListenerUtil.buildOperationBinding(annotation, stringValueResolver, context); + public Map buildOperationBinding(BindingContext bindingContext) { + return RabbitListenerUtil.buildOperationBinding(bindingContext.annotation(), stringValueResolver, context); } @Override - public Map buildMessageBinding(RabbitListener annotation, SchemaObject headerSchema) { + public Map buildMessageBinding( + BindingContext bindingContext, SchemaObject headerSchema) { return RabbitListenerUtil.buildMessageBinding(); } } diff --git a/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/channels/RabbitQueueBeanScanner.java b/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/channels/RabbitQueueBeanScanner.java index 5406174eb..0898c1567 100644 --- a/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/channels/RabbitQueueBeanScanner.java +++ b/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/channels/RabbitQueueBeanScanner.java @@ -9,8 +9,6 @@ import org.springframework.amqp.core.Queue; import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; import java.util.stream.Stream; @RequiredArgsConstructor @@ -19,12 +17,12 @@ public class RabbitQueueBeanScanner implements ChannelsScanner { private final List bindings; @Override - public Map scan() { + public List scan() { return Stream.concat( queues.stream().map(RabbitListenerUtil::buildChannelObject), bindings.stream() .map(RabbitListenerUtil::buildChannelObject) .flatMap(List::stream)) - .collect(Collectors.toMap(ChannelObject::getChannelId, c -> c, (a, b) -> a)); + .toList(); } } diff --git a/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/configuration/SpringwolfAmqpScannerConfiguration.java b/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/configuration/SpringwolfAmqpScannerConfiguration.java index 4f988351d..57ada3559 100644 --- a/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/configuration/SpringwolfAmqpScannerConfiguration.java +++ b/springwolf-plugins/springwolf-amqp-plugin/src/main/java/io/github/springwolf/plugins/amqp/configuration/SpringwolfAmqpScannerConfiguration.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.plugins.amqp.configuration; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.ChannelsScanner; import io.github.springwolf.core.asyncapi.scanners.OperationsScanner; import io.github.springwolf.core.asyncapi.scanners.channels.ChannelPriority; @@ -21,6 +21,7 @@ import io.github.springwolf.core.asyncapi.scanners.operations.OperationsInClassScannerAdapter; import io.github.springwolf.core.asyncapi.scanners.operations.annotations.SpringAnnotationClassLevelOperationsScanner; import io.github.springwolf.core.asyncapi.scanners.operations.annotations.SpringAnnotationMethodLevelOperationsScanner; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.standalone.StandaloneConfiguration; import io.github.springwolf.plugins.amqp.asyncapi.scanners.bindings.AmqpBindingFactory; import io.github.springwolf.plugins.amqp.asyncapi.scanners.channels.RabbitQueueBeanScanner; @@ -86,13 +87,15 @@ public ChannelsScanner simpleRabbitClassLevelListenerAnnotationChannelsScanner( AsyncHeadersForAmqpBuilder asyncHeadersForAmqpBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService) { + MessagesService messagesService, + SchemasService schemasService) { final var springAnnotationMessagesService = new SpringAnnotationMessagesService<>( amqpBindingFactory, asyncHeadersForAmqpBuilder, payloadMethodParameterService, headerClassExtractor, - componentsService); + messagesService, + schemasService); final var springAnnotationChannelService = new SpringAnnotationChannelService<>(amqpBindingFactory); SpringAnnotationClassLevelChannelsScanner strategy = new SpringAnnotationClassLevelChannelsScanner<>( @@ -117,7 +120,8 @@ public OperationsScanner simpleRabbitClassLevelListenerAnnotationOperationsScann AsyncHeadersForAmqpBuilder asyncHeadersForAmqpBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService, + MessagesService messagesService, + SchemasService schemasService, List operationCustomizers) { final var springAnnotationOperationsService = new SpringAnnotationOperationsService<>( amqpBindingFactory, @@ -126,7 +130,8 @@ public OperationsScanner simpleRabbitClassLevelListenerAnnotationOperationsScann asyncHeadersForAmqpBuilder, payloadMethodParameterService, headerClassExtractor, - componentsService)); + messagesService, + schemasService)); SpringAnnotationClassLevelOperationsScanner strategy = new SpringAnnotationClassLevelOperationsScanner<>( RabbitListener.class, @@ -150,10 +155,11 @@ public ChannelsScanner simpleRabbitMethodLevelListenerAnnotationChannelsScanner( AsyncHeadersForAmqpBuilder asyncHeadersForAmqpBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService) { + MessagesService messagesService, + SchemasService schemasService) { final var springAnnotationChannelService = new SpringAnnotationChannelService<>(amqpBindingFactory); - final var springAnnotationMessageService = - new SpringAnnotationMessageService<>(amqpBindingFactory, asyncHeadersForAmqpBuilder, componentsService); + final var springAnnotationMessageService = new SpringAnnotationMessageService<>( + amqpBindingFactory, asyncHeadersForAmqpBuilder, messagesService, schemasService); SpringAnnotationMethodLevelChannelsScanner strategy = new SpringAnnotationMethodLevelChannelsScanner<>( RabbitListener.class, @@ -178,12 +184,13 @@ public OperationsScanner simpleRabbitMethodLevelListenerAnnotationOperationsScan AsyncHeadersForAmqpBuilder asyncHeadersForAmqpBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService, + MessagesService messagesService, + SchemasService schemasService, List operationCustomizers) { final var springAnnotationOperationService = new SpringAnnotationOperationService<>( amqpBindingFactory, new SpringAnnotationMessageService<>( - amqpBindingFactory, asyncHeadersForAmqpBuilder, componentsService)); + amqpBindingFactory, asyncHeadersForAmqpBuilder, messagesService, schemasService)); SpringAnnotationMethodLevelOperationsScanner strategy = new SpringAnnotationMethodLevelOperationsScanner<>( RabbitListener.class, diff --git a/springwolf-plugins/springwolf-amqp-plugin/src/test/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/channels/RabbitQueueBeanScannerTest.java b/springwolf-plugins/springwolf-amqp-plugin/src/test/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/channels/RabbitQueueBeanScannerTest.java index e7e94e0c2..2553ff63f 100644 --- a/springwolf-plugins/springwolf-amqp-plugin/src/test/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/channels/RabbitQueueBeanScannerTest.java +++ b/springwolf-plugins/springwolf-amqp-plugin/src/test/java/io/github/springwolf/plugins/amqp/asyncapi/scanners/channels/RabbitQueueBeanScannerTest.java @@ -13,7 +13,7 @@ import java.util.List; import java.util.Map; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; class RabbitQueueBeanScannerTest { @@ -29,8 +29,7 @@ void scan() { // then assertThat(result) - .isEqualTo(Map.of( - "name", + .containsExactly( ChannelObject.builder() .channelId("name") .address("name") @@ -46,7 +45,6 @@ void scan() { .build()) .build())) .build(), - "exchange_routingKey", ChannelObject.builder() .channelId("exchange_routingKey") .address("routingKey") @@ -59,7 +57,6 @@ void scan() { .build()) .build())) .build(), - "destination", ChannelObject.builder() .channelId("destination") .address("destination") @@ -71,6 +68,6 @@ void scan() { .name("destination") .build()) .build())) - .build())); + .build()); } } diff --git a/springwolf-plugins/springwolf-amqp-plugin/src/test/java/io/github/springwolf/plugins/amqp/configuration/SpringwolfAmqpProducerConfigurationIntegrationTest.java b/springwolf-plugins/springwolf-amqp-plugin/src/test/java/io/github/springwolf/plugins/amqp/configuration/SpringwolfAmqpProducerConfigurationIntegrationTest.java index 02633d4ca..01b34157d 100644 --- a/springwolf-plugins/springwolf-amqp-plugin/src/test/java/io/github/springwolf/plugins/amqp/configuration/SpringwolfAmqpProducerConfigurationIntegrationTest.java +++ b/springwolf-plugins/springwolf-amqp-plugin/src/test/java/io/github/springwolf/plugins/amqp/configuration/SpringwolfAmqpProducerConfigurationIntegrationTest.java @@ -3,9 +3,11 @@ import io.github.springwolf.core.asyncapi.AsyncApiService; import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.classes.SpringwolfClassScanner; import io.github.springwolf.core.asyncapi.scanners.common.headers.HeaderClassExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadMethodParameterService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.controller.PublishingPayloadCreator; import io.github.springwolf.plugins.amqp.controller.SpringwolfAmqpController; import io.github.springwolf.plugins.amqp.producer.SpringwolfAmqpProducer; @@ -42,6 +44,8 @@ public class SpringwolfAmqpProducerConfigurationIntegrationTest { types = { SpringwolfClassScanner.class, ComponentsService.class, + MessagesService.class, + SchemasService.class, HeaderClassExtractor.class, PayloadMethodParameterService.class, StringValueResolver.class, @@ -81,6 +85,8 @@ void springwolfAmqpProducerShouldBePresentInSpringContext() { types = { SpringwolfClassScanner.class, ComponentsService.class, + MessagesService.class, + SchemasService.class, HeaderClassExtractor.class, PayloadMethodParameterService.class, StringValueResolver.class, diff --git a/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/channels/CloudStreamFunctionChannelsScanner.java b/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/channels/CloudStreamFunctionChannelsScanner.java index 09357e70f..be4b7890c 100644 --- a/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/channels/CloudStreamFunctionChannelsScanner.java +++ b/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/channels/CloudStreamFunctionChannelsScanner.java @@ -14,17 +14,17 @@ import io.github.springwolf.asyncapi.v3.model.schema.MultiFormatSchema; import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; import io.github.springwolf.asyncapi.v3.model.server.Server; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.ChannelsScanner; import io.github.springwolf.core.asyncapi.scanners.beans.BeanMethodsScanner; import io.github.springwolf.core.asyncapi.scanners.bindings.channels.ChannelBindingProcessor; import io.github.springwolf.core.asyncapi.scanners.bindings.messages.MessageBindingProcessor; -import io.github.springwolf.core.asyncapi.scanners.channels.ChannelMerger; import io.github.springwolf.core.asyncapi.scanners.classes.spring.ComponentClassScanner; import io.github.springwolf.core.asyncapi.scanners.common.annotation.AsyncAnnotationUtil; import io.github.springwolf.core.asyncapi.scanners.common.headers.AsyncHeadersNotDocumented; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.configuration.docket.AsyncApiDocket; import io.github.springwolf.core.configuration.docket.AsyncApiDocketService; import io.github.springwolf.plugins.cloudstream.asyncapi.scanners.common.FunctionalChannelBeanBuilder; @@ -47,7 +47,8 @@ public class CloudStreamFunctionChannelsScanner implements ChannelsScanner { private final AsyncApiDocketService asyncApiDocketService; private final BeanMethodsScanner beanMethodsScanner; private final ComponentClassScanner componentClassScanner; - private final ComponentsService componentsService; + private final MessagesService messagesService; + private final SchemasService schemasService; private final PayloadService payloadService; private final BindingServiceProperties cloudStreamBindingsProperties; private final FunctionalChannelBeanBuilder functionalChannelBeanBuilder; @@ -55,7 +56,7 @@ public class CloudStreamFunctionChannelsScanner implements ChannelsScanner { protected final List messageBindingProcessors; @Override - public Map scan() { + public List scan() { Set elements = new HashSet<>(); elements.addAll(componentClassScanner.scan()); elements.addAll(beanMethodsScanner.getBeanMethods()); @@ -67,7 +68,7 @@ public Map scan() { .map(this::toChannelEntry) .toList(); - return ChannelMerger.mergeChannels(channels); + return channels; } private boolean isChannelBean(FunctionalChannelBeanData beanData) { @@ -88,7 +89,7 @@ private ChannelObject buildChannel(FunctionalChannelBeanData beanData, String ch var messagePayload = MessagePayload.of( MultiFormatSchema.builder().schema(payloadSchema.payload()).build()); - String headerModelName = componentsService.registerSchema(AsyncHeadersNotDocumented.NOT_DOCUMENTED); + String headerModelName = schemasService.registerSchema(AsyncHeadersNotDocumented.NOT_DOCUMENTED); MessageHeaders messageHeaders = MessageHeaders.of(SchemaReference.toSchema(headerModelName)); Map messageBinding = buildMessageBinding(beanData.annotatedElement()); @@ -99,7 +100,7 @@ private ChannelObject buildChannel(FunctionalChannelBeanData beanData, String ch .headers(messageHeaders) .bindings(messageBinding) .build(); - this.componentsService.registerMessage(message); + this.messagesService.registerMessage(message); Map channelBinding = buildChannelBinding(beanData.annotatedElement()); diff --git a/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/operations/CloudStreamFunctionOperationsScanner.java b/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/operations/CloudStreamFunctionOperationsScanner.java index f15ccca4d..b3b8b78be 100644 --- a/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/operations/CloudStreamFunctionOperationsScanner.java +++ b/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/operations/CloudStreamFunctionOperationsScanner.java @@ -15,15 +15,17 @@ import io.github.springwolf.asyncapi.v3.model.schema.MultiFormatSchema; import io.github.springwolf.asyncapi.v3.model.schema.SchemaReference; import io.github.springwolf.asyncapi.v3.model.server.Server; -import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.scanners.OperationsScanner; import io.github.springwolf.core.asyncapi.scanners.beans.BeanMethodsScanner; +import io.github.springwolf.core.asyncapi.scanners.bindings.messages.MessageBindingProcessor; +import io.github.springwolf.core.asyncapi.scanners.bindings.operations.OperationBindingProcessor; import io.github.springwolf.core.asyncapi.scanners.classes.spring.ComponentClassScanner; +import io.github.springwolf.core.asyncapi.scanners.common.annotation.AsyncAnnotationUtil; import io.github.springwolf.core.asyncapi.scanners.common.headers.AsyncHeadersNotDocumented; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; import io.github.springwolf.core.asyncapi.scanners.operations.OperationIdHelper; -import io.github.springwolf.core.asyncapi.scanners.operations.OperationMerger; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.configuration.docket.AsyncApiDocket; import io.github.springwolf.core.configuration.docket.AsyncApiDocketService; import io.github.springwolf.plugins.cloudstream.asyncapi.scanners.common.FunctionalChannelBeanBuilder; @@ -33,6 +35,7 @@ import org.springframework.cloud.stream.config.BindingServiceProperties; import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.HashSet; import java.util.List; @@ -46,13 +49,15 @@ public class CloudStreamFunctionOperationsScanner implements OperationsScanner { private final AsyncApiDocketService asyncApiDocketService; private final BeanMethodsScanner beanMethodsScanner; private final ComponentClassScanner componentClassScanner; - private final ComponentsService componentsService; + private final SchemasService schemasService; private final PayloadService payloadService; private final BindingServiceProperties cloudStreamBindingsProperties; private final FunctionalChannelBeanBuilder functionalChannelBeanBuilder; + private final List messageBindingProcessors; + private final List operationBindingProcessors; @Override - public Map scan() { + public List scan() { Set elements = new HashSet<>(); elements.addAll(componentClassScanner.scan()); elements.addAll(beanMethodsScanner.getBeanMethods()); @@ -64,7 +69,7 @@ public Map scan() { .map(this::buildOperation) .toList(); - return OperationMerger.mergeOperations(operations); + return operations; } private boolean isChannelBean(FunctionalChannelBeanData beanData) { @@ -85,7 +90,7 @@ private Operation buildOperation(FunctionalChannelBeanData beanData) { MessagePayload payload = MessagePayload.of( MultiFormatSchema.builder().schema(payloadSchema.payload()).build()); - String headerModelName = componentsService.registerSchema(AsyncHeadersNotDocumented.NOT_DOCUMENTED); + String headerModelName = schemasService.registerSchema(AsyncHeadersNotDocumented.NOT_DOCUMENTED); MessageHeaders messageHeaders = MessageHeaders.of(SchemaReference.toSchema(headerModelName)); MessageObject message = MessageObject.builder() @@ -93,7 +98,7 @@ private Operation buildOperation(FunctionalChannelBeanData beanData) { .title(payloadSchema.title()) .payload(payload) .headers(messageHeaders) - .bindings(buildMessageBinding()) + .bindings(buildMessageBinding(beanData.annotatedElement())) .build(); return Operation.builder() @@ -102,18 +107,29 @@ private Operation buildOperation(FunctionalChannelBeanData beanData) { .description("Auto-generated description") .channel(ChannelReference.fromChannel(channelId)) .messages(List.of(MessageReference.toChannelMessage(channelId, message))) - .bindings(buildOperationBinding()) + .bindings(buildOperationBinding(beanData.annotatedElement())) .build(); } - private Map buildMessageBinding() { - // FIXME: handle messageBindings from annotations as for the channel + private Map buildMessageBinding(AnnotatedElement annotatedElement) { + Map messageBindings = + AsyncAnnotationUtil.processMessageBindingFromAnnotation(annotatedElement, messageBindingProcessors); + if (!messageBindings.isEmpty()) { + return messageBindings; + } + String protocolName = getProtocolName(); return Map.of(protocolName, new EmptyMessageBinding()); } - private Map buildOperationBinding() { - // FIXME: handle operationBindings from annotations as for the channel + private Map buildOperationBinding(AnnotatedElement annotatedElement) { + Map operationBindings = annotatedElement instanceof Method method + ? AsyncAnnotationUtil.processOperationBindingFromAnnotation(method, operationBindingProcessors) + : Map.of(); + if (!operationBindings.isEmpty()) { + return operationBindings; + } + String protocolName = getProtocolName(); return Map.of(protocolName, new EmptyOperationBinding()); } diff --git a/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/configuration/SpringwolfCloudStreamConfiguration.java b/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/configuration/SpringwolfCloudStreamConfiguration.java index 5a557381d..19c303235 100644 --- a/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/configuration/SpringwolfCloudStreamConfiguration.java +++ b/springwolf-plugins/springwolf-cloud-stream-plugin/src/main/java/io/github/springwolf/plugins/cloudstream/configuration/SpringwolfCloudStreamConfiguration.java @@ -1,13 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.plugins.cloudstream.configuration; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.beans.BeanMethodsScanner; import io.github.springwolf.core.asyncapi.scanners.bindings.channels.ChannelBindingProcessor; import io.github.springwolf.core.asyncapi.scanners.bindings.messages.MessageBindingProcessor; +import io.github.springwolf.core.asyncapi.scanners.bindings.operations.OperationBindingProcessor; import io.github.springwolf.core.asyncapi.scanners.classes.spring.ComponentClassScanner; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.TypeExtractor; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.configuration.docket.AsyncApiDocketService; import io.github.springwolf.core.standalone.StandaloneConfiguration; import io.github.springwolf.plugins.cloudstream.asyncapi.scanners.channels.CloudStreamFunctionChannelsScanner; @@ -30,7 +32,8 @@ public CloudStreamFunctionChannelsScanner cloudStreamFunctionChannelsScanner( AsyncApiDocketService asyncApiDocketService, BeanMethodsScanner beanMethodsScanner, ComponentClassScanner componentClassScanner, - ComponentsService componentsService, + MessagesService messagesService, + SchemasService schemasService, PayloadService payloadService, BindingServiceProperties bindingServiceProperties, FunctionalChannelBeanBuilder functionalChannelBeanBuilder, @@ -40,7 +43,8 @@ public CloudStreamFunctionChannelsScanner cloudStreamFunctionChannelsScanner( asyncApiDocketService, beanMethodsScanner, componentClassScanner, - componentsService, + messagesService, + schemasService, payloadService, bindingServiceProperties, functionalChannelBeanBuilder, @@ -54,18 +58,22 @@ public CloudStreamFunctionOperationsScanner cloudStreamFunctionOperationsScanner AsyncApiDocketService asyncApiDocketService, BeanMethodsScanner beanMethodsScanner, ComponentClassScanner componentClassScanner, - ComponentsService componentsService, + SchemasService schemasService, PayloadService payloadService, BindingServiceProperties cloudstreamBindingServiceProperties, - FunctionalChannelBeanBuilder functionalChannelBeanBuilder) { + FunctionalChannelBeanBuilder functionalChannelBeanBuilder, + List messageBindingProcessors, + List operationBindingProcessors) { return new CloudStreamFunctionOperationsScanner( asyncApiDocketService, beanMethodsScanner, componentClassScanner, - componentsService, + schemasService, payloadService, cloudstreamBindingServiceProperties, - functionalChannelBeanBuilder); + functionalChannelBeanBuilder, + messageBindingProcessors, + operationBindingProcessors); } @Bean diff --git a/springwolf-plugins/springwolf-cloud-stream-plugin/src/test/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/channels/CloudStreamFunctionChannelsScannerIntegrationTest.java b/springwolf-plugins/springwolf-cloud-stream-plugin/src/test/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/channels/CloudStreamFunctionChannelsScannerIntegrationTest.java index 201fe1c73..95f22ae25 100644 --- a/springwolf-plugins/springwolf-cloud-stream-plugin/src/test/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/channels/CloudStreamFunctionChannelsScannerIntegrationTest.java +++ b/springwolf-plugins/springwolf-cloud-stream-plugin/src/test/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/channels/CloudStreamFunctionChannelsScannerIntegrationTest.java @@ -21,24 +21,31 @@ import io.github.springwolf.asyncapi.v3.model.schema.SchemaType; import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.components.DefaultComponentsService; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.DefaultSchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.messages.DefaultMessagesService; import io.github.springwolf.core.asyncapi.scanners.beans.DefaultBeanMethodsScanner; +import io.github.springwolf.core.asyncapi.scanners.bindings.messages.MessageBindingProcessor; +import io.github.springwolf.core.asyncapi.scanners.bindings.messages.ProcessedMessageBinding; +import io.github.springwolf.core.asyncapi.scanners.bindings.operations.OperationBindingProcessor; +import io.github.springwolf.core.asyncapi.scanners.bindings.operations.ProcessedOperationBinding; import io.github.springwolf.core.asyncapi.scanners.classes.spring.ComponentClassScanner; import io.github.springwolf.core.asyncapi.scanners.classes.spring.ConfigurationClassScanner; import io.github.springwolf.core.asyncapi.scanners.common.headers.AsyncHeadersNotDocumented; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.TypeExtractor; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.DefaultSchemasService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.DefaultSchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; import io.github.springwolf.core.configuration.docket.DefaultAsyncApiDocketService; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.github.springwolf.plugins.cloudstream.asyncapi.scanners.common.FunctionalChannelBeanBuilder; import io.github.springwolf.plugins.cloudstream.asyncapi.scanners.operations.CloudStreamFunctionOperationsScanner; import org.apache.kafka.streams.kstream.KStream; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -51,9 +58,11 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; +import java.lang.reflect.Method; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BiFunction; @@ -70,6 +79,8 @@ ComponentClassScanner.class, DefaultBeanMethodsScanner.class, DefaultComponentsService.class, + DefaultSchemasService.class, + DefaultMessagesService.class, SwaggerSchemaService.class, PayloadService.class, PayloadExtractor.class, @@ -83,7 +94,7 @@ CloudStreamFunctionOperationsScanner.class, FunctionalChannelBeanBuilder.class, SpringwolfConfigProperties.class, - ModelConvertersProvider.class + ModelConvertersRegisterer.class }) @TestPropertySource( properties = { @@ -114,10 +125,15 @@ class CloudStreamFunctionChannelsScannerIntegrationTest { private Map operationBinding = Map.of("kafka", new EmptyOperationBinding()); private Map channelBinding = Map.of("kafka", new EmptyChannelBinding()); + @BeforeEach + void clearRegisteredMessages() { + componentsService.getMessages().clear(); + } + @Test void noBindings() { when(bindingServiceProperties.getBindings()).thenReturn(Collections.emptyMap()); - Map channels = channelsScanner.scan(); + List channels = channelsScanner.scan(); assertThat(channels).isEmpty(); } @@ -130,8 +146,8 @@ void consumerBinding() { when(bindingServiceProperties.getBindings()).thenReturn(Map.of("testConsumer-in-0", testConsumerInBinding)); // When scan is called - Map actualChannels = channelsScanner.scan(); - Map actualOperations = operationsScanner.scan(); + List actualChannels = channelsScanner.scan(); + List actualOperations = operationsScanner.scan(); // Then the returned channels contain a ChannelItem with the correct data MessageObject message = MessageObject.builder() @@ -144,7 +160,7 @@ void consumerBinding() { .build())) .headers(MessageHeaders.of( SchemaReference.toSchema(AsyncHeadersNotDocumented.NOT_DOCUMENTED.getTitle()))) - .bindings(messageBinding) + .bindings(Map.of("test", new EmptyMessageBinding())) .build(); ChannelObject expectedChannel = ChannelObject.builder() @@ -157,15 +173,14 @@ void consumerBinding() { Operation expectedOperation = Operation.builder() .operationId("test-consumer-input-topic_receive_testConsumer") .action(OperationAction.RECEIVE) - .bindings(operationBinding) + .bindings(Map.of("test", new EmptyOperationBinding())) .description("Auto-generated description") .channel(ChannelReference.fromChannel(topicName)) .messages(List.of(MessageReference.toChannelMessage(topicName, message))) .build(); - assertThat(actualChannels).containsExactly(Map.entry(topicName, expectedChannel)); - assertThat(actualOperations) - .containsExactly(Map.entry("test-consumer-input-topic_receive_testConsumer", expectedOperation)); + assertThat(actualChannels).containsExactly(expectedChannel); + assertThat(actualOperations).containsExactly(expectedOperation); assertThat(componentsService.getMessages()).contains(Map.entry(String.class.getName(), message)); } @@ -178,8 +193,8 @@ void biConsumerBinding() { when(bindingServiceProperties.getBindings()).thenReturn(Map.of("testBiConsumer-in-0", testBiConsumerInBinding)); // When scan is called - Map actualChannels = channelsScanner.scan(); - Map actualOperations = operationsScanner.scan(); + List actualChannels = channelsScanner.scan(); + List actualOperations = operationsScanner.scan(); // Then the returned channels contain a ChannelItem with the correct data MessageObject message = MessageObject.builder() @@ -211,9 +226,8 @@ void biConsumerBinding() { .messages(List.of(MessageReference.toChannelMessage(topicName, message))) .build(); - assertThat(actualChannels).containsExactly(Map.entry(topicName, expectedChannel)); - assertThat(actualOperations) - .containsExactly(Map.entry("test-biconsumer-input-topic_receive_testBiConsumer", expectedOperation)); + assertThat(actualChannels).containsExactly(expectedChannel); + assertThat(actualOperations).containsExactly(expectedOperation); assertThat(componentsService.getMessages()).contains(Map.entry(String.class.getName(), message)); } @@ -226,8 +240,8 @@ void supplierBinding() { when(bindingServiceProperties.getBindings()).thenReturn(Map.of("testSupplier-out-0", testSupplierOutBinding)); // When scan is called - Map actualChannels = channelsScanner.scan(); - Map actualOperations = operationsScanner.scan(); + List actualChannels = channelsScanner.scan(); + List actualOperations = operationsScanner.scan(); // Then the returned channels contain a ChannelItem with the correct data @@ -260,9 +274,8 @@ void supplierBinding() { .messages(Map.of(message.getMessageId(), MessageReference.toComponentMessage(message))) .build(); - assertThat(actualChannels).containsExactly(Map.entry(topicName, expectedChannel)); - assertThat(actualOperations) - .containsExactly(Map.entry("test-supplier-output-topic_send_testSupplier", expectedOperation)); + assertThat(actualChannels).containsExactly(expectedChannel); + assertThat(actualOperations).containsExactly(expectedOperation); assertThat(componentsService.getMessages()).contains(Map.entry(String.class.getName(), message)); } @@ -283,8 +296,8 @@ void functionBinding() { "testFunction-out-0", testFunctionOutBinding)); // When scan is called - Map actualChannels = channelsScanner.scan(); - Map actualOperations = operationsScanner.scan(); + List actualChannels = channelsScanner.scan(); + List actualOperations = operationsScanner.scan(); // Then the returned channels contain a publish ChannelItem and a subscribe ChannelItem MessageObject subscribeMessage = MessageObject.builder() @@ -342,12 +355,8 @@ void functionBinding() { .messages(Map.of(publishMessage.getMessageId(), MessageReference.toComponentMessage(publishMessage))) .build(); - assertThat(actualChannels) - .contains(Map.entry(inputTopicName, subscribeChannel), Map.entry(outputTopicName, publishChannel)); - assertThat(actualOperations) - .contains( - Map.entry("test-in-topic_receive_testFunction", subscribeOperation), - Map.entry("test-out-topic_send_testFunction", publishOperation)); + assertThat(actualChannels).containsExactlyInAnyOrder(subscribeChannel, publishChannel); + assertThat(actualOperations).containsExactlyInAnyOrder(subscribeOperation, publishOperation); } @Test @@ -367,8 +376,8 @@ void biFunctionBinding() { "testBiFunction-out-0", testBiFunctionOutBinding)); // When scan is called - Map actualChannels = channelsScanner.scan(); - Map actualOperations = operationsScanner.scan(); + List actualChannels = channelsScanner.scan(); + List actualOperations = operationsScanner.scan(); // Then the returned channels contain a publish ChannelItem and a subscribe ChannelItem MessageObject subscribeMessage = MessageObject.builder() @@ -426,12 +435,8 @@ void biFunctionBinding() { .messages(Map.of(publishMessage.getMessageId(), MessageReference.toComponentMessage(publishMessage))) .build(); - assertThat(actualChannels) - .contains(Map.entry(outputTopicName, publishChannel), Map.entry(inputTopicName, subscribeChannel)); - assertThat(actualOperations) - .contains( - Map.entry("test-in-topic_receive_testBiFunction", subscribeOperation), - Map.entry("test-out-topic_send_testBiFunction", publishOperation)); + assertThat(actualChannels).containsExactlyInAnyOrder(subscribeChannel, publishChannel); + assertThat(actualOperations).containsExactlyInAnyOrder(subscribeOperation, publishOperation); } @Test @@ -451,8 +456,8 @@ void kStreamFunctionBinding() { "kStreamTestFunction-out-0", testFunctionOutBinding)); // When scan is called - Map actualChannels = channelsScanner.scan(); - Map actualOperations = operationsScanner.scan(); + List actualChannels = channelsScanner.scan(); + List actualOperations = operationsScanner.scan(); // Then the returned channels contain a publish ChannelItem and a subscribe ChannelItem MessageObject subscribeMessage = MessageObject.builder() @@ -515,12 +520,8 @@ void kStreamFunctionBinding() { .messages(Map.of(publishMessage.getMessageId(), MessageReference.toComponentMessage(publishMessage))) .build(); - assertThat(actualChannels) - .contains(Map.entry(outputTopicName, publishChannel), Map.entry(inputTopicName, subscribeChannel)); - assertThat(actualOperations) - .contains( - Map.entry("test-in-topic_receive_kStreamTestFunction", subscribeOperation), - Map.entry("test-out-topic_send_kStreamTestFunction", publishOperation)); + assertThat(actualChannels).containsExactlyInAnyOrder(subscribeChannel, publishChannel); + assertThat(actualOperations).containsExactlyInAnyOrder(subscribeOperation, publishOperation); assertThat(componentsService.getMessages()).contains(Map.entry(String.class.getName(), subscribeMessage)); assertThat(componentsService.getMessages()).contains(Map.entry(Integer.class.getName(), publishMessage)); } @@ -541,10 +542,10 @@ void functionBindingWithSameTopicName() { "testFunction-out-0", testFunctionOutBinding)); // When scan is called - Map actualChannels = channelsScanner.scan(); - Map actualOperations = operationsScanner.scan(); + List actualChannels = channelsScanner.scan(); + List actualOperations = operationsScanner.scan(); - // Then the returned merged channels contain a publish operation and a subscribe operation + // Then the returned channels contain a publish and a subscribe channel MessageObject subscribeMessage = MessageObject.builder() .name(String.class.getName()) .title("string") @@ -589,28 +590,44 @@ void functionBindingWithSameTopicName() { .messages(List.of(MessageReference.toChannelMessage(topicName, publishMessage))) .build(); - ChannelObject mergedChannel = ChannelObject.builder() + ChannelObject subscribeChannel = ChannelObject.builder() + .channelId(topicName) + .address(topicName) + .bindings(channelBinding) + .messages( + Map.of(subscribeMessage.getMessageId(), MessageReference.toComponentMessage(subscribeMessage))) + .build(); + + ChannelObject publishChannel = ChannelObject.builder() .channelId(topicName) .address(topicName) .bindings(channelBinding) - .messages(Map.of( - publishMessage.getMessageId(), - MessageReference.toComponentMessage(publishMessage), - subscribeMessage.getMessageId(), - MessageReference.toComponentMessage(subscribeMessage))) - .build(); - - assertThat(actualChannels).contains(Map.entry(topicName, mergedChannel)); - assertThat(actualOperations) - .contains( - Map.entry("test-topic_send_testFunction", publishOperation), - Map.entry("test-topic_receive_testFunction", subscribeOperation)); + .messages(Map.of(publishMessage.getMessageId(), MessageReference.toComponentMessage(publishMessage))) + .build(); + + assertThat(actualChannels).containsExactlyInAnyOrder(subscribeChannel, publishChannel); + assertThat(actualOperations).containsExactlyInAnyOrder(subscribeOperation, publishOperation); assertThat(componentsService.getMessages()).contains(Map.entry(String.class.getName(), subscribeMessage)); assertThat(componentsService.getMessages()).contains(Map.entry(Integer.class.getName(), publishMessage)); } @TestConfiguration public static class Configuration { + @Bean + public MessageBindingProcessor testMessageBindingProcessor() { + return annotatedElement -> annotatedElement instanceof Method method + && method.getName().equals("testConsumer") + ? Optional.of(new ProcessedMessageBinding("test", new EmptyMessageBinding())) + : Optional.empty(); + } + + @Bean + public OperationBindingProcessor testOperationBindingProcessor() { + return method -> method.getName().equals("testConsumer") + ? Optional.of(new ProcessedOperationBinding("test", new EmptyOperationBinding())) + : Optional.empty(); + } + @Bean public Consumer testConsumer() { return System.out::println; diff --git a/springwolf-plugins/springwolf-cloud-stream-plugin/src/test/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/common/FunctionalChannelBeanBuilderTest.java b/springwolf-plugins/springwolf-cloud-stream-plugin/src/test/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/common/FunctionalChannelBeanBuilderTest.java index 9b4dd61f3..73e93f20a 100644 --- a/springwolf-plugins/springwolf-cloud-stream-plugin/src/test/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/common/FunctionalChannelBeanBuilderTest.java +++ b/springwolf-plugins/springwolf-cloud-stream-plugin/src/test/java/io/github/springwolf/plugins/cloudstream/asyncapi/scanners/common/FunctionalChannelBeanBuilderTest.java @@ -419,12 +419,16 @@ void testConsumerChildChildClassBean() throws Exception { interface BiConsumerChild extends BiConsumer {} + @SuppressWarnings("rawtypes") interface BiConsumerRawChild extends BiConsumer {} + @SuppressWarnings("rawtypes") interface SupplierRawChild extends Supplier {} + @SuppressWarnings("rawtypes") interface FunctionRawChild extends Function {} + @SuppressWarnings("rawtypes") interface BiFunctionRawChild extends BiFunction {} interface BiConsumerChildChild extends BiConsumerChild {} diff --git a/springwolf-plugins/springwolf-jms-plugin/src/main/java/io/github/springwolf/plugins/jms/asyncapi/scanners/bindings/JmsBindingFactory.java b/springwolf-plugins/springwolf-jms-plugin/src/main/java/io/github/springwolf/plugins/jms/asyncapi/scanners/bindings/JmsBindingFactory.java index 8713ebeba..3c73fe9a0 100644 --- a/springwolf-plugins/springwolf-jms-plugin/src/main/java/io/github/springwolf/plugins/jms/asyncapi/scanners/bindings/JmsBindingFactory.java +++ b/springwolf-plugins/springwolf-jms-plugin/src/main/java/io/github/springwolf/plugins/jms/asyncapi/scanners/bindings/JmsBindingFactory.java @@ -5,6 +5,7 @@ import io.github.springwolf.asyncapi.v3.bindings.MessageBinding; import io.github.springwolf.asyncapi.v3.bindings.OperationBinding; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; +import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingFactory; import lombok.RequiredArgsConstructor; import org.springframework.jms.annotation.JmsListener; @@ -17,22 +18,23 @@ public class JmsBindingFactory implements BindingFactory { private final StringValueResolver stringValueResolver; @Override - public String getChannelName(JmsListener annotation) { - return JmsListenerUtil.getChannelName(annotation, stringValueResolver); + public String getChannelName(BindingContext bindingContext) { + return JmsListenerUtil.getChannelName(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildChannelBinding(JmsListener annotation) { - return JmsListenerUtil.buildChannelBinding(annotation, stringValueResolver); + public Map buildChannelBinding(BindingContext bindingContext) { + return JmsListenerUtil.buildChannelBinding(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildOperationBinding(JmsListener annotation) { - return JmsListenerUtil.buildOperationBinding(annotation, stringValueResolver); + public Map buildOperationBinding(BindingContext bindingContext) { + return JmsListenerUtil.buildOperationBinding(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildMessageBinding(JmsListener annotation, SchemaObject headerSchema) { + public Map buildMessageBinding( + BindingContext bindingContext, SchemaObject headerSchema) { return JmsListenerUtil.buildMessageBinding(); } } diff --git a/springwolf-plugins/springwolf-jms-plugin/src/main/java/io/github/springwolf/plugins/jms/configuration/SpringwolfJmsScannerConfiguration.java b/springwolf-plugins/springwolf-jms-plugin/src/main/java/io/github/springwolf/plugins/jms/configuration/SpringwolfJmsScannerConfiguration.java index 2894c1026..13294fef6 100644 --- a/springwolf-plugins/springwolf-jms-plugin/src/main/java/io/github/springwolf/plugins/jms/configuration/SpringwolfJmsScannerConfiguration.java +++ b/springwolf-plugins/springwolf-jms-plugin/src/main/java/io/github/springwolf/plugins/jms/configuration/SpringwolfJmsScannerConfiguration.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.plugins.jms.configuration; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.ChannelsScanner; import io.github.springwolf.core.asyncapi.scanners.OperationsScanner; import io.github.springwolf.core.asyncapi.scanners.channels.ChannelPriority; @@ -17,6 +17,7 @@ import io.github.springwolf.core.asyncapi.scanners.operations.OperationCustomizer; import io.github.springwolf.core.asyncapi.scanners.operations.OperationsInClassScannerAdapter; import io.github.springwolf.core.asyncapi.scanners.operations.annotations.SpringAnnotationMethodLevelOperationsScanner; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.standalone.StandaloneConfiguration; import io.github.springwolf.plugins.jms.asyncapi.scanners.bindings.JmsBindingFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -54,10 +55,11 @@ public ChannelsScanner simpleJmsMethodLevelListenerAnnotationChannelsScanner( JmsBindingFactory jmsBindingFactory, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService) { + MessagesService messagesService, + SchemasService schemasService) { final var springAnnotationChannelService = new SpringAnnotationChannelService<>(jmsBindingFactory); final var springAnnotationMessageService = new SpringAnnotationMessageService<>( - jmsBindingFactory, new AsyncHeadersNotDocumented(), componentsService); + jmsBindingFactory, new AsyncHeadersNotDocumented(), messagesService, schemasService); SpringAnnotationMethodLevelChannelsScanner strategy = new SpringAnnotationMethodLevelChannelsScanner<>( JmsListener.class, @@ -78,12 +80,13 @@ public OperationsScanner simpleJmsMethodLevelListenerAnnotationOperationsScanner JmsBindingFactory jmsBindingFactory, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService, + MessagesService messagesService, + SchemasService schemasService, List operationCustomizers) { final var springAnnotationOperationService = new SpringAnnotationOperationService<>( jmsBindingFactory, new SpringAnnotationMessageService<>( - jmsBindingFactory, new AsyncHeadersNotDocumented(), componentsService)); + jmsBindingFactory, new AsyncHeadersNotDocumented(), messagesService, schemasService)); SpringAnnotationMethodLevelOperationsScanner strategy = new SpringAnnotationMethodLevelOperationsScanner<>( JmsListener.class, diff --git a/springwolf-plugins/springwolf-jms-plugin/src/test/java/io/github/springwolf/plugins/jms/configuration/SpringwolfJmsProducerConfigurationIntegrationTest.java b/springwolf-plugins/springwolf-jms-plugin/src/test/java/io/github/springwolf/plugins/jms/configuration/SpringwolfJmsProducerConfigurationIntegrationTest.java index 7479b73bb..8c622c460 100644 --- a/springwolf-plugins/springwolf-jms-plugin/src/test/java/io/github/springwolf/plugins/jms/configuration/SpringwolfJmsProducerConfigurationIntegrationTest.java +++ b/springwolf-plugins/springwolf-jms-plugin/src/test/java/io/github/springwolf/plugins/jms/configuration/SpringwolfJmsProducerConfigurationIntegrationTest.java @@ -2,9 +2,11 @@ package io.github.springwolf.plugins.jms.configuration; import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.classes.SpringwolfClassScanner; import io.github.springwolf.core.asyncapi.scanners.common.headers.HeaderClassExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadMethodParameterService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.controller.PublishingPayloadCreator; import io.github.springwolf.plugins.jms.controller.SpringwolfJmsController; import io.github.springwolf.plugins.jms.producer.SpringwolfJmsProducer; @@ -41,6 +43,8 @@ public class SpringwolfJmsProducerConfigurationIntegrationTest { types = { SpringwolfClassScanner.class, ComponentsService.class, + MessagesService.class, + SchemasService.class, HeaderClassExtractor.class, PayloadMethodParameterService.class, StringValueResolver.class, @@ -79,6 +83,8 @@ void springwolfJmsProducerShouldBePresentInSpringContext() { types = { SpringwolfClassScanner.class, ComponentsService.class, + MessagesService.class, + SchemasService.class, HeaderClassExtractor.class, PayloadMethodParameterService.class, StringValueResolver.class, diff --git a/springwolf-plugins/springwolf-jms-plugin/src/test/java/io/github/springwolf/plugins/jms/controller/SpringwolfJmsControllerIntegrationTest.java b/springwolf-plugins/springwolf-jms-plugin/src/test/java/io/github/springwolf/plugins/jms/controller/SpringwolfJmsControllerIntegrationTest.java index a64db1f4b..27c70f7f9 100644 --- a/springwolf-plugins/springwolf-jms-plugin/src/test/java/io/github/springwolf/plugins/jms/controller/SpringwolfJmsControllerIntegrationTest.java +++ b/springwolf-plugins/springwolf-jms-plugin/src/test/java/io/github/springwolf/plugins/jms/controller/SpringwolfJmsControllerIntegrationTest.java @@ -3,17 +3,19 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; -import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.components.DefaultComponentsService; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.DefaultSchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.messages.DefaultMessagesService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.TypeExtractor; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.DefaultSchemasService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.DefaultSchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.github.springwolf.core.controller.PublishingPayloadCreator; import io.github.springwolf.core.controller.dtos.MessageDto; @@ -60,6 +62,8 @@ PayloadExtractor.class, TypeExtractor.class, DefaultComponentsService.class, + DefaultSchemasService.class, + DefaultMessagesService.class, SwaggerSchemaService.class, PayloadService.class, SwaggerSchemaMapper.class, @@ -67,7 +71,7 @@ SchemaWalkerProvider.class, ExampleJsonValueGenerator.class, SpringwolfConfigProperties.class, - ModelConvertersProvider.class, + ModelConvertersRegisterer.class, JsonMapperTestConfiguration.class, }) @ExtendWith(MockitoExtension.class) @@ -84,7 +88,7 @@ class SpringwolfJmsControllerIntegrationTest { private MockMvc mvc; @Autowired - private ComponentsService componentsService; + private SchemasService schemasService; @MockitoBean private SpringwolfJmsProducer springwolfJmsProducer; @@ -99,7 +103,7 @@ class SpringwolfJmsControllerIntegrationTest { void setup() { when(springwolfJmsProducer.isEnabled()).thenReturn(true); - componentsService.registerSchema(SchemaObject.builder() + schemasService.registerSchema(SchemaObject.builder() .title(PayloadDto.class.getName()) .properties(new HashMap<>()) .build()); diff --git a/springwolf-plugins/springwolf-kafka-plugin/build.gradle b/springwolf-plugins/springwolf-kafka-plugin/build.gradle index e494ce415..1263ff8d9 100644 --- a/springwolf-plugins/springwolf-kafka-plugin/build.gradle +++ b/springwolf-plugins/springwolf-kafka-plugin/build.gradle @@ -17,6 +17,7 @@ dependencies { permitUnusedDeclared libs.swagger.models implementation libs.kafka.clients + implementation libs.jspecify implementation libs.jakarta.annotation.api implementation libs.slf4j.api diff --git a/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/asyncapi/scanners/bindings/KafkaBindingFactory.java b/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/asyncapi/scanners/bindings/KafkaBindingFactory.java index 91ff2a1fb..1997add37 100644 --- a/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/asyncapi/scanners/bindings/KafkaBindingFactory.java +++ b/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/asyncapi/scanners/bindings/KafkaBindingFactory.java @@ -25,11 +25,6 @@ public String getChannelId(BindingContext bindingContext) { return ReferenceUtil.toValidId(getChannelName(bindingContext)); } - @Override - public String getChannelName(KafkaListener annotation) { - return KafkaListenerUtil.getChannelName(annotation, stringValueResolver); - } - @Override public String getChannelName(BindingContext bindingContext) { StringValueResolver stringValueResolver = beanRefResolver.getStringValueResolver(bindingContext); @@ -37,15 +32,10 @@ public String getChannelName(BindingContext bindingContext) { } @Override - public Map buildChannelBinding(KafkaListener annotation) { + public Map buildChannelBinding(BindingContext bindingContext) { return KafkaListenerUtil.buildChannelBinding(); } - @Override - public Map buildOperationBinding(KafkaListener annotation) { - return KafkaListenerUtil.buildOperationBinding(annotation, stringValueResolver); - } - @Override public Map buildOperationBinding(BindingContext bindingContext) { StringValueResolver stringValueResolver = beanRefResolver.getStringValueResolver(bindingContext); @@ -53,7 +43,8 @@ public Map buildOperationBinding(BindingContext buildMessageBinding(KafkaListener annotation, SchemaObject headerSchema) { + public Map buildMessageBinding( + BindingContext bindingContext, SchemaObject headerSchema) { return KafkaListenerUtil.buildMessageBinding(headerSchema); } } diff --git a/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/asyncapi/scanners/bindings/KafkaListenerBeanRefResolver.java b/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/asyncapi/scanners/bindings/KafkaListenerBeanRefResolver.java index 166dd50d7..07a5ad76c 100644 --- a/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/asyncapi/scanners/bindings/KafkaListenerBeanRefResolver.java +++ b/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/asyncapi/scanners/bindings/KafkaListenerBeanRefResolver.java @@ -4,6 +4,7 @@ import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import jakarta.annotation.Nullable; import lombok.RequiredArgsConstructor; +import org.jspecify.annotations.NonNull; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanExpressionException; import org.springframework.beans.factory.BeanFactory; @@ -37,7 +38,7 @@ public class KafkaListenerBeanRefResolver implements BeanFactoryAware { private ConfigurableBeanFactory beanFactory; @Override - public void setBeanFactory(BeanFactory beanFactory) { + public void setBeanFactory(@NonNull BeanFactory beanFactory) { if (beanFactory instanceof ConfigurableBeanFactory configurableBeanFactory) { this.beanFactory = configurableBeanFactory; } @@ -104,7 +105,7 @@ private ListenerBeanUnavailableException(String message, BeansException cause) { private record BeanRefScope(BeanFactory beanFactory, String beanRef, Class listenerClass) implements Scope { @Override @Nullable - public Object resolveContextualObject(String key) { + public Object resolveContextualObject(@NonNull String key) { if (!beanRef.equals(key)) { return null; } @@ -117,18 +118,18 @@ public Object resolveContextualObject(String key) { } @Override - public Object get(String name, ObjectFactory objectFactory) { + public @NonNull Object get(@NonNull String name, ObjectFactory objectFactory) { return objectFactory.getObject(); } @Override @Nullable - public Object remove(String name) { + public Object remove(@NonNull String name) { return null; } @Override - public void registerDestructionCallback(String name, Runnable callback) {} + public void registerDestructionCallback(@NonNull String name, @NonNull Runnable callback) {} @Override @Nullable diff --git a/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/configuration/SpringwolfKafkaScannerConfiguration.java b/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/configuration/SpringwolfKafkaScannerConfiguration.java index 716a0bcd1..2638147cc 100644 --- a/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/configuration/SpringwolfKafkaScannerConfiguration.java +++ b/springwolf-plugins/springwolf-kafka-plugin/src/main/java/io/github/springwolf/plugins/kafka/configuration/SpringwolfKafkaScannerConfiguration.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.plugins.kafka.configuration; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.ChannelsScanner; import io.github.springwolf.core.asyncapi.scanners.OperationsScanner; import io.github.springwolf.core.asyncapi.scanners.channels.ChannelPriority; @@ -21,6 +21,7 @@ import io.github.springwolf.core.asyncapi.scanners.operations.OperationsInClassScannerAdapter; import io.github.springwolf.core.asyncapi.scanners.operations.annotations.SpringAnnotationClassLevelOperationsScanner; import io.github.springwolf.core.asyncapi.scanners.operations.annotations.SpringAnnotationMethodLevelOperationsScanner; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.standalone.StandaloneConfiguration; import io.github.springwolf.plugins.kafka.asyncapi.scanners.bindings.KafkaBindingFactory; import io.github.springwolf.plugins.kafka.asyncapi.scanners.bindings.KafkaListenerBeanRefResolver; @@ -90,13 +91,15 @@ public ChannelsScanner simpleKafkaClassLevelListenerAnnotationChannelsScanner( AsyncHeadersForKafkaBuilder asyncHeadersForKafkaBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService) { + MessagesService messagesService, + SchemasService schemasService) { final var springAnnotationMessagesService = new SpringAnnotationMessagesService<>( kafkaBindingFactory, asyncHeadersForKafkaBuilder, payloadMethodParameterService, headerClassExtractor, - componentsService); + messagesService, + schemasService); final var springAnnotationChannelService = new SpringAnnotationChannelService<>(kafkaBindingFactory); SpringAnnotationClassLevelChannelsScanner strategy = new SpringAnnotationClassLevelChannelsScanner<>( @@ -121,7 +124,8 @@ public OperationsScanner simpleKafkaClassLevelListenerAnnotationOperationScanner AsyncHeadersForKafkaBuilder asyncHeadersForKafkaBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService, + MessagesService messagesService, + SchemasService schemasService, List operationCustomizers) { final var springAnnotationOperationsService = new SpringAnnotationOperationsService<>( kafkaBindingFactory, @@ -130,7 +134,8 @@ public OperationsScanner simpleKafkaClassLevelListenerAnnotationOperationScanner asyncHeadersForKafkaBuilder, payloadMethodParameterService, headerClassExtractor, - componentsService)); + messagesService, + schemasService)); SpringAnnotationClassLevelOperationsScanner strategy = new SpringAnnotationClassLevelOperationsScanner<>( KafkaListener.class, @@ -154,10 +159,11 @@ public ChannelsScanner simpleKafkaMethodLevelListenerAnnotationChannelsScanner( AsyncHeadersForKafkaBuilder asyncHeadersForKafkaBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService) { + MessagesService messagesService, + SchemasService schemasService) { final var springAnnotationChannelService = new SpringAnnotationChannelService<>(kafkaBindingFactory); final var springAnnotationMessageService = new SpringAnnotationMessageService<>( - kafkaBindingFactory, asyncHeadersForKafkaBuilder, componentsService); + kafkaBindingFactory, asyncHeadersForKafkaBuilder, messagesService, schemasService); SpringAnnotationMethodLevelChannelsScanner strategy = new SpringAnnotationMethodLevelChannelsScanner<>( KafkaListener.class, @@ -181,12 +187,13 @@ public OperationsScanner simpleKafkaMethodLevelListenerAnnotationOperationsScann AsyncHeadersForKafkaBuilder asyncHeadersForKafkaBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService, + MessagesService messagesService, + SchemasService schemasService, List operationCustomizers) { final var springAnnotationOperationService = new SpringAnnotationOperationService<>( kafkaBindingFactory, new SpringAnnotationMessageService<>( - kafkaBindingFactory, asyncHeadersForKafkaBuilder, componentsService)); + kafkaBindingFactory, asyncHeadersForKafkaBuilder, messagesService, schemasService)); SpringAnnotationMethodLevelOperationsScanner strategy = new SpringAnnotationMethodLevelOperationsScanner<>( KafkaListener.class, diff --git a/springwolf-plugins/springwolf-kafka-plugin/src/test/java/io/github/springwolf/plugins/kafka/configuration/SpringwolfKafkaProducerConfigurationIntegrationTest.java b/springwolf-plugins/springwolf-kafka-plugin/src/test/java/io/github/springwolf/plugins/kafka/configuration/SpringwolfKafkaProducerConfigurationIntegrationTest.java index 2a73b9950..90aaa0b05 100644 --- a/springwolf-plugins/springwolf-kafka-plugin/src/test/java/io/github/springwolf/plugins/kafka/configuration/SpringwolfKafkaProducerConfigurationIntegrationTest.java +++ b/springwolf-plugins/springwolf-kafka-plugin/src/test/java/io/github/springwolf/plugins/kafka/configuration/SpringwolfKafkaProducerConfigurationIntegrationTest.java @@ -2,9 +2,11 @@ package io.github.springwolf.plugins.kafka.configuration; import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.classes.SpringwolfClassScanner; import io.github.springwolf.core.asyncapi.scanners.common.headers.HeaderClassExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadMethodParameterService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.controller.PublishingPayloadCreator; import io.github.springwolf.plugins.kafka.controller.SpringwolfKafkaController; import io.github.springwolf.plugins.kafka.producer.SpringwolfKafkaProducer; @@ -40,6 +42,8 @@ public class SpringwolfKafkaProducerConfigurationIntegrationTest { types = { SpringwolfClassScanner.class, ComponentsService.class, + MessagesService.class, + SchemasService.class, HeaderClassExtractor.class, PayloadMethodParameterService.class, StringValueResolver.class @@ -77,6 +81,8 @@ void springwolfKafkaTemplateShouldBePresentInSpringContext() { types = { SpringwolfClassScanner.class, ComponentsService.class, + MessagesService.class, + SchemasService.class, HeaderClassExtractor.class, PayloadMethodParameterService.class, StringValueResolver.class diff --git a/springwolf-plugins/springwolf-kafka-plugin/src/test/java/io/github/springwolf/plugins/kafka/controller/SpringwolfKafkaControllerIntegrationTest.java b/springwolf-plugins/springwolf-kafka-plugin/src/test/java/io/github/springwolf/plugins/kafka/controller/SpringwolfKafkaControllerIntegrationTest.java index 1d2d7c26e..3f7e52270 100644 --- a/springwolf-plugins/springwolf-kafka-plugin/src/test/java/io/github/springwolf/plugins/kafka/controller/SpringwolfKafkaControllerIntegrationTest.java +++ b/springwolf-plugins/springwolf-kafka-plugin/src/test/java/io/github/springwolf/plugins/kafka/controller/SpringwolfKafkaControllerIntegrationTest.java @@ -3,17 +3,19 @@ import com.fasterxml.jackson.annotation.JsonProperty; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; -import io.github.springwolf.core.asyncapi.components.ComponentsService; import io.github.springwolf.core.asyncapi.components.DefaultComponentsService; -import io.github.springwolf.core.asyncapi.components.examples.SchemaWalkerProvider; -import io.github.springwolf.core.asyncapi.components.examples.walkers.DefaultSchemaWalker; -import io.github.springwolf.core.asyncapi.components.examples.walkers.json.ExampleJsonValueGenerator; +import io.github.springwolf.core.asyncapi.messages.DefaultMessagesService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.PayloadService; import io.github.springwolf.core.asyncapi.scanners.common.payload.internal.TypeExtractor; -import io.github.springwolf.core.asyncapi.schemas.ModelConvertersProvider; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaMapper; -import io.github.springwolf.core.asyncapi.schemas.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.DefaultSchemasService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; +import io.github.springwolf.core.asyncapi.schemas.converters.ModelConvertersRegisterer; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaMapper; +import io.github.springwolf.core.asyncapi.schemas.schema.SwaggerSchemaService; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.SchemaWalkerProvider; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.DefaultSchemaWalker; +import io.github.springwolf.core.asyncapi.schemas.schema.examples.walkers.json.ExampleJsonValueGenerator; import io.github.springwolf.core.configuration.properties.SpringwolfConfigProperties; import io.github.springwolf.core.controller.PublishingPayloadCreator; import io.github.springwolf.core.controller.dtos.MessageDto; @@ -58,6 +60,8 @@ PublishingPayloadCreator.class, SpringwolfKafkaProducer.class, DefaultComponentsService.class, + DefaultSchemasService.class, + DefaultMessagesService.class, SwaggerSchemaService.class, PayloadService.class, SwaggerSchemaMapper.class, @@ -67,7 +71,7 @@ SchemaWalkerProvider.class, ExampleJsonValueGenerator.class, SpringwolfConfigProperties.class, - ModelConvertersProvider.class, + ModelConvertersRegisterer.class, JsonMapperTestConfiguration.class, }) @ExtendWith(MockitoExtension.class) @@ -84,7 +88,7 @@ class SpringwolfKafkaControllerIntegrationTest { private MockMvc mvc; @Autowired - private ComponentsService componentsService; + private SchemasService schemasService; @MockitoBean private SpringwolfKafkaProducer springwolfKafkaProducer; @@ -99,7 +103,7 @@ class SpringwolfKafkaControllerIntegrationTest { void setup() { when(springwolfKafkaProducer.isEnabled()).thenReturn(true); - componentsService.registerSchema(SchemaObject.builder() + schemasService.registerSchema(SchemaObject.builder() .title(PayloadDto.class.getName()) .properties(new HashMap<>()) .build()); diff --git a/springwolf-plugins/springwolf-sqs-plugin/src/main/java/io/github/springwolf/plugins/sqs/asyncapi/scanners/bindings/SqsBindingFactory.java b/springwolf-plugins/springwolf-sqs-plugin/src/main/java/io/github/springwolf/plugins/sqs/asyncapi/scanners/bindings/SqsBindingFactory.java index 047d191a2..7d73d6300 100644 --- a/springwolf-plugins/springwolf-sqs-plugin/src/main/java/io/github/springwolf/plugins/sqs/asyncapi/scanners/bindings/SqsBindingFactory.java +++ b/springwolf-plugins/springwolf-sqs-plugin/src/main/java/io/github/springwolf/plugins/sqs/asyncapi/scanners/bindings/SqsBindingFactory.java @@ -6,6 +6,7 @@ import io.github.springwolf.asyncapi.v3.bindings.MessageBinding; import io.github.springwolf.asyncapi.v3.bindings.OperationBinding; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; +import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingFactory; import lombok.RequiredArgsConstructor; import org.springframework.util.StringValueResolver; @@ -17,22 +18,23 @@ public class SqsBindingFactory implements BindingFactory { private final StringValueResolver stringValueResolver; @Override - public String getChannelName(SqsListener annotation) { - return SqsListenerUtil.getChannelName(annotation, stringValueResolver); + public String getChannelName(BindingContext bindingContext) { + return SqsListenerUtil.getChannelName(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildChannelBinding(SqsListener annotation) { - return SqsListenerUtil.buildChannelBinding(annotation, stringValueResolver); + public Map buildChannelBinding(BindingContext bindingContext) { + return SqsListenerUtil.buildChannelBinding(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildOperationBinding(SqsListener annotation) { - return SqsListenerUtil.buildOperationBinding(annotation, stringValueResolver); + public Map buildOperationBinding(BindingContext bindingContext) { + return SqsListenerUtil.buildOperationBinding(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildMessageBinding(SqsListener annotation, SchemaObject headerSchema) { + public Map buildMessageBinding( + BindingContext bindingContext, SchemaObject headerSchema) { return SqsListenerUtil.buildMessageBinding(); } } diff --git a/springwolf-plugins/springwolf-sqs-plugin/src/main/java/io/github/springwolf/plugins/sqs/configuration/SpringwolfSqsScannerConfiguration.java b/springwolf-plugins/springwolf-sqs-plugin/src/main/java/io/github/springwolf/plugins/sqs/configuration/SpringwolfSqsScannerConfiguration.java index e163bfe08..5d73a1352 100644 --- a/springwolf-plugins/springwolf-sqs-plugin/src/main/java/io/github/springwolf/plugins/sqs/configuration/SpringwolfSqsScannerConfiguration.java +++ b/springwolf-plugins/springwolf-sqs-plugin/src/main/java/io/github/springwolf/plugins/sqs/configuration/SpringwolfSqsScannerConfiguration.java @@ -2,7 +2,7 @@ package io.github.springwolf.plugins.sqs.configuration; import io.awspring.cloud.sqs.annotation.SqsListener; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.ChannelsScanner; import io.github.springwolf.core.asyncapi.scanners.OperationsScanner; import io.github.springwolf.core.asyncapi.scanners.channels.ChannelPriority; @@ -18,6 +18,7 @@ import io.github.springwolf.core.asyncapi.scanners.operations.OperationCustomizer; import io.github.springwolf.core.asyncapi.scanners.operations.OperationsInClassScannerAdapter; import io.github.springwolf.core.asyncapi.scanners.operations.annotations.SpringAnnotationMethodLevelOperationsScanner; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.standalone.StandaloneConfiguration; import io.github.springwolf.plugins.sqs.asyncapi.scanners.bindings.SqsBindingFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -54,10 +55,11 @@ public ChannelsScanner simpleSqsMethodLevelListenerAnnotationChannelsScanner( SqsBindingFactory sqsBindingFactory, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService) { + MessagesService messagesService, + SchemasService schemasService) { final var springAnnotationChannelService = new SpringAnnotationChannelService<>(sqsBindingFactory); final var springAnnotationMessageService = new SpringAnnotationMessageService<>( - sqsBindingFactory, new AsyncHeadersNotDocumented(), componentsService); + sqsBindingFactory, new AsyncHeadersNotDocumented(), messagesService, schemasService); SpringAnnotationMethodLevelChannelsScanner strategy = new SpringAnnotationMethodLevelChannelsScanner<>( SqsListener.class, @@ -77,12 +79,13 @@ public OperationsScanner simpleSqsMethodLevelListenerAnnotationOperationsScanner SqsBindingFactory sqsBindingFactory, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService, + MessagesService messagesService, + SchemasService schemasService, List operationCustomizers) { final var springAnnotationOperationService = new SpringAnnotationOperationService<>( sqsBindingFactory, new SpringAnnotationMessageService<>( - sqsBindingFactory, new AsyncHeadersNotDocumented(), componentsService)); + sqsBindingFactory, new AsyncHeadersNotDocumented(), messagesService, schemasService)); SpringAnnotationMethodLevelOperationsScanner strategy = new SpringAnnotationMethodLevelOperationsScanner<>( SqsListener.class, diff --git a/springwolf-plugins/springwolf-sqs-plugin/src/test/java/io/github/springwolf/plugins/sqs/configuration/SpringwolfSqsProducerConfigurationIntegrationTest.java b/springwolf-plugins/springwolf-sqs-plugin/src/test/java/io/github/springwolf/plugins/sqs/configuration/SpringwolfSqsProducerConfigurationIntegrationTest.java index 170f4d499..ae8742908 100644 --- a/springwolf-plugins/springwolf-sqs-plugin/src/test/java/io/github/springwolf/plugins/sqs/configuration/SpringwolfSqsProducerConfigurationIntegrationTest.java +++ b/springwolf-plugins/springwolf-sqs-plugin/src/test/java/io/github/springwolf/plugins/sqs/configuration/SpringwolfSqsProducerConfigurationIntegrationTest.java @@ -3,9 +3,11 @@ import io.awspring.cloud.sqs.operations.SqsTemplate; import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.classes.SpringwolfClassScanner; import io.github.springwolf.core.asyncapi.scanners.common.headers.HeaderClassExtractor; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadMethodParameterService; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.controller.PublishingPayloadCreator; import io.github.springwolf.plugins.sqs.controller.SpringwolfSqsController; import io.github.springwolf.plugins.sqs.producer.SpringwolfSqsProducer; @@ -41,6 +43,8 @@ public class SpringwolfSqsProducerConfigurationIntegrationTest { types = { SpringwolfClassScanner.class, ComponentsService.class, + MessagesService.class, + SchemasService.class, HeaderClassExtractor.class, PayloadMethodParameterService.class, StringValueResolver.class, @@ -79,6 +83,8 @@ void springwolfSqsProducerShouldBePresentInSpringContext() { types = { SpringwolfClassScanner.class, ComponentsService.class, + MessagesService.class, + SchemasService.class, HeaderClassExtractor.class, PayloadMethodParameterService.class, StringValueResolver.class, diff --git a/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingMessageMappingFactory.java b/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingMessageMappingFactory.java index 0c788a088..0aac029ba 100644 --- a/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingMessageMappingFactory.java +++ b/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingMessageMappingFactory.java @@ -5,6 +5,7 @@ import io.github.springwolf.asyncapi.v3.bindings.MessageBinding; import io.github.springwolf.asyncapi.v3.bindings.OperationBinding; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; +import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingFactory; import io.github.springwolf.plugins.stomp.asyncapi.scanners.common.MessageMappingUtil; import io.github.springwolf.plugins.stomp.configuration.properties.SpringwolfStompConfigProperties; @@ -20,22 +21,24 @@ public class StompBindingMessageMappingFactory implements BindingFactory bindingContext) { + return properties.getEndpoint().getApp() + + MessageMappingUtil.getChannelName(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildChannelBinding(MessageMapping annotation) { + public Map buildChannelBinding(BindingContext bindingContext) { return MessageMappingUtil.buildChannelBinding(); } @Override - public Map buildOperationBinding(MessageMapping annotation) { - return MessageMappingUtil.buildOperationBinding(annotation, stringValueResolver); + public Map buildOperationBinding(BindingContext bindingContext) { + return MessageMappingUtil.buildOperationBinding(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildMessageBinding(MessageMapping annotation, SchemaObject headerSchema) { + public Map buildMessageBinding( + BindingContext bindingContext, SchemaObject headerSchema) { return MessageMappingUtil.buildMessageBinding(); } } diff --git a/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingSendToFactory.java b/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingSendToFactory.java index 11728d2b5..0b48b7684 100644 --- a/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingSendToFactory.java +++ b/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingSendToFactory.java @@ -5,6 +5,7 @@ import io.github.springwolf.asyncapi.v3.bindings.MessageBinding; import io.github.springwolf.asyncapi.v3.bindings.OperationBinding; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; +import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingFactory; import io.github.springwolf.plugins.stomp.asyncapi.scanners.common.SendToUtil; import io.github.springwolf.plugins.stomp.configuration.properties.SpringwolfStompConfigProperties; @@ -20,22 +21,24 @@ public class StompBindingSendToFactory implements BindingFactory { private final StringValueResolver stringValueResolver; @Override - public String getChannelName(SendTo annotation) { - return properties.getEndpoint().getApp() + SendToUtil.getChannelName(annotation, stringValueResolver); + public String getChannelName(BindingContext bindingContext) { + return properties.getEndpoint().getApp() + + SendToUtil.getChannelName(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildChannelBinding(SendTo annotation) { + public Map buildChannelBinding(BindingContext bindingContext) { return SendToUtil.buildChannelBinding(); } @Override - public Map buildOperationBinding(SendTo annotation) { - return SendToUtil.buildOperationBinding(annotation, stringValueResolver); + public Map buildOperationBinding(BindingContext bindingContext) { + return SendToUtil.buildOperationBinding(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildMessageBinding(SendTo annotation, SchemaObject headerSchema) { + public Map buildMessageBinding( + BindingContext bindingContext, SchemaObject headerSchema) { return SendToUtil.buildMessageBinding(); } } diff --git a/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingSendToUserFactory.java b/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingSendToUserFactory.java index d62c097fb..d02768d67 100644 --- a/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingSendToUserFactory.java +++ b/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/bindings/StompBindingSendToUserFactory.java @@ -5,6 +5,7 @@ import io.github.springwolf.asyncapi.v3.bindings.MessageBinding; import io.github.springwolf.asyncapi.v3.bindings.OperationBinding; import io.github.springwolf.asyncapi.v3.model.schema.SchemaObject; +import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.bindings.BindingFactory; import io.github.springwolf.plugins.stomp.asyncapi.scanners.common.SendToUserUtil; import io.github.springwolf.plugins.stomp.asyncapi.scanners.common.SendToUtil; @@ -21,22 +22,24 @@ public class StompBindingSendToUserFactory implements BindingFactory private final StringValueResolver stringValueResolver; @Override - public String getChannelName(SendToUser annotation) { - return properties.getEndpoint().getUser() + SendToUserUtil.getChannelName(annotation, stringValueResolver); + public String getChannelName(BindingContext bindingContext) { + return properties.getEndpoint().getUser() + + SendToUserUtil.getChannelName(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildChannelBinding(SendToUser annotation) { + public Map buildChannelBinding(BindingContext bindingContext) { return SendToUserUtil.buildChannelBinding(); } @Override - public Map buildOperationBinding(SendToUser annotation) { - return SendToUserUtil.buildOperationBinding(annotation, stringValueResolver); + public Map buildOperationBinding(BindingContext bindingContext) { + return SendToUserUtil.buildOperationBinding(bindingContext.annotation(), stringValueResolver); } @Override - public Map buildMessageBinding(SendToUser annotation, SchemaObject headerSchema) { + public Map buildMessageBinding( + BindingContext bindingContext, SchemaObject headerSchema) { return SendToUtil.buildMessageBinding(); } } diff --git a/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/configuration/SpringwolfStompScannerConfiguration.java b/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/configuration/SpringwolfStompScannerConfiguration.java index 3ee3aef31..d88535c31 100644 --- a/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/configuration/SpringwolfStompScannerConfiguration.java +++ b/springwolf-plugins/springwolf-stomp-plugin/src/main/java/io/github/springwolf/plugins/stomp/configuration/SpringwolfStompScannerConfiguration.java @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 package io.github.springwolf.plugins.stomp.configuration; -import io.github.springwolf.core.asyncapi.components.ComponentsService; +import io.github.springwolf.core.asyncapi.messages.MessagesService; import io.github.springwolf.core.asyncapi.scanners.ChannelsScanner; import io.github.springwolf.core.asyncapi.scanners.OperationsScanner; import io.github.springwolf.core.asyncapi.scanners.channels.ChannelPriority; @@ -22,6 +22,7 @@ import io.github.springwolf.core.asyncapi.scanners.operations.OperationsInClassScannerAdapter; import io.github.springwolf.core.asyncapi.scanners.operations.annotations.SpringAnnotationClassLevelOperationsScanner; import io.github.springwolf.core.asyncapi.scanners.operations.annotations.SpringAnnotationMethodLevelOperationsScanner; +import io.github.springwolf.core.asyncapi.schemas.SchemasService; import io.github.springwolf.core.standalone.StandaloneConfiguration; import io.github.springwolf.plugins.stomp.asyncapi.scanners.bindings.StompBindingMessageMappingFactory; import io.github.springwolf.plugins.stomp.asyncapi.scanners.bindings.StompBindingSendToFactory; @@ -127,13 +128,15 @@ public ChannelsScanner simpleStompClassLevelListenerAnnotationChannelsScanner( AsyncHeadersForStompBuilder asyncHeadersForStompBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService) { + MessagesService messagesService, + SchemasService schemasService) { final var springAnnotationMessagesService = new SpringAnnotationMessagesService<>( stompBindingMessageMappingFactory, asyncHeadersForStompBuilder, payloadMethodParameterService, headerClassExtractor, - componentsService); + messagesService, + schemasService); final var springAnnotationChannelService = new SpringAnnotationChannelService<>(stompBindingMessageMappingFactory); SpringAnnotationClassLevelChannelsScanner strategy = @@ -159,7 +162,8 @@ public OperationsScanner simpleStompClassLevelListenerAnnotationOperationScanner AsyncHeadersForStompBuilder asyncHeadersForStompBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService, + MessagesService messagesService, + SchemasService schemasService, List operationCustomizers) { final var springAnnotationOperationsService = new SpringAnnotationOperationsService<>( stompBindingMessageMappingFactory, @@ -168,7 +172,8 @@ public OperationsScanner simpleStompClassLevelListenerAnnotationOperationScanner asyncHeadersForStompBuilder, payloadMethodParameterService, headerClassExtractor, - componentsService)); + messagesService, + schemasService)); SpringAnnotationClassLevelOperationsScanner strategy = new SpringAnnotationClassLevelOperationsScanner<>( MessageMapping.class, @@ -192,11 +197,12 @@ public ChannelsScanner simpleStompMethodLevelListenerAnnotationChannelsScanner( AsyncHeadersForStompBuilder asyncHeadersForStompBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService) { + MessagesService messagesService, + SchemasService schemasService) { final var springAnnotationChannelService = new SpringAnnotationChannelService<>(stompBindingMessageMappingFactory); final var springAnnotationMessageService = new SpringAnnotationMessageService<>( - stompBindingMessageMappingFactory, asyncHeadersForStompBuilder, componentsService); + stompBindingMessageMappingFactory, asyncHeadersForStompBuilder, messagesService, schemasService); SpringAnnotationMethodLevelChannelsScanner strategy = new SpringAnnotationMethodLevelChannelsScanner<>( MessageMapping.class, @@ -220,12 +226,16 @@ public OperationsScanner simpleStompMethodLevelListenerAnnotationOperationsScann AsyncHeadersForStompBuilder asyncHeadersForStompBuilder, PayloadMethodParameterService payloadMethodParameterService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService, + MessagesService messagesService, + SchemasService schemasService, List operationCustomizers) { final var springAnnotationOperationService = new SpringAnnotationOperationService<>( stompBindingMessageMappingFactory, new SpringAnnotationMessageService<>( - stompBindingMessageMappingFactory, asyncHeadersForStompBuilder, componentsService)); + stompBindingMessageMappingFactory, + asyncHeadersForStompBuilder, + messagesService, + schemasService)); SpringAnnotationMethodLevelOperationsScanner strategy = new SpringAnnotationMethodLevelOperationsScanner<>( MessageMapping.class, @@ -247,11 +257,12 @@ public ChannelsScanner simpleStompMethodLevelListenerSendToAnnotationChannelsSca AsyncHeadersForStompBuilder asyncHeadersForStompBuilder, PayloadMethodReturnService payloadMethodReturnService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService) { + MessagesService messagesService, + SchemasService schemasService) { final var springAnnotationChannelService = new SpringAnnotationChannelService<>(stompBindingMessageMappingFactory); final var springAnnotationMessageService = new SpringAnnotationMessageService<>( - stompBindingMessageMappingFactory, asyncHeadersForStompBuilder, componentsService); + stompBindingMessageMappingFactory, asyncHeadersForStompBuilder, messagesService, schemasService); SpringAnnotationMethodLevelChannelsScanner strategy = new SpringAnnotationMethodLevelChannelsScanner<>( SendTo.class, payloadMethodReturnService, @@ -274,11 +285,12 @@ public ChannelsScanner simpleStompMethodLevelListenerSendToUserAnnotationChannel AsyncHeadersForStompBuilder asyncHeadersForStompBuilder, PayloadMethodReturnService payloadMethodReturnService, HeaderClassExtractor headerClassExtractor, - ComponentsService componentsService) { + MessagesService messagesService, + SchemasService schemasService) { final var springAnnotationChannelService = new SpringAnnotationChannelService<>(stompBindingMessageMappingFactory); final var springAnnotationMessageService = new SpringAnnotationMessageService<>( - stompBindingMessageMappingFactory, asyncHeadersForStompBuilder, componentsService); + stompBindingMessageMappingFactory, asyncHeadersForStompBuilder, messagesService, schemasService); SpringAnnotationMethodLevelChannelsScanner strategy = new SpringAnnotationMethodLevelChannelsScanner<>( SendToUser.class, diff --git a/springwolf-plugins/springwolf-stomp-plugin/src/test/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/operation/annotations/SendToCustomizerTest.java b/springwolf-plugins/springwolf-stomp-plugin/src/test/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/operation/annotations/SendToCustomizerTest.java index 1c56e5df1..fbca27be3 100644 --- a/springwolf-plugins/springwolf-stomp-plugin/src/test/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/operation/annotations/SendToCustomizerTest.java +++ b/springwolf-plugins/springwolf-stomp-plugin/src/test/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/operation/annotations/SendToCustomizerTest.java @@ -4,7 +4,6 @@ import io.github.springwolf.asyncapi.v3.model.channel.ChannelReference; import io.github.springwolf.asyncapi.v3.model.channel.message.MessageReference; import io.github.springwolf.asyncapi.v3.model.operation.Operation; -import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadMethodReturnService; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; import io.github.springwolf.plugins.stomp.asyncapi.scanners.bindings.StompBindingSendToFactory; @@ -32,8 +31,8 @@ class SendToCustomizerTest { void customize() throws Exception { // given Operation operation = new Operation(); - when(bindingFactory.getChannelId(any(BindingContext.class))).thenReturn(CHANNEL_ID); - when(bindingFactory.getChannelName(any(BindingContext.class))).thenReturn(CHANNEL_ID); + when(bindingFactory.getChannelId(any())).thenReturn(CHANNEL_ID); + when(bindingFactory.getChannelName(any())).thenReturn(CHANNEL_ID); when(payloadService.extractSchema(any())).thenReturn(new PayloadSchemaObject(MESSAGE_ID, MESSAGE_ID, null)); // when diff --git a/springwolf-plugins/springwolf-stomp-plugin/src/test/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/operation/annotations/SendToUserCustomizerTest.java b/springwolf-plugins/springwolf-stomp-plugin/src/test/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/operation/annotations/SendToUserCustomizerTest.java index ae5a474dd..52ff3605f 100644 --- a/springwolf-plugins/springwolf-stomp-plugin/src/test/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/operation/annotations/SendToUserCustomizerTest.java +++ b/springwolf-plugins/springwolf-stomp-plugin/src/test/java/io/github/springwolf/plugins/stomp/asyncapi/scanners/operation/annotations/SendToUserCustomizerTest.java @@ -4,7 +4,6 @@ import io.github.springwolf.asyncapi.v3.model.channel.ChannelReference; import io.github.springwolf.asyncapi.v3.model.channel.message.MessageReference; import io.github.springwolf.asyncapi.v3.model.operation.Operation; -import io.github.springwolf.core.asyncapi.scanners.bindings.BindingContext; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadMethodReturnService; import io.github.springwolf.core.asyncapi.scanners.common.payload.PayloadSchemaObject; import io.github.springwolf.plugins.stomp.asyncapi.scanners.bindings.StompBindingSendToUserFactory; @@ -32,8 +31,8 @@ class SendToUserCustomizerTest { void customize() throws Exception { // given Operation operation = new Operation(); - when(bindingFactory.getChannelId(any(BindingContext.class))).thenReturn(CHANNEL_ID); - when(bindingFactory.getChannelName(any(BindingContext.class))).thenReturn(CHANNEL_ID); + when(bindingFactory.getChannelId(any())).thenReturn(CHANNEL_ID); + when(bindingFactory.getChannelName(any())).thenReturn(CHANNEL_ID); when(payloadService.extractSchema(any())).thenReturn(new PayloadSchemaObject(MESSAGE_ID, MESSAGE_ID, null)); // when diff --git a/springwolf-ui/src/app/components/header/header.component.html b/springwolf-ui/src/app/components/header/header.component.html index 4bc18a5cb..fd6a48267 100644 --- a/springwolf-ui/src/app/components/header/header.component.html +++ b/springwolf-ui/src/app/components/header/header.component.html @@ -7,7 +7,7 @@ class="flex flex-column items-center" > {{ title() }}   Github([]); diff --git a/springwolf-ui/src/app/service/mock/init-values.ts b/springwolf-ui/src/app/service/mock/init-values.ts index e0fb841bc..23975cca3 100644 --- a/springwolf-ui/src/app/service/mock/init-values.ts +++ b/springwolf-ui/src/app/service/mock/init-values.ts @@ -6,7 +6,8 @@ import { Binding, Bindings } from "../../models/bindings.model"; import { Message } from "../../models/message.model"; import { Info } from "../../models/info.model"; -// TODO: are the init values needed? +// These default values initialize Angular signals/components before async API data is loaded. +// They provide an empty, valid state while the real model is being fetched. export const initExample = new Example("init"); export const noExample = new Example(""); export const initBindings: Bindings = {};