diff --git a/customization-tests/src/main/java/fixtures/bodycomplex/implementation/CoreToCodegenBridgeUtils.java b/customization-tests/src/main/java/fixtures/bodycomplex/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 3c4d3fd742..0000000000 --- a/customization-tests/src/main/java/fixtures/bodycomplex/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package fixtures.bodycomplex.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/customization-tests/src/main/java/fixtures/bodycomplex/implementation/models/DurationWrapper.java b/customization-tests/src/main/java/fixtures/bodycomplex/implementation/models/DurationWrapper.java index 919fdbc2a3..5bcee97769 100644 --- a/customization-tests/src/main/java/fixtures/bodycomplex/implementation/models/DurationWrapper.java +++ b/customization-tests/src/main/java/fixtures/bodycomplex/implementation/models/DurationWrapper.java @@ -5,11 +5,11 @@ package fixtures.bodycomplex.implementation.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import fixtures.bodycomplex.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; @@ -55,7 +55,7 @@ public DurationWrapper setField(Duration field) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("field", CoreToCodegenBridgeUtils.durationToStringWithDays(this.field)); + jsonWriter.writeStringField("field", CoreUtils.durationToStringWithDays(this.field)); return jsonWriter.writeEndObject(); } diff --git a/javagen/src/main/java/com/azure/autorest/Javagen.java b/javagen/src/main/java/com/azure/autorest/Javagen.java index 23637b0763..d5a9495193 100644 --- a/javagen/src/main/java/com/azure/autorest/Javagen.java +++ b/javagen/src/main/java/com/azure/autorest/Javagen.java @@ -341,20 +341,6 @@ protected void writeClientModels(Client client, JavaPackage javaPackage, JavaSet } protected void writeHelperClasses(Client client, JavaPackage javaPackage, JavaSettings settings) { - // While azure-core's ResponseError hasn't shipped implementing JsonSerializable add a utility method that - // will serialize and deserialize ResponseError. - if (settings.isStreamStyleSerialization()) { - boolean generateCoreToCodegenBridgeUtils = false; - for (ClientModel model : client.getModels()) { - if (ClientModelUtil.generateCoreToCodegenBridgeUtils(model, settings)) { - generateCoreToCodegenBridgeUtils = true; - break; - } - } - if (generateCoreToCodegenBridgeUtils) { - javaPackage.addJavaFromResources(settings.getPackage(settings.getImplementationSubpackage()), ClientModelUtil.CORE_TO_CODEGEN_BRIDGE_UTILS_CLASS_NAME); - } - } } private void clear() { diff --git a/javagen/src/main/java/com/azure/autorest/model/clientmodel/ClassType.java b/javagen/src/main/java/com/azure/autorest/model/clientmodel/ClassType.java index 9845ddb057..9ea376c267 100644 --- a/javagen/src/main/java/com/azure/autorest/model/clientmodel/ClassType.java +++ b/javagen/src/main/java/com/azure/autorest/model/clientmodel/ClassType.java @@ -5,7 +5,6 @@ import com.azure.autorest.extension.base.model.extensionmodel.XmsExtensions; import com.azure.autorest.extension.base.plugin.JavaSettings; -import com.azure.autorest.util.ClientModelUtil; import com.azure.autorest.util.TemplateUtil; import com.azure.core.client.traits.ConfigurationTrait; import com.azure.core.client.traits.EndpointTrait; @@ -149,6 +148,24 @@ private static ClassType.Builder getClassTypeBuilder(Class classKey) { } } + public static final ClassType REQUEST_CONDITIONS = new Builder().knownClass(RequestConditions.class).build(); + public static final ClassType MATCH_CONDITIONS = new Builder().knownClass(MatchConditions.class).build(); + public static final ClassType CORE_UTILS = getClassTypeBuilder(CoreUtils.class).build(); + public static final ClassType RESPONSE = getClassTypeBuilder(Response.class).build(); + public static final ClassType SIMPLE_RESPONSE = getClassTypeBuilder(SimpleResponse.class).build(); + public static final ClassType EXPANDABLE_STRING_ENUM = getClassTypeBuilder(ExpandableStringEnum.class).build(); + public static final ClassType HTTP_PIPELINE_BUILDER = getClassTypeBuilder(HttpPipelineBuilder.class).build(); + public static final ClassType KEY_CREDENTIAL_POLICY = getClassTypeBuilder(KeyCredentialPolicy.class).build(); + public static final ClassType KEY_CREDENTIAL_TRAIT = getClassTypeBuilder(KeyCredentialTrait.class).build(); + public static final ClassType ENDPOINT_TRAIT = getClassTypeBuilder(EndpointTrait.class).build(); + public static final ClassType HTTP_TRAIT = getClassTypeBuilder(HttpTrait.class).build(); + public static final ClassType CONFIGURATION_TRAIT = getClassTypeBuilder(ConfigurationTrait.class).build(); + public static final ClassType POLL_OPERATION_DETAILS = getClassTypeBuilder(PollOperationDetails.class).build(); + public static final ClassType JSON_SERIALIZABLE = getClassTypeBuilder(JsonSerializable.class).build(); + public static final ClassType JSON_WRITER = getClassTypeBuilder(JsonWriter.class).build(); + public static final ClassType JSON_READER = getClassTypeBuilder(JsonReader.class).build(); + public static final ClassType JSON_TOKEN = getClassTypeBuilder(JsonToken.class).build(); + public static final ClassType TYPE_REFERENCE = getClassTypeBuilder(TypeReference.class).build(); public static final ClassType VOID = new ClassType.Builder(false).knownClass(Void.class).build(); @@ -254,7 +271,7 @@ private static ClassType.Builder getClassTypeBuilder(Class classKey) { public static final ClassType DURATION = new Builder(false).knownClass(Duration.class) .defaultValueExpressionConverter(defaultValueExpression -> "Duration.parse(\"" + defaultValueExpression + "\")") .jsonToken("JsonToken.STRING") - .serializationValueGetterModifier(valueGetter -> ClientModelUtil.CORE_TO_CODEGEN_BRIDGE_UTILS_CLASS_NAME + ".durationToStringWithDays(" + valueGetter + ")") + .serializationValueGetterModifier(valueGetter -> CORE_UTILS.getName() + ".durationToStringWithDays(" + valueGetter + ")") .jsonDeserializationMethod("getNullable(nonNullReader -> Duration.parse(nonNullReader.getString()))") .serializationMethodBase("writeString") .xmlElementDeserializationMethod("getNullableElement(Duration::parse)") @@ -471,25 +488,6 @@ private static ClassType.Builder getClassTypeBuilder(Class classKey) { .jsonToken("JsonToken.START_OBJECT") .build(); - public static final ClassType REQUEST_CONDITIONS = new Builder().knownClass(RequestConditions.class).build(); - public static final ClassType MATCH_CONDITIONS = new Builder().knownClass(MatchConditions.class).build(); - public static final ClassType CORE_UTILS = getClassTypeBuilder(CoreUtils.class).build(); - public static final ClassType RESPONSE = getClassTypeBuilder(Response.class).build(); - public static final ClassType SIMPLE_RESPONSE = getClassTypeBuilder(SimpleResponse.class).build(); - public static final ClassType EXPANDABLE_STRING_ENUM = getClassTypeBuilder(ExpandableStringEnum.class).build(); - public static final ClassType HTTP_PIPELINE_BUILDER = getClassTypeBuilder(HttpPipelineBuilder.class).build(); - public static final ClassType KEY_CREDENTIAL_POLICY = getClassTypeBuilder(KeyCredentialPolicy.class).build(); - public static final ClassType KEY_CREDENTIAL_TRAIT = getClassTypeBuilder(KeyCredentialTrait.class).build(); - public static final ClassType ENDPOINT_TRAIT = getClassTypeBuilder(EndpointTrait.class).build(); - public static final ClassType HTTP_TRAIT = getClassTypeBuilder(HttpTrait.class).build(); - public static final ClassType CONFIGURATION_TRAIT = getClassTypeBuilder(ConfigurationTrait.class).build(); - public static final ClassType POLL_OPERATION_DETAILS = getClassTypeBuilder(PollOperationDetails.class).build(); - public static final ClassType JSON_SERIALIZABLE = getClassTypeBuilder(JsonSerializable.class).build(); - public static final ClassType JSON_WRITER = getClassTypeBuilder(JsonWriter.class).build(); - public static final ClassType JSON_READER = getClassTypeBuilder(JsonReader.class).build(); - public static final ClassType JSON_TOKEN = getClassTypeBuilder(JsonToken.class).build(); - public static final ClassType TYPE_REFERENCE = getClassTypeBuilder(TypeReference.class).build(); - private final String fullName; private final String packageName; private final String name; diff --git a/javagen/src/main/java/com/azure/autorest/template/StreamSerializationModelTemplate.java b/javagen/src/main/java/com/azure/autorest/template/StreamSerializationModelTemplate.java index 1762cdb268..0237a4b844 100644 --- a/javagen/src/main/java/com/azure/autorest/template/StreamSerializationModelTemplate.java +++ b/javagen/src/main/java/com/azure/autorest/template/StreamSerializationModelTemplate.java @@ -89,8 +89,6 @@ protected void addSerializationImports(Set imports, ClientModel model, J imports.add(List.class.getName()); imports.add(Map.class.getName()); imports.add(Objects.class.getName()); - imports.add(settings.getPackage(settings.getImplementationSubpackage()) + "." - + ClientModelUtil.CORE_TO_CODEGEN_BRIDGE_UTILS_CLASS_NAME); } @Override @@ -377,11 +375,7 @@ private static void serializeJsonProperty(JavaBlock methodBlock, ClientModelProp // This is primitives, boxed primitives, a small set of string based models, and other ClientModels. String fieldSerializationMethod = wireType.jsonSerializationMethodCall("jsonWriter", serializedName, propertyValueGetter); - if (wireType == ClassType.RESPONSE_ERROR) { - // While azure-core hasn't shipped ResponseError implementing JsonSerializable it has special handling. - methodBlock.line("jsonWriter.writeFieldName(\"" + serializedName + "\");"); - methodBlock.line(ClientModelUtil.CORE_TO_CODEGEN_BRIDGE_UTILS_CLASS_NAME + ".responseErrorToJson(jsonWriter, " + propertyValueGetter + ");"); - } else if (fieldSerializationMethod != null) { + if (fieldSerializationMethod != null) { if (isJsonMergePatch && wireType instanceof ClassType && ((ClassType) wireType).isSwaggerType()) { methodBlock.line(propertyValueGetter + ".serializeAsJsonMergePatch(true);"); } @@ -475,11 +469,7 @@ private static void serializeJsonContainerProperty(JavaBlock methodBlock, String } methodBlock.indent(() -> { - if (elementType == ClassType.RESPONSE_ERROR) { - // While azure-core hasn't shipped ResponseError implementing JsonSerializable it has special handling. - methodBlock.line(lambdaWriterName + ".writeFieldName(\"" + serializedName + "\");"); - methodBlock.line(ClientModelUtil.CORE_TO_CODEGEN_BRIDGE_UTILS_CLASS_NAME + ".responseErrorToJson(" + lambdaWriterName + ", " + propertyValueGetter + ");"); - } else if (valueSerializationMethod != null) { + if (valueSerializationMethod != null) { if (isJsonMergePatch && containerType instanceof MapType) { methodBlock.block("", codeBlock -> { codeBlock.ifBlock(elementName + "!=null", ifBlock -> { @@ -1038,15 +1028,7 @@ private static void generateJsonDeserializationLogic(JavaBlock deserializationBl // Attempt to determine whether the wire type is simple deserialization. // This is primitives, boxed primitives, a small set of string based models, and other ClientModels. String simpleDeserialization = getSimpleJsonDeserialization(wireType, "reader"); - if (wireType == ClassType.RESPONSE_ERROR) { - // While azure-core hasn't shipped ResponseError implementing JsonSerializable it has special handling. - if (!hasConstructorArguments) { - handleSettingDeserializedValue(deserializationBlock, modelVariableName, property, - ClientModelUtil.CORE_TO_CODEGEN_BRIDGE_UTILS_CLASS_NAME + ".responseErrorFromJson(reader)", fromSuper); - } else { - deserializationBlock.line(property.getName() + " = " + ClientModelUtil.CORE_TO_CODEGEN_BRIDGE_UTILS_CLASS_NAME + ".responseErrorFromJson(reader);"); - } - } else if (simpleDeserialization != null) { + if (simpleDeserialization != null) { // Need to convert the wire type to the client type for constructors. // Need to convert the wire type to the client type for public setters. boolean convertToClientType = (clientType != wireType) @@ -1153,10 +1135,7 @@ private static void deserializeJsonContainerProperty(JavaBlock methodBlock, Stri methodBlock.line(callingReaderName + "." + utilityMethod + "(" + lambdaReaderName + " ->"); } methodBlock.indent(() -> { - if (elementWireType == ClassType.RESPONSE_ERROR) { - // While azure-core hasn't shipped ResponseError implementing JsonSerializable it has special handling. - methodBlock.line(ClientModelUtil.CORE_TO_CODEGEN_BRIDGE_UTILS_CLASS_NAME + ".responseErrorFromJson(" + lambdaReaderName + ")"); - } else if (valueDeserializationMethod != null) { + if (valueDeserializationMethod != null) { if (convertToClientType) { // If the wire type is nullable don't attempt to call the convert to client type until it's known that // a value was deserialized. This protects against cases such as UnixTimeLong where the wire type is diff --git a/javagen/src/main/java/com/azure/autorest/util/ClientModelUtil.java b/javagen/src/main/java/com/azure/autorest/util/ClientModelUtil.java index 46a4121ecd..aeedb816ca 100644 --- a/javagen/src/main/java/com/azure/autorest/util/ClientModelUtil.java +++ b/javagen/src/main/java/com/azure/autorest/util/ClientModelUtil.java @@ -18,7 +18,6 @@ import com.azure.autorest.model.clientmodel.ClientModel; import com.azure.autorest.model.clientmodel.ClientModelProperty; import com.azure.autorest.model.clientmodel.ClientModelPropertyAccess; -import com.azure.autorest.model.clientmodel.ClientModelPropertyReference; import com.azure.autorest.model.clientmodel.ClientModels; import com.azure.autorest.model.clientmodel.ConvenienceMethod; import com.azure.autorest.model.clientmodel.GenericType; @@ -30,7 +29,6 @@ import com.azure.core.util.CoreUtils; import java.net.URI; -import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -56,8 +54,6 @@ public class ClientModelUtil { public static final String MULTI_PART_FORM_DATA_HELPER_CLASS_NAME = "MultipartFormDataHelper"; public static final String GENERIC_MULTI_PART_FORM_DATA_HELPER_CLASS_NAME = "GenericMultipartFormDataHelper"; - public static final String CORE_TO_CODEGEN_BRIDGE_UTILS_CLASS_NAME = "CoreToCodegenBridgeUtils"; - private static final Pattern SPACE = Pattern.compile("\\s"); private static final Pattern SPLIT_FLATTEN_PROPERTY_PATTERN = Pattern.compile("((? - * At this time it is required if {@link JavaSettings#isStreamStyleSerialization()} is true and the model uses - * either {@code ResponseError} or {@link Duration} as both types have special serialization requirements that - * aren't exposed by azure-core. - * - * @param model the model - * @param settings Java settings - * @return Whether to generate the {@code CoreToCodegenBridgeUtils} utility class. - */ - public static boolean generateCoreToCodegenBridgeUtils(ClientModel model, JavaSettings settings) { - if (!settings.isStreamStyleSerialization()) { - return false; - } - - // If any of the properties are ResponseError generate the bridge utils. - // Or if any of the properties are Duration or contain Duration as a generic generate the bridge utils. - if (model.getProperties().stream().anyMatch(p -> p.getClientType() == ClassType.RESPONSE_ERROR - || p.getClientType() == ClassType.DURATION || p.getClientType().contains(ClassType.DURATION))) { - return true; - } - - // flatten properties - if (settings.getClientFlattenAnnotationTarget() == JavaSettings.ClientFlattenAnnotationTarget.NONE) { - return model.getPropertyReferences().stream() - .filter(ClientModelPropertyReference::isFromFlattenedProperty) - .anyMatch(p -> p.getClientType() == ClassType.RESPONSE_ERROR || p.getClientType() == ClassType.DURATION); - } - - for (ClientModelPropertyReference p : model.getPropertyReferences()) { - if (p.isFromFlattenedProperty() && - (p.getClientType() == ClassType.RESPONSE_ERROR || p.getClientType() == ClassType.DURATION)) { - return true; - } - } - - return false; - } - /** * Gets a mapping of XML namespace to constant name for XML namespaces used in the model. * diff --git a/javagen/src/main/resources/CoreToCodegenBridgeUtils.java b/javagen/src/main/resources/CoreToCodegenBridgeUtils.java deleted file mode 100644 index b7ed8cb6fd..0000000000 --- a/javagen/src/main/resources/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,187 +0,0 @@ -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/protocol-tests/src/main/java/fixtures/bodycomplex/implementation/CoreToCodegenBridgeUtils.java b/protocol-tests/src/main/java/fixtures/bodycomplex/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 3c4d3fd742..0000000000 --- a/protocol-tests/src/main/java/fixtures/bodycomplex/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package fixtures.bodycomplex.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/protocol-tests/src/main/java/fixtures/header/implementation/CoreToCodegenBridgeUtils.java b/protocol-tests/src/main/java/fixtures/header/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index d2fd12f9d2..0000000000 --- a/protocol-tests/src/main/java/fixtures/header/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package fixtures.header.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-extension/src/main/java/com/azure/autorest/TypeSpecPlugin.java b/typespec-extension/src/main/java/com/azure/autorest/TypeSpecPlugin.java index f8368ed4c0..3c54e1d2e3 100644 --- a/typespec-extension/src/main/java/com/azure/autorest/TypeSpecPlugin.java +++ b/typespec-extension/src/main/java/com/azure/autorest/TypeSpecPlugin.java @@ -132,21 +132,6 @@ protected void writeClientModels(Client client, JavaPackage javaPackage, JavaSet @Override protected void writeHelperClasses(Client client, JavaPackage javaPackage, JavaSettings settings) { - // While azure-core's ResponseError hasn't shipped implementing JsonSerializable add a utility method that - // will serialize and deserialize ResponseError. - if (settings.isStreamStyleSerialization()) { - boolean generateCoreToCodegenBridgeUtils = false; - for (ClientModel model : client.getModels()) { - if (ClientModelUtil.generateCoreToCodegenBridgeUtils(model, settings) && ModelUtil.isGeneratingModel(model)) { - generateCoreToCodegenBridgeUtils = true; - break; - } - } - if (generateCoreToCodegenBridgeUtils) { - javaPackage.addJavaFromResources(settings.getPackage(settings.getImplementationSubpackage()), ClientModelUtil.CORE_TO_CODEGEN_BRIDGE_UTILS_CLASS_NAME); - } - } - // JsonMergePatchHelper List jsonMergePatchModels = client.getModels().stream() .filter(ModelUtil::isGeneratingModel) diff --git a/typespec-tests/src/main/java/com/_specs_/azure/core/lro/rpc/legacy/implementation/CoreToCodegenBridgeUtils.java b/typespec-tests/src/main/java/com/_specs_/azure/core/lro/rpc/legacy/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 613d809a7a..0000000000 --- a/typespec-tests/src/main/java/com/_specs_/azure/core/lro/rpc/legacy/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com._specs_.azure.core.lro.rpc.legacy.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-tests/src/main/java/com/_specs_/azure/core/lro/rpc/legacy/models/ErrorResponse.java b/typespec-tests/src/main/java/com/_specs_/azure/core/lro/rpc/legacy/models/ErrorResponse.java index 3b91f97550..7c53615757 100644 --- a/typespec-tests/src/main/java/com/_specs_/azure/core/lro/rpc/legacy/models/ErrorResponse.java +++ b/typespec-tests/src/main/java/com/_specs_/azure/core/lro/rpc/legacy/models/ErrorResponse.java @@ -4,7 +4,6 @@ package com._specs_.azure.core.lro.rpc.legacy.models; -import com._specs_.azure.core.lro.rpc.legacy.implementation.CoreToCodegenBridgeUtils; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; import com.azure.core.models.ResponseError; @@ -52,8 +51,7 @@ public ResponseError getError() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeFieldName("error"); - CoreToCodegenBridgeUtils.responseErrorToJson(jsonWriter, this.error); + jsonWriter.writeJsonField("error", this.error); return jsonWriter.writeEndObject(); } @@ -74,7 +72,7 @@ public static ErrorResponse fromJson(JsonReader jsonReader) throws IOException { reader.nextToken(); if ("error".equals(fieldName)) { - error = CoreToCodegenBridgeUtils.responseErrorFromJson(reader); + error = ResponseError.fromJson(reader); } else { reader.skipChildren(); } diff --git a/typespec-tests/src/main/java/com/cadl/builtin/implementation/CoreToCodegenBridgeUtils.java b/typespec-tests/src/main/java/com/cadl/builtin/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 7dcbd45e38..0000000000 --- a/typespec-tests/src/main/java/com/cadl/builtin/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.cadl.builtin.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-tests/src/main/java/com/cadl/builtin/models/Builtin.java b/typespec-tests/src/main/java/com/cadl/builtin/models/Builtin.java index a29d1288d6..538fdbc914 100644 --- a/typespec-tests/src/main/java/com/cadl/builtin/models/Builtin.java +++ b/typespec-tests/src/main/java/com/cadl/builtin/models/Builtin.java @@ -11,7 +11,6 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.cadl.builtin.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.math.BigDecimal; import java.time.Duration; @@ -360,7 +359,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeLongField("long", this.longProperty); jsonWriter.writeDoubleField("float", this.floatProperty); jsonWriter.writeDoubleField("double", this.doubleProperty); - jsonWriter.writeStringField("duration", CoreToCodegenBridgeUtils.durationToStringWithDays(this.duration)); + jsonWriter.writeStringField("duration", CoreUtils.durationToStringWithDays(this.duration)); jsonWriter.writeStringField("date", Objects.toString(this.date, null)); jsonWriter.writeStringField("dateTime", this.dateTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.dateTime)); diff --git a/typespec-tests/src/main/java/com/cadl/errormodel/implementation/CoreToCodegenBridgeUtils.java b/typespec-tests/src/main/java/com/cadl/errormodel/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index b350c5ba8c..0000000000 --- a/typespec-tests/src/main/java/com/cadl/errormodel/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.cadl.errormodel.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-tests/src/main/java/com/cadl/errormodel/models/Diagnostic.java b/typespec-tests/src/main/java/com/cadl/errormodel/models/Diagnostic.java index ef43554633..f26e244633 100644 --- a/typespec-tests/src/main/java/com/cadl/errormodel/models/Diagnostic.java +++ b/typespec-tests/src/main/java/com/cadl/errormodel/models/Diagnostic.java @@ -11,7 +11,6 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.cadl.errormodel.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; /** @@ -71,8 +70,7 @@ public ResponseError getError() { public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", this.name); - jsonWriter.writeFieldName("error"); - CoreToCodegenBridgeUtils.responseErrorToJson(jsonWriter, this.error); + jsonWriter.writeJsonField("error", this.error); return jsonWriter.writeEndObject(); } @@ -96,7 +94,7 @@ public static Diagnostic fromJson(JsonReader jsonReader) throws IOException { if ("name".equals(fieldName)) { name = reader.getString(); } else if ("error".equals(fieldName)) { - error = CoreToCodegenBridgeUtils.responseErrorFromJson(reader); + error = ResponseError.fromJson(reader); } else { reader.skipChildren(); } diff --git a/typespec-tests/src/main/java/com/cadl/longrunning/implementation/CoreToCodegenBridgeUtils.java b/typespec-tests/src/main/java/com/cadl/longrunning/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index c9bac7cf1f..0000000000 --- a/typespec-tests/src/main/java/com/cadl/longrunning/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.cadl.longrunning.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-tests/src/main/java/com/cadl/longrunning/models/JobResult.java b/typespec-tests/src/main/java/com/cadl/longrunning/models/JobResult.java index 43ad82eb86..ee7efd8767 100644 --- a/typespec-tests/src/main/java/com/cadl/longrunning/models/JobResult.java +++ b/typespec-tests/src/main/java/com/cadl/longrunning/models/JobResult.java @@ -11,7 +11,6 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.cadl.longrunning.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.OffsetDateTime; @@ -146,8 +145,7 @@ public JobResultResult getResult() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeFieldName("error"); - CoreToCodegenBridgeUtils.responseErrorToJson(jsonWriter, this.error); + jsonWriter.writeJsonField("error", this.error); jsonWriter.writeJsonField("result", this.result); return jsonWriter.writeEndObject(); } @@ -188,7 +186,7 @@ public static JobResult fromJson(JsonReader jsonReader) throws IOException { lastUpdateDateTime = reader.getNullable(nonNullReader -> OffsetDateTime.parse(nonNullReader.getString())); } else if ("error".equals(fieldName)) { - error = CoreToCodegenBridgeUtils.responseErrorFromJson(reader); + error = ResponseError.fromJson(reader); } else if ("result".equals(fieldName)) { result = JobResultResult.fromJson(reader); } else { diff --git a/typespec-tests/src/main/java/com/cadl/optional/implementation/CoreToCodegenBridgeUtils.java b/typespec-tests/src/main/java/com/cadl/optional/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 30c23ea5bc..0000000000 --- a/typespec-tests/src/main/java/com/cadl/optional/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.cadl.optional.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-tests/src/main/java/com/cadl/optional/models/AllPropertiesOptional.java b/typespec-tests/src/main/java/com/cadl/optional/models/AllPropertiesOptional.java index 329795f9fb..c7ce427ff1 100644 --- a/typespec-tests/src/main/java/com/cadl/optional/models/AllPropertiesOptional.java +++ b/typespec-tests/src/main/java/com/cadl/optional/models/AllPropertiesOptional.java @@ -11,7 +11,6 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.cadl.optional.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; import java.time.OffsetDateTime; @@ -339,7 +338,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNumberField("long", this.longProperty); jsonWriter.writeNumberField("float", this.floatProperty); jsonWriter.writeNumberField("double", this.doubleProperty); - jsonWriter.writeStringField("duration", CoreToCodegenBridgeUtils.durationToStringWithDays(this.duration)); + jsonWriter.writeStringField("duration", CoreUtils.durationToStringWithDays(this.duration)); jsonWriter.writeStringField("dateTime", this.dateTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.dateTime)); jsonWriter.writeArrayField("stringList", this.stringList, (writer, element) -> writer.writeString(element)); diff --git a/typespec-tests/src/main/java/com/cadl/optional/models/Optional.java b/typespec-tests/src/main/java/com/cadl/optional/models/Optional.java index 31992f274d..5ea016e9cd 100644 --- a/typespec-tests/src/main/java/com/cadl/optional/models/Optional.java +++ b/typespec-tests/src/main/java/com/cadl/optional/models/Optional.java @@ -11,7 +11,6 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.cadl.optional.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; import java.time.OffsetDateTime; @@ -489,7 +488,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNumberField("long", this.longProperty); jsonWriter.writeNumberField("float", this.floatProperty); jsonWriter.writeNumberField("double", this.doubleProperty); - jsonWriter.writeStringField("duration", CoreToCodegenBridgeUtils.durationToStringWithDays(this.duration)); + jsonWriter.writeStringField("duration", CoreUtils.durationToStringWithDays(this.duration)); jsonWriter.writeStringField("dateTime", this.dateTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.dateTime)); jsonWriter.writeArrayField("stringList", this.stringList, (writer, element) -> writer.writeString(element)); diff --git a/typespec-tests/src/main/java/com/cadl/response/implementation/CoreToCodegenBridgeUtils.java b/typespec-tests/src/main/java/com/cadl/response/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 444a7e7e83..0000000000 --- a/typespec-tests/src/main/java/com/cadl/response/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.cadl.response.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-tests/src/main/java/com/cadl/response/models/OperationDetails1.java b/typespec-tests/src/main/java/com/cadl/response/models/OperationDetails1.java index eeb963ce67..2d4c606d18 100644 --- a/typespec-tests/src/main/java/com/cadl/response/models/OperationDetails1.java +++ b/typespec-tests/src/main/java/com/cadl/response/models/OperationDetails1.java @@ -11,7 +11,6 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.cadl.response.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; /** @@ -104,8 +103,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("operationId", this.operationId); jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); - jsonWriter.writeFieldName("error"); - CoreToCodegenBridgeUtils.responseErrorToJson(jsonWriter, this.error); + jsonWriter.writeJsonField("error", this.error); jsonWriter.writeJsonField("result", this.result); return jsonWriter.writeEndObject(); } @@ -134,7 +132,7 @@ public static OperationDetails1 fromJson(JsonReader jsonReader) throws IOExcepti } else if ("status".equals(fieldName)) { status = OperationState.fromString(reader.getString()); } else if ("error".equals(fieldName)) { - error = CoreToCodegenBridgeUtils.responseErrorFromJson(reader); + error = ResponseError.fromJson(reader); } else if ("result".equals(fieldName)) { result = Resource.fromJson(reader); } else { diff --git a/typespec-tests/src/main/java/com/cadl/response/models/OperationDetails2.java b/typespec-tests/src/main/java/com/cadl/response/models/OperationDetails2.java index a3d2c512e5..3e414adaa8 100644 --- a/typespec-tests/src/main/java/com/cadl/response/models/OperationDetails2.java +++ b/typespec-tests/src/main/java/com/cadl/response/models/OperationDetails2.java @@ -11,7 +11,6 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.cadl.response.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; /** @@ -104,8 +103,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("id", this.id); jsonWriter.writeStringField("status", this.status == null ? null : this.status.toString()); - jsonWriter.writeFieldName("error"); - CoreToCodegenBridgeUtils.responseErrorToJson(jsonWriter, this.error); + jsonWriter.writeJsonField("error", this.error); jsonWriter.writeJsonField("lroResult", this.lroResult); return jsonWriter.writeEndObject(); } @@ -134,7 +132,7 @@ public static OperationDetails2 fromJson(JsonReader jsonReader) throws IOExcepti } else if ("status".equals(fieldName)) { status = OperationState.fromString(reader.getString()); } else if ("error".equals(fieldName)) { - error = CoreToCodegenBridgeUtils.responseErrorFromJson(reader); + error = ResponseError.fromJson(reader); } else if ("lroResult".equals(fieldName)) { lroResult = Resource.fromJson(reader); } else { diff --git a/typespec-tests/src/main/java/com/encode/duration/implementation/CoreToCodegenBridgeUtils.java b/typespec-tests/src/main/java/com/encode/duration/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 38ea9a3bac..0000000000 --- a/typespec-tests/src/main/java/com/encode/duration/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.encode.duration.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-tests/src/main/java/com/encode/duration/models/DefaultDurationProperty.java b/typespec-tests/src/main/java/com/encode/duration/models/DefaultDurationProperty.java index e8032d5e26..17f2bc598a 100644 --- a/typespec-tests/src/main/java/com/encode/duration/models/DefaultDurationProperty.java +++ b/typespec-tests/src/main/java/com/encode/duration/models/DefaultDurationProperty.java @@ -6,11 +6,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.encode.duration.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; @@ -52,7 +52,7 @@ public Duration getValue() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", CoreToCodegenBridgeUtils.durationToStringWithDays(this.value)); + jsonWriter.writeStringField("value", CoreUtils.durationToStringWithDays(this.value)); return jsonWriter.writeEndObject(); } diff --git a/typespec-tests/src/main/java/com/encode/duration/models/ISO8601DurationProperty.java b/typespec-tests/src/main/java/com/encode/duration/models/ISO8601DurationProperty.java index 854cdacf30..baab8692a8 100644 --- a/typespec-tests/src/main/java/com/encode/duration/models/ISO8601DurationProperty.java +++ b/typespec-tests/src/main/java/com/encode/duration/models/ISO8601DurationProperty.java @@ -6,11 +6,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.encode.duration.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; @@ -52,7 +52,7 @@ public Duration getValue() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("value", CoreToCodegenBridgeUtils.durationToStringWithDays(this.value)); + jsonWriter.writeStringField("value", CoreUtils.durationToStringWithDays(this.value)); return jsonWriter.writeEndObject(); } diff --git a/typespec-tests/src/main/java/com/type/property/nullable/implementation/CoreToCodegenBridgeUtils.java b/typespec-tests/src/main/java/com/type/property/nullable/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 1e84a3aeab..0000000000 --- a/typespec-tests/src/main/java/com/type/property/nullable/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.type.property.nullable.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-tests/src/main/java/com/type/property/nullable/models/DurationProperty.java b/typespec-tests/src/main/java/com/type/property/nullable/models/DurationProperty.java index f1fbc3a1eb..a7baf86ab2 100644 --- a/typespec-tests/src/main/java/com/type/property/nullable/models/DurationProperty.java +++ b/typespec-tests/src/main/java/com/type/property/nullable/models/DurationProperty.java @@ -6,11 +6,11 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.type.property.nullable.implementation.CoreToCodegenBridgeUtils; import com.type.property.nullable.implementation.JsonMergePatchHelper; import java.io.IOException; import java.time.Duration; @@ -121,8 +121,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } else { jsonWriter.writeStartObject(); jsonWriter.writeStringField("requiredProperty", this.requiredProperty); - jsonWriter.writeStringField("nullableProperty", - CoreToCodegenBridgeUtils.durationToStringWithDays(this.nullableProperty)); + jsonWriter.writeStringField("nullableProperty", CoreUtils.durationToStringWithDays(this.nullableProperty)); return jsonWriter.writeEndObject(); } } @@ -142,7 +141,7 @@ private JsonWriter toJsonMergePatch(JsonWriter jsonWriter) throws IOException { jsonWriter.writeNullField("nullableProperty"); } else { jsonWriter.writeStringField("nullableProperty", - CoreToCodegenBridgeUtils.durationToStringWithDays(this.nullableProperty)); + CoreUtils.durationToStringWithDays(this.nullableProperty)); } } return jsonWriter.writeEndObject(); diff --git a/typespec-tests/src/main/java/com/type/property/optional/implementation/CoreToCodegenBridgeUtils.java b/typespec-tests/src/main/java/com/type/property/optional/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 41dc2dd03d..0000000000 --- a/typespec-tests/src/main/java/com/type/property/optional/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.type.property.optional.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-tests/src/main/java/com/type/property/optional/models/DurationProperty.java b/typespec-tests/src/main/java/com/type/property/optional/models/DurationProperty.java index 891a30ff8f..9ecdd11a31 100644 --- a/typespec-tests/src/main/java/com/type/property/optional/models/DurationProperty.java +++ b/typespec-tests/src/main/java/com/type/property/optional/models/DurationProperty.java @@ -6,11 +6,11 @@ import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.type.property.optional.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; @@ -61,7 +61,7 @@ public DurationProperty setProperty(Duration property) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("property", CoreToCodegenBridgeUtils.durationToStringWithDays(this.property)); + jsonWriter.writeStringField("property", CoreUtils.durationToStringWithDays(this.property)); return jsonWriter.writeEndObject(); } diff --git a/typespec-tests/src/main/java/com/type/property/valuetypes/implementation/CoreToCodegenBridgeUtils.java b/typespec-tests/src/main/java/com/type/property/valuetypes/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 1de50c4714..0000000000 --- a/typespec-tests/src/main/java/com/type/property/valuetypes/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) TypeSpec Code Generator. - -package com.type.property.valuetypes.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/typespec-tests/src/main/java/com/type/property/valuetypes/models/DurationProperty.java b/typespec-tests/src/main/java/com/type/property/valuetypes/models/DurationProperty.java index 7f9a4d68d3..056d7cbe35 100644 --- a/typespec-tests/src/main/java/com/type/property/valuetypes/models/DurationProperty.java +++ b/typespec-tests/src/main/java/com/type/property/valuetypes/models/DurationProperty.java @@ -6,11 +6,11 @@ import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import com.type.property.valuetypes.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; @@ -52,7 +52,7 @@ public Duration getProperty() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("property", CoreToCodegenBridgeUtils.durationToStringWithDays(this.property)); + jsonWriter.writeStringField("property", CoreUtils.durationToStringWithDays(this.property)); return jsonWriter.writeEndObject(); } diff --git a/vanilla-tests/src/main/java/fixtures/bodycomplex/implementation/CoreToCodegenBridgeUtils.java b/vanilla-tests/src/main/java/fixtures/bodycomplex/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 3c4d3fd742..0000000000 --- a/vanilla-tests/src/main/java/fixtures/bodycomplex/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package fixtures.bodycomplex.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/vanilla-tests/src/main/java/fixtures/bodycomplex/models/DurationWrapper.java b/vanilla-tests/src/main/java/fixtures/bodycomplex/models/DurationWrapper.java index 8056c8b8a3..b96d3aa57a 100644 --- a/vanilla-tests/src/main/java/fixtures/bodycomplex/models/DurationWrapper.java +++ b/vanilla-tests/src/main/java/fixtures/bodycomplex/models/DurationWrapper.java @@ -5,11 +5,11 @@ package fixtures.bodycomplex.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import fixtures.bodycomplex.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; @@ -63,7 +63,7 @@ public void validate() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("field", CoreToCodegenBridgeUtils.durationToStringWithDays(this.field)); + jsonWriter.writeStringField("field", CoreUtils.durationToStringWithDays(this.field)); return jsonWriter.writeEndObject(); } diff --git a/vanilla-tests/src/main/java/fixtures/header/implementation/CoreToCodegenBridgeUtils.java b/vanilla-tests/src/main/java/fixtures/header/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index d2fd12f9d2..0000000000 --- a/vanilla-tests/src/main/java/fixtures/header/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package fixtures.header.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/vanilla-tests/src/main/java/fixtures/nonamedresponsetypes/implementation/CoreToCodegenBridgeUtils.java b/vanilla-tests/src/main/java/fixtures/nonamedresponsetypes/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 888f0cd05a..0000000000 --- a/vanilla-tests/src/main/java/fixtures/nonamedresponsetypes/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package fixtures.nonamedresponsetypes.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/vanilla-tests/src/main/java/fixtures/streamstyleserialization/implementation/CoreToCodegenBridgeUtils.java b/vanilla-tests/src/main/java/fixtures/streamstyleserialization/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 5be31fd623..0000000000 --- a/vanilla-tests/src/main/java/fixtures/streamstyleserialization/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package fixtures.streamstyleserialization.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/vanilla-tests/src/main/java/fixtures/streamstyleserialization/models/DurationWrapper.java b/vanilla-tests/src/main/java/fixtures/streamstyleserialization/models/DurationWrapper.java index 412912ea72..41f17c5d1c 100644 --- a/vanilla-tests/src/main/java/fixtures/streamstyleserialization/models/DurationWrapper.java +++ b/vanilla-tests/src/main/java/fixtures/streamstyleserialization/models/DurationWrapper.java @@ -5,11 +5,11 @@ package fixtures.streamstyleserialization.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import fixtures.streamstyleserialization.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; @@ -63,7 +63,7 @@ public void validate() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("field", CoreToCodegenBridgeUtils.durationToStringWithDays(this.field)); + jsonWriter.writeStringField("field", CoreUtils.durationToStringWithDays(this.field)); return jsonWriter.writeEndObject(); } diff --git a/vanilla-tests/src/main/java/fixtures/streamstyleserializationctorargs/implementation/CoreToCodegenBridgeUtils.java b/vanilla-tests/src/main/java/fixtures/streamstyleserializationctorargs/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index 530c2ef6a8..0000000000 --- a/vanilla-tests/src/main/java/fixtures/streamstyleserializationctorargs/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package fixtures.streamstyleserializationctorargs.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/vanilla-tests/src/main/java/fixtures/streamstyleserializationctorargs/models/DurationWrapper.java b/vanilla-tests/src/main/java/fixtures/streamstyleserializationctorargs/models/DurationWrapper.java index 63f1a98194..13b53ad9af 100644 --- a/vanilla-tests/src/main/java/fixtures/streamstyleserializationctorargs/models/DurationWrapper.java +++ b/vanilla-tests/src/main/java/fixtures/streamstyleserializationctorargs/models/DurationWrapper.java @@ -5,11 +5,11 @@ package fixtures.streamstyleserializationctorargs.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import fixtures.streamstyleserializationctorargs.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; @@ -63,7 +63,7 @@ public void validate() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("field", CoreToCodegenBridgeUtils.durationToStringWithDays(this.field)); + jsonWriter.writeStringField("field", CoreUtils.durationToStringWithDays(this.field)); return jsonWriter.writeEndObject(); } diff --git a/vanilla-tests/src/main/java/fixtures/streamstyleserializationimmutableoutput/implementation/CoreToCodegenBridgeUtils.java b/vanilla-tests/src/main/java/fixtures/streamstyleserializationimmutableoutput/implementation/CoreToCodegenBridgeUtils.java deleted file mode 100644 index dbff8a7bfb..0000000000 --- a/vanilla-tests/src/main/java/fixtures/streamstyleserializationimmutableoutput/implementation/CoreToCodegenBridgeUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// Code generated by Microsoft (R) AutoRest Code Generator. - -package fixtures.streamstyleserializationimmutableoutput.implementation; - -import com.azure.core.models.ResponseError; -import com.azure.json.JsonReader; -import com.azure.json.JsonToken; -import com.azure.json.JsonWriter; - -import java.io.IOException; -import java.time.Duration; - -/** - * Utility class that handles functionality not yet available in azure-core that generated code requires. - */ -public final class CoreToCodegenBridgeUtils { - /** - * Writes the object to the passed {@link ResponseError}. - * - * @param jsonWriter Where the {@link ResponseError} JSON will be written. - * @return The {@link JsonWriter} where the JSON was written. - * @throws IOException If the {@link ResponseError} fails to be written to the {@code jsonWriter}. - */ - public static JsonWriter responseErrorToJson(JsonWriter jsonWriter, ResponseError responseError) - throws IOException { - return jsonWriter.writeStartObject() - .writeStringField("code", responseError.getCode()) - .writeStringField("message", responseError.getMessage()) - .writeEndObject(); - } - - /** - * Reads a JSON stream into a {@link ResponseError}. - * - * @param jsonReader The {@link JsonReader} being read. - * @return The {@link ResponseError} that the JSON stream represented, or null if it pointed to JSON null. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If a {@link ResponseError} fails to be read from the {@code jsonReader}. - */ - public static ResponseError responseErrorFromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - // Buffer the next JSON object as ResponseError can take two forms: - // - // - A ResponseError object - // - A ResponseError object wrapped in an "error" node. - JsonReader bufferedReader = reader.bufferObject(); - bufferedReader.nextToken(); // Get to the START_OBJECT token. - while (bufferedReader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = bufferedReader.getFieldName(); - bufferedReader.nextToken(); - - if ("error".equals(fieldName)) { - // If the ResponseError was wrapped in the "error" node begin reading it now. - return readResponseError(bufferedReader); - } else { - bufferedReader.skipChildren(); - } - } - - // Otherwise reset the JsonReader and read the whole JSON object. - return readResponseError(bufferedReader.reset()); - }); - } - - private static ResponseError readResponseError(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String code = null; - boolean codeFound = false; - String message = null; - boolean messageFound = false; - - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("code".equals(fieldName)) { - code = reader.getString(); - codeFound = true; - } else if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; - } else { - reader.skipChildren(); - } - } - - if (!codeFound && !messageFound) { - throw new IllegalStateException("Missing required properties: code, message"); - } else if (!codeFound) { - throw new IllegalStateException("Missing required property: code"); - } else if (!messageFound) { - throw new IllegalStateException("Missing required property: message"); - } - - return new ResponseError(code, message); - }); - } - - /** - * Converts a {@link Duration} to a string in ISO-8601 format with support for a day component. - * - * @param duration The {@link Duration} to convert. - * @return The {@link Duration} as a string in ISO-8601 format with support for a day component, or null if the - * provided {@link Duration} was null. - */ - public static String durationToStringWithDays(Duration duration) { - if (duration == null) { - return null; - } - - if (duration.isZero()) { - return "PT0S"; - } - - StringBuilder builder = new StringBuilder(); - - if (duration.isNegative()) { - builder.append("-P"); - duration = duration.negated(); - } else { - builder.append('P'); - } - - long days = duration.toDays(); - if (days > 0) { - builder.append(days); - builder.append('D'); - duration = duration.minusDays(days); - } - - long hours = duration.toHours(); - if (hours > 0) { - builder.append('T'); - builder.append(hours); - builder.append('H'); - duration = duration.minusHours(hours); - } - - final long minutes = duration.toMinutes(); - if (minutes > 0) { - if (hours == 0) { - builder.append('T'); - } - - builder.append(minutes); - builder.append('M'); - duration = duration.minusMinutes(minutes); - } - - final long seconds = duration.getSeconds(); - if (seconds > 0) { - if (hours == 0 && minutes == 0) { - builder.append('T'); - } - - builder.append(seconds); - duration = duration.minusSeconds(seconds); - } - - long milliseconds = duration.toMillis(); - if (milliseconds > 0) { - if (hours == 0 && minutes == 0 && seconds == 0) { - builder.append("T"); - } - - if (seconds == 0) { - builder.append("0"); - } - - builder.append('.'); - - if (milliseconds <= 99) { - builder.append('0'); - - if (milliseconds <= 9) { - builder.append('0'); - } - } - - // Remove trailing zeros. - while (milliseconds % 10 == 0) { - milliseconds /= 10; - } - builder.append(milliseconds); - } - - if (seconds > 0 || milliseconds > 0) { - builder.append('S'); - } - - return builder.toString(); - } -} diff --git a/vanilla-tests/src/main/java/fixtures/streamstyleserializationimmutableoutput/models/DurationWrapper.java b/vanilla-tests/src/main/java/fixtures/streamstyleserializationimmutableoutput/models/DurationWrapper.java index e978acf66b..5ee3998a4d 100644 --- a/vanilla-tests/src/main/java/fixtures/streamstyleserializationimmutableoutput/models/DurationWrapper.java +++ b/vanilla-tests/src/main/java/fixtures/streamstyleserializationimmutableoutput/models/DurationWrapper.java @@ -5,11 +5,11 @@ package fixtures.streamstyleserializationimmutableoutput.models; import com.azure.core.annotation.Fluent; +import com.azure.core.util.CoreUtils; import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; -import fixtures.streamstyleserializationimmutableoutput.implementation.CoreToCodegenBridgeUtils; import java.io.IOException; import java.time.Duration; @@ -63,7 +63,7 @@ public void validate() { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("field", CoreToCodegenBridgeUtils.durationToStringWithDays(this.field)); + jsonWriter.writeStringField("field", CoreUtils.durationToStringWithDays(this.field)); return jsonWriter.writeEndObject(); }