From 78835e4bdadda930421cac5550b3c57adbe16785 Mon Sep 17 00:00:00 2001 From: Weidong Xu Date: Mon, 4 Mar 2024 14:22:28 +0800 Subject: [PATCH 1/2] add a case for enum as discriminator value --- Generate.ps1 | 3 +- vanilla-tests/swagger/discriminator-enum.json | 89 +++++++++++++++++++ 2 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 vanilla-tests/swagger/discriminator-enum.json diff --git a/Generate.ps1 b/Generate.ps1 index cca0295567..724773f381 100644 --- a/Generate.ps1 +++ b/Generate.ps1 @@ -144,7 +144,8 @@ $job = @( "$VANILLA_ARGUMENTS --input-file=vanilla-tests/swagger/xml-tag-with-attribute-and-value.json --namespace=fixtures.complexstreamstylexmlserialization --stream-style-serialization", "$VANILLA_ARGUMENTS --input-file=vanilla-tests/swagger/security-info.json --namespace=fixtures.securityinfo --use-key-credential", "$VANILLA_ARGUMENTS --input-file=vanilla-tests/swagger/special-header.json --namespace=fixtures.specialheader", - "$VANILLA_ARGUMENTS --input-file=vanilla-tests/swagger/required-fields-as-ctor-args-transformation.json --namespace=fixtures.requiredfieldsascotrargstransformation --required-fields-as-ctor-args=true --output-model-immutable --null-byte-array-maps-to-empty-array" + "$VANILLA_ARGUMENTS --input-file=vanilla-tests/swagger/required-fields-as-ctor-args-transformation.json --namespace=fixtures.requiredfieldsascotrargstransformation --required-fields-as-ctor-args=true --output-model-immutable --null-byte-array-maps-to-empty-array", + "$VANILLA_ARGUMENTS --input-file=vanilla-tests/swagger/discriminator-enum.json --namespace=fixtures.discriminatorenum" ) | ForEach-Object -Parallel $generateScript -ThrottleLimit $Parallelization -AsJob $job | Wait-Job -Timeout 120 diff --git a/vanilla-tests/swagger/discriminator-enum.json b/vanilla-tests/swagger/discriminator-enum.json new file mode 100644 index 0000000000..75fa1232bd --- /dev/null +++ b/vanilla-tests/swagger/discriminator-enum.json @@ -0,0 +1,89 @@ +{ + "swagger": "2.0", + "info": { + "title": "EnumDiscriminator", + "version": "0000-00-00", + "x-typespec-generated": [ + { + "emitter": "@azure-tools/typespec-autorest" + } + ] + }, + "schemes": [ + "https" + ], + "produces": [ + "application/json" + ], + "consumes": [ + "application/json" + ], + "tags": [], + "paths": { + "/extensible-enum": { + "get": { + "operationId": "GetExtensibleModel", + "parameters": [], + "responses": { + "200": { + "description": "The request has succeeded.", + "schema": { + "$ref": "#/definitions/Dog" + } + } + } + } + } + }, + "definitions": { + "Dog": { + "type": "object", + "description": "Test extensible enum type for discriminator", + "properties": { + "kind": { + "$ref": "#/definitions/DogKind", + "description": "discriminator property" + }, + "weight": { + "type": "integer", + "format": "int32", + "description": "Weight of the dog" + } + }, + "discriminator": "kind", + "required": [ + "kind", + "weight" + ] + }, + "DogKind": { + "type": "string", + "description": "extensible enum type for discriminator", + "enum": [ + "golden" + ], + "x-ms-enum": { + "name": "DogKind", + "modelAsString": true, + "values": [ + { + "name": "Golden", + "value": "golden", + "description": "Species golden" + } + ] + } + }, + "Golden": { + "type": "object", + "description": "Golden dog model", + "allOf": [ + { + "$ref": "#/definitions/Dog" + } + ], + "x-ms-discriminator-value": "golden" + } + }, + "parameters": {} +} From 688e425fb4b2d9db5983fbfc261e97c45ded662b Mon Sep 17 00:00:00 2001 From: actions-user Date: Mon, 4 Mar 2024 06:34:38 +0000 Subject: [PATCH 2/2] re-generate test code --- .../discriminatorenum/EnumDiscriminator.java | 213 ++++++++++++++ .../EnumDiscriminatorBuilder.java | 278 ++++++++++++++++++ .../discriminatorenum/models/Dog.java | 147 +++++++++ .../discriminatorenum/models/DogKind.java | 46 +++ .../discriminatorenum/models/Golden.java | 82 ++++++ .../models/package-info.java | 9 + .../discriminatorenum/package-info.java | 9 + 7 files changed, 784 insertions(+) create mode 100644 vanilla-tests/src/main/java/fixtures/discriminatorenum/EnumDiscriminator.java create mode 100644 vanilla-tests/src/main/java/fixtures/discriminatorenum/EnumDiscriminatorBuilder.java create mode 100644 vanilla-tests/src/main/java/fixtures/discriminatorenum/models/Dog.java create mode 100644 vanilla-tests/src/main/java/fixtures/discriminatorenum/models/DogKind.java create mode 100644 vanilla-tests/src/main/java/fixtures/discriminatorenum/models/Golden.java create mode 100644 vanilla-tests/src/main/java/fixtures/discriminatorenum/models/package-info.java create mode 100644 vanilla-tests/src/main/java/fixtures/discriminatorenum/package-info.java diff --git a/vanilla-tests/src/main/java/fixtures/discriminatorenum/EnumDiscriminator.java b/vanilla-tests/src/main/java/fixtures/discriminatorenum/EnumDiscriminator.java new file mode 100644 index 0000000000..a8e0a27b0e --- /dev/null +++ b/vanilla-tests/src/main/java/fixtures/discriminatorenum/EnumDiscriminator.java @@ -0,0 +1,213 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package fixtures.discriminatorenum; + +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.core.util.serializer.SerializerAdapter; +import fixtures.discriminatorenum.models.Dog; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the EnumDiscriminator type. + */ +public final class EnumDiscriminator { + /** + * The proxy service used to perform REST calls. + */ + private final EnumDiscriminatorService service; + + /** + * server parameter. + */ + private final String host; + + /** + * Gets server parameter. + * + * @return the host value. + */ + public String getHost() { + return this.host; + } + + /** + * The HTTP pipeline to send requests through. + */ + private final HttpPipeline httpPipeline; + + /** + * Gets The HTTP pipeline to send requests through. + * + * @return the httpPipeline value. + */ + public HttpPipeline getHttpPipeline() { + return this.httpPipeline; + } + + /** + * The serializer to serialize an object into a string. + */ + private final SerializerAdapter serializerAdapter; + + /** + * Gets The serializer to serialize an object into a string. + * + * @return the serializerAdapter value. + */ + public SerializerAdapter getSerializerAdapter() { + return this.serializerAdapter; + } + + /** + * Initializes an instance of EnumDiscriminator client. + * + * @param host server parameter. + */ + EnumDiscriminator(String host) { + this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), + JacksonAdapter.createDefaultSerializerAdapter(), host); + } + + /** + * Initializes an instance of EnumDiscriminator client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param host server parameter. + */ + EnumDiscriminator(HttpPipeline httpPipeline, String host) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), host); + } + + /** + * Initializes an instance of EnumDiscriminator client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param serializerAdapter The serializer to serialize an object into a string. + * @param host server parameter. + */ + EnumDiscriminator(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String host) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.host = host; + this.service = RestProxy.create(EnumDiscriminatorService.class, this.httpPipeline, this.getSerializerAdapter()); + } + + /** + * The interface defining all the services for EnumDiscriminator to be used by the proxy service to perform REST calls. + */ + @Host("{$host}") + @ServiceInterface(name = "EnumDiscriminator") + public interface EnumDiscriminatorService { + @Get("/extensible-enum") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getExtensibleModel(@HostParam("$host") String host, @HeaderParam("Accept") String accept, + Context context); + } + + /** + * The getExtensibleModel operation. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return test extensible enum type for discriminator along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getExtensibleModelWithResponseAsync() { + if (this.getHost() == null) { + return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); + } + final String accept = "application/json"; + return FluxUtil.withContext(context -> service.getExtensibleModel(this.getHost(), accept, context)); + } + + /** + * The getExtensibleModel operation. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return test extensible enum type for discriminator along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getExtensibleModelWithResponseAsync(Context context) { + if (this.getHost() == null) { + return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); + } + final String accept = "application/json"; + return service.getExtensibleModel(this.getHost(), accept, context); + } + + /** + * The getExtensibleModel operation. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return test extensible enum type for discriminator on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getExtensibleModelAsync() { + return getExtensibleModelWithResponseAsync().flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * The getExtensibleModel operation. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return test extensible enum type for discriminator on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getExtensibleModelAsync(Context context) { + return getExtensibleModelWithResponseAsync(context).flatMap(res -> Mono.justOrEmpty(res.getValue())); + } + + /** + * The getExtensibleModel operation. + * + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return test extensible enum type for discriminator along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getExtensibleModelWithResponse(Context context) { + return getExtensibleModelWithResponseAsync(context).block(); + } + + /** + * The getExtensibleModel operation. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return test extensible enum type for discriminator. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Dog getExtensibleModel() { + return getExtensibleModelWithResponse(Context.NONE).getValue(); + } +} diff --git a/vanilla-tests/src/main/java/fixtures/discriminatorenum/EnumDiscriminatorBuilder.java b/vanilla-tests/src/main/java/fixtures/discriminatorenum/EnumDiscriminatorBuilder.java new file mode 100644 index 0000000000..fec052a658 --- /dev/null +++ b/vanilla-tests/src/main/java/fixtures/discriminatorenum/EnumDiscriminatorBuilder.java @@ -0,0 +1,278 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package fixtures.discriminatorenum; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.client.traits.ConfigurationTrait; +import com.azure.core.client.traits.HttpTrait; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.HttpPipelinePosition; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.policy.AddHeadersPolicy; +import com.azure.core.http.policy.HttpLoggingPolicy; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.core.http.policy.HttpPolicyProviders; +import com.azure.core.http.policy.RequestIdPolicy; +import com.azure.core.http.policy.RetryOptions; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.util.ClientOptions; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.builder.ClientBuilderUtil; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.core.util.serializer.SerializerAdapter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * A builder for creating a new instance of the EnumDiscriminator type. + */ +@ServiceClientBuilder(serviceClients = { EnumDiscriminator.class }) +public final class EnumDiscriminatorBuilder + implements HttpTrait, ConfigurationTrait { + @Generated + private static final String SDK_NAME = "name"; + + @Generated + private static final String SDK_VERSION = "version"; + + @Generated + private static final Map PROPERTIES = new HashMap<>(); + + @Generated + private final List pipelinePolicies; + + /** + * Create an instance of the EnumDiscriminatorBuilder. + */ + @Generated + public EnumDiscriminatorBuilder() { + this.pipelinePolicies = new ArrayList<>(); + } + + /* + * The HTTP pipeline to send requests through. + */ + @Generated + private HttpPipeline pipeline; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public EnumDiscriminatorBuilder pipeline(HttpPipeline pipeline) { + this.pipeline = pipeline; + return this; + } + + /* + * The HTTP client used to send the request. + */ + @Generated + private HttpClient httpClient; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public EnumDiscriminatorBuilder httpClient(HttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /* + * The logging configuration for HTTP requests and responses. + */ + @Generated + private HttpLogOptions httpLogOptions; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public EnumDiscriminatorBuilder httpLogOptions(HttpLogOptions httpLogOptions) { + this.httpLogOptions = httpLogOptions; + return this; + } + + /* + * The client options such as application ID and custom headers to set on a request. + */ + @Generated + private ClientOptions clientOptions; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public EnumDiscriminatorBuilder clientOptions(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + return this; + } + + /* + * The retry options to configure retry policy for failed requests. + */ + @Generated + private RetryOptions retryOptions; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public EnumDiscriminatorBuilder retryOptions(RetryOptions retryOptions) { + this.retryOptions = retryOptions; + return this; + } + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public EnumDiscriminatorBuilder addPolicy(HttpPipelinePolicy customPolicy) { + Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); + pipelinePolicies.add(customPolicy); + return this; + } + + /* + * The configuration store that is used during construction of the service client. + */ + @Generated + private Configuration configuration; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public EnumDiscriminatorBuilder configuration(Configuration configuration) { + this.configuration = configuration; + return this; + } + + /* + * server parameter + */ + @Generated + private String host; + + /** + * Sets server parameter. + * + * @param host the host value. + * @return the EnumDiscriminatorBuilder. + */ + @Generated + public EnumDiscriminatorBuilder host(String host) { + this.host = host; + return this; + } + + /* + * The serializer to serialize an object into a string + */ + @Generated + private SerializerAdapter serializerAdapter; + + /** + * Sets The serializer to serialize an object into a string. + * + * @param serializerAdapter the serializerAdapter value. + * @return the EnumDiscriminatorBuilder. + */ + @Generated + public EnumDiscriminatorBuilder serializerAdapter(SerializerAdapter serializerAdapter) { + this.serializerAdapter = serializerAdapter; + return this; + } + + /* + * The retry policy that will attempt to retry failed requests, if applicable. + */ + @Generated + private RetryPolicy retryPolicy; + + /** + * Sets The retry policy that will attempt to retry failed requests, if applicable. + * + * @param retryPolicy the retryPolicy value. + * @return the EnumDiscriminatorBuilder. + */ + @Generated + public EnumDiscriminatorBuilder retryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; + return this; + } + + /** + * Builds an instance of EnumDiscriminator with the provided parameters. + * + * @return an instance of EnumDiscriminator. + */ + @Generated + public EnumDiscriminator buildClient() { + HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); + String localHost = (host != null) ? host : ""; + SerializerAdapter localSerializerAdapter + = (serializerAdapter != null) ? serializerAdapter : JacksonAdapter.createDefaultSerializerAdapter(); + EnumDiscriminator client = new EnumDiscriminator(localPipeline, localSerializerAdapter, localHost); + return client; + } + + @Generated + private HttpPipeline createHttpPipeline() { + Configuration buildConfiguration + = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; + HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions; + ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions; + List policies = new ArrayList<>(); + String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName"); + String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion"); + String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions); + policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); + policies.add(new RequestIdPolicy()); + policies.add(new AddHeadersFromContextPolicy()); + HttpHeaders headers = new HttpHeaders(); + localClientOptions.getHeaders() + .forEach(header -> headers.set(HttpHeaderName.fromString(header.getName()), header.getValue())); + if (headers.getSize() > 0) { + policies.add(new AddHeadersPolicy(headers)); + } + this.pipelinePolicies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL) + .forEach(p -> policies.add(p)); + HttpPolicyProviders.addBeforeRetryPolicies(policies); + policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy())); + policies.add(new AddDatePolicy()); + this.pipelinePolicies.stream() + .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY) + .forEach(p -> policies.add(p)); + HttpPolicyProviders.addAfterRetryPolicies(policies); + policies.add(new HttpLoggingPolicy(localHttpLogOptions)); + HttpPipeline httpPipeline = new HttpPipelineBuilder().policies(policies.toArray(new HttpPipelinePolicy[0])) + .httpClient(httpClient) + .clientOptions(localClientOptions) + .build(); + return httpPipeline; + } +} diff --git a/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/Dog.java b/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/Dog.java new file mode 100644 index 0000000000..5970cd03f7 --- /dev/null +++ b/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/Dog.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package fixtures.discriminatorenum.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Test extensible enum type for discriminator. + */ +@Fluent +public class Dog implements JsonSerializable { + /* + * discriminator property + */ + private DogKind kind; + + /* + * Weight of the dog + */ + private int weight; + + /** + * Creates an instance of Dog class. + */ + public Dog() { + this.kind = DogKind.fromString("Dog"); + } + + /** + * Get the kind property: discriminator property. + * + * @return the kind value. + */ + public DogKind getKind() { + return this.kind; + } + + /** + * Set the kind property: discriminator property. + * + * @param kind the kind value to set. + * @return the Dog object itself. + */ + Dog setKind(DogKind kind) { + this.kind = kind; + return this; + } + + /** + * Get the weight property: Weight of the dog. + * + * @return the weight value. + */ + public int getWeight() { + return this.weight; + } + + /** + * Set the weight property: Weight of the dog. + * + * @param weight the weight value to set. + * @return the Dog object itself. + */ + public Dog setWeight(int weight) { + this.weight = weight; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() { + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("weight", this.weight); + jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Dog from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Dog if the JsonReader was pointing to an instance of it, or null if it was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the Dog. + */ + public static Dog fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String discriminatorValue = null; + try (JsonReader readerToUse = reader.bufferObject()) { + readerToUse.nextToken(); // Prepare for reading + while (readerToUse.nextToken() != JsonToken.END_OBJECT) { + String fieldName = readerToUse.getFieldName(); + readerToUse.nextToken(); + if ("kind".equals(fieldName)) { + discriminatorValue = readerToUse.getString(); + break; + } else { + readerToUse.skipChildren(); + } + } + // Use the discriminator value to determine which subtype should be deserialized. + if ("golden".equals(discriminatorValue)) { + return Golden.fromJson(readerToUse.reset()); + } else { + return fromJsonKnownDiscriminator(readerToUse.reset()); + } + } + }); + } + + static Dog fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Dog deserializedDog = new Dog(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("weight".equals(fieldName)) { + deserializedDog.weight = reader.getInt(); + } else if ("kind".equals(fieldName)) { + deserializedDog.kind = DogKind.fromString(reader.getString()); + } else { + reader.skipChildren(); + } + } + + return deserializedDog; + }); + } +} diff --git a/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/DogKind.java b/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/DogKind.java new file mode 100644 index 0000000000..9059776aa2 --- /dev/null +++ b/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/DogKind.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package fixtures.discriminatorenum.models; + +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * extensible enum type for discriminator. + */ +public final class DogKind extends ExpandableStringEnum { + /** + * Species golden. + */ + public static final DogKind GOLDEN = fromString("golden"); + + /** + * Creates a new instance of DogKind value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Deprecated + public DogKind() { + } + + /** + * Creates or finds a DogKind from its string representation. + * + * @param name a name to look for. + * @return the corresponding DogKind. + */ + public static DogKind fromString(String name) { + return fromString(name, DogKind.class); + } + + /** + * Gets known DogKind values. + * + * @return known DogKind values. + */ + public static Collection values() { + return values(DogKind.class); + } +} diff --git a/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/Golden.java b/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/Golden.java new file mode 100644 index 0000000000..a8f91ad88a --- /dev/null +++ b/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/Golden.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package fixtures.discriminatorenum.models; + +import com.azure.core.annotation.Fluent; +import com.azure.json.JsonReader; +import com.azure.json.JsonToken; +import com.azure.json.JsonWriter; +import java.io.IOException; + +/** + * Golden dog model. + */ +@Fluent +public final class Golden extends Dog { + /** + * Creates an instance of Golden class. + */ + public Golden() { + setKind(DogKind.GOLDEN); + } + + /** + * {@inheritDoc} + */ + @Override + public Golden setWeight(int weight) { + super.setWeight(weight); + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + @Override + public void validate() { + super.validate(); + } + + /** + * {@inheritDoc} + */ + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeIntField("weight", getWeight()); + jsonWriter.writeStringField("kind", getKind() == null ? null : getKind().toString()); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of Golden from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of Golden if the JsonReader was pointing to an instance of it, or null if it was pointing to JSON null. + * @throws IllegalStateException If the deserialized JSON object was missing any required properties. + * @throws IOException If an error occurs while reading the Golden. + */ + public static Golden fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Golden deserializedGolden = new Golden(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("weight".equals(fieldName)) { + deserializedGolden.setWeight(reader.getInt()); + } else if ("kind".equals(fieldName)) { + deserializedGolden.setKind(DogKind.fromString(reader.getString())); + } else { + reader.skipChildren(); + } + } + + return deserializedGolden; + }); + } +} diff --git a/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/package-info.java b/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/package-info.java new file mode 100644 index 0000000000..c23abe46d8 --- /dev/null +++ b/vanilla-tests/src/main/java/fixtures/discriminatorenum/models/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * Package containing the data models for EnumDiscriminator. + * null. + */ +package fixtures.discriminatorenum.models; diff --git a/vanilla-tests/src/main/java/fixtures/discriminatorenum/package-info.java b/vanilla-tests/src/main/java/fixtures/discriminatorenum/package-info.java new file mode 100644 index 0000000000..bbc2f89276 --- /dev/null +++ b/vanilla-tests/src/main/java/fixtures/discriminatorenum/package-info.java @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * Package containing the classes for EnumDiscriminator. + * null. + */ +package fixtures.discriminatorenum;