From 25b7e150ce94c7c62b838786181ba0a4a70fc5c9 Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Thu, 10 Sep 2020 10:59:34 -0700 Subject: [PATCH] Prepare Schema Registry for preview (#15001) * Schema registry changes with new APIs Co-authored-by: Arthur Erlendsson <30675661+arerlend@users.noreply.github.com> Co-authored-by: Mitch Denny --- .../checkstyle/checkstyle-suppressions.xml | 3 +- .../CHANGELOG.md | 8 +- .../azure-data-schemaregistry-avro/pom.xml | 28 + .../schemaregistry/avro/AvroByteDecoder.java | 86 - .../schemaregistry/avro/AvroByteEncoder.java | 82 - .../data/schemaregistry/avro/AvroCodec.java | 26 - .../avro/AvroSchemaRegistryUtils.java | 153 ++ .../SchemaRegistryAvroAsyncDeserializer.java | 43 - .../SchemaRegistryAvroAsyncSerializer.java | 48 - .../avro/SchemaRegistryAvroDeserializer.java | 39 - ...SchemaRegistryAvroDeserializerBuilder.java | 112 - .../avro/SchemaRegistryAvroSerializer.java | 166 +- .../SchemaRegistryAvroSerializerBuilder.java | 89 +- .../src/samples/README.md | 46 + ...chemaRegistryAvroDeserilizationSample.java | 61 + ...SchemaRegistryAvroSerializationSample.java | 53 + .../generatedtestsources/HandOfCards.java | 354 +++ .../generatedtestsources/PlayingCard.java | 469 ++++ .../generatedtestsources/PlayingCardSuit.java | 13 + .../samples/resources/avro/HandOfCards.avro | 29 + .../avro/AvroByteDecoderTest.java | 15 - .../avro/AvroByteEncoderTest.java | 22 - .../azure-data-schemaregistry/CHANGELOG.md | 6 +- .../azure-data-schemaregistry/README.md | 192 +- .../azure-data-schemaregistry/pom.xml | 6 + .../AbstractDataDeserializer.java | 126 -- .../schemaregistry/AbstractDataSerDe.java | 39 - .../AbstractDataSerializer.java | 130 -- .../data/schemaregistry/ByteDecoder.java | 18 - .../data/schemaregistry/ByteEncoder.java | 40 - .../com/azure/data/schemaregistry/Codec.java | 24 - .../SchemaRegistryAsyncClient.java | 314 +++ .../schemaregistry/SchemaRegistryClient.java | 117 + ....java => SchemaRegistryClientBuilder.java} | 127 +- .../SerializationException.java | 26 - .../client/CachedSchemaRegistryClient.java | 295 --- .../client/SchemaRegistryClient.java | 100 - .../client/SchemaRegistryClientException.java | 26 - .../client/SchemaRegistryObject.java | 78 - .../AzureSchemaRegistryRestService.java | 1922 ----------------- ...chemaRegistryRestServiceClientBuilder.java | 67 - .../models/CreateGroupHeaders.java | 44 - .../models/CreateGroupResponse.java | 25 - .../models/CreateSchemaResponse.java | 31 - .../models/GetIdBySchemaContentHeaders.java | 149 -- .../models/GetLatestSchemaResponse.java | 31 - .../models/GetSchemaVersionHeaders.java | 149 -- .../models/GetSchemaVersionsHeaders.java | 44 - .../models/GetSchemaVersionsResponse.java | 36 - .../models/GetSchemasByGroupHeaders.java | 44 - .../models/GetSchemasByGroupResponse.java | 36 - .../implementation/models/SchemaGroup.java | 176 -- .../implementation/models/package-info.java | 2 - .../client/implementation/package-info.java | 2 - .../schemaregistry/client/package-info.java | 7 - .../implementation/AzureSchemaRegistry.java | 108 + .../AzureSchemaRegistryBuilder.java | 210 ++ .../implementation/Schemas.java | 338 +++ .../implementation/models/SchemaId.java | 10 +- .../models/SchemasGetByIdHeaders.java} | 33 +- .../models/SchemasGetByIdResponse.java} | 14 +- .../SchemasQueryIdByContentHeaders.java} | 33 +- .../SchemasQueryIdByContentResponse.java} | 18 +- .../models/SchemasRegisterHeaders.java} | 33 +- .../models/SchemasRegisterResponse.java} | 14 +- .../models/SerializationType.java | 30 + .../models/ServiceErrorResponse.java | 44 + .../models/ServiceErrorResponseException.java | 36 + .../implementation/models/package-info.java | 8 + .../implementation/package-info.java | 8 + .../models/SchemaProperties.java | 78 + .../models/SerializationType.java | 22 + .../schemaregistry/models/package-info.java | 7 + .../data/schemaregistry/package-info.java | 5 +- .../src/main/module-info.java | 2 +- .../src/samples/README.md | 47 + .../schemaregistry/GetSchemaIdSample.java | 42 + .../data/schemaregistry/GetSchemaSample.java | 39 + .../data/schemaregistry/ReadmeSamples.java | 116 + .../schemaregistry/RegisterSchemaSample.java | 40 + .../AbstractDataDeserializerTest.java | 102 - .../AbstractDataSerializerTest.java | 104 - .../MockSchemaRegistryClient.java | 93 - .../schemaregistry/SampleByteDecoder.java | 27 - .../schemaregistry/SampleByteEncoder.java | 46 - .../SchemaRegistryAsyncClientTest.java | 272 +++ .../schemaregistry/TestDummyDeserializer.java | 14 - .../schemaregistry/TestDummySerializer.java | 35 - .../CachedSchemaRegistryClientTest.java | 233 -- 89 files changed, 3588 insertions(+), 5047 deletions(-) delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroByteDecoder.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroByteEncoder.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroCodec.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryUtils.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroAsyncDeserializer.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroAsyncSerializer.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserializer.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserializerBuilder.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/README.md create mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserilizationSample.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializationSample.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/HandOfCards.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/PlayingCard.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/PlayingCardSuit.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/resources/avro/HandOfCards.avro delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/test/java/com/azure/data/schemaregistry/avro/AvroByteDecoderTest.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/test/java/com/azure/data/schemaregistry/avro/AvroByteEncoderTest.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataDeserializer.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataSerDe.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataSerializer.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/ByteDecoder.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/ByteEncoder.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/Codec.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClient.java rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client/CachedSchemaRegistryClientBuilder.java => SchemaRegistryClientBuilder.java} (65%) delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SerializationException.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClient.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryClient.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryClientException.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryObject.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/AzureSchemaRegistryRestService.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/AzureSchemaRegistryRestServiceClientBuilder.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateGroupHeaders.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateGroupResponse.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateSchemaResponse.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetIdBySchemaContentHeaders.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetLatestSchemaResponse.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionHeaders.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionsHeaders.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionsResponse.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemasByGroupHeaders.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemasByGroupResponse.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/SchemaGroup.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/package-info.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/package-info.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/package-info.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistry.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistryBuilder.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/Schemas.java rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/SchemaId.java (67%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client/implementation/models/CreateSchemaHeaders.java => implementation/models/SchemasGetByIdHeaders.java} (77%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client/implementation/models/GetSchemaByIdResponse.java => implementation/models/SchemasGetByIdResponse.java} (63%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client/implementation/models/GetSchemaByIdHeaders.java => implementation/models/SchemasQueryIdByContentHeaders.java} (75%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client/implementation/models/GetSchemaVersionResponse.java => implementation/models/SchemasQueryIdByContentResponse.java} (58%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client/implementation/models/GetLatestSchemaHeaders.java => implementation/models/SchemasRegisterHeaders.java} (77%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client/implementation/models/GetIdBySchemaContentResponse.java => implementation/models/SchemasRegisterResponse.java} (63%) create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SerializationType.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/ServiceErrorResponse.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/ServiceErrorResponseException.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/package-info.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/package-info.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaProperties.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SerializationType.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/package-info.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/samples/README.md create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaIdSample.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaSample.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/ReadmeSamples.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/RegisterSchemaSample.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/AbstractDataDeserializerTest.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/AbstractDataSerializerTest.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/MockSchemaRegistryClient.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleByteDecoder.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleByteEncoder.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClientTest.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummyDeserializer.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummySerializer.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClientTest.java diff --git a/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml b/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml index 24f91ca6b0cf2..0a32bf228a954 100755 --- a/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml +++ b/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml @@ -416,7 +416,7 @@ - + @@ -432,6 +432,7 @@ + 4.0.0 + com.azure azure-client-sdk-parent @@ -73,6 +74,12 @@ 5.6.2 test + + com.azure + azure-identity + 1.1.2 + test + @@ -91,6 +98,27 @@ + + org.apache.avro + avro-maven-plugin + 1.9.2 + + + generate-test-sources + + schema + + + src/samples/resources/avro/ + ${project.basedir}/src/samples/java/ + + **/*.avro + + String + + + + diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroByteDecoder.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroByteDecoder.java deleted file mode 100644 index 9b38935837719..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroByteDecoder.java +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.avro; - -import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.ByteDecoder; -import com.azure.data.schemaregistry.SerializationException; -import org.apache.avro.Schema; -import org.apache.avro.generic.GenericDatumReader; -import org.apache.avro.io.DatumReader; -import org.apache.avro.io.DecoderFactory; -import org.apache.avro.specific.SpecificDatumReader; - -import java.io.IOException; -import java.util.Objects; - -/** - * Apache Avro ByteDecoder implementation with all Avro-specific functionality required to deserialize byte arrays - * given an Avro schema. - */ -public class AvroByteDecoder extends AvroCodec - implements ByteDecoder { - private final ClientLogger logger = new ClientLogger(AvroByteDecoder.class); - private static final DecoderFactory DECODER_FACTORY = DecoderFactory.get(); - private final boolean avroSpecificReader; - - /** - * Instantiates AvroByteDecoder instance - * @param avroSpecificReader flag indicating if attempting to decode as Avro SpecificRecord - */ - public AvroByteDecoder(boolean avroSpecificReader) { - this.avroSpecificReader = avroSpecificReader; - } - - /** - * @param b byte array containing encoded bytes - * @param object schema for Avro reader read - fetched from Azure Schema Registry - * @return deserialized object - * @throws SerializationException upon deserialization failure - */ - public Object decodeBytes(byte[] b, Object object) { - Objects.requireNonNull(object, "Schema must not be null."); - - if (!(object instanceof Schema)) { - throw logger.logExceptionAsError( - new SerializationException("Object must be an Avro schema.")); - } - Schema schema = (Schema) object; - - if (schema.getType().equals(Schema.Type.BYTES)) { - return b; - } - - DatumReader reader = getDatumReader(schema); - - try { - Object result = reader.read(null, DECODER_FACTORY.binaryDecoder(b, null)); - - if (schema.getType().equals(Schema.Type.STRING)) { - return result.toString(); - } - - return result; - } catch (IOException | RuntimeException e) { - // avro deserialization may throw AvroRuntimeException, NullPointerException, etc - throw logger.logExceptionAsError(new SerializationException("Error deserializing Avro message.", e)); - } - } - - /** - * Returns correct reader for decoding payload. - * - * @param writerSchema Avro schema fetched from schema registry store - * @return correct Avro DatumReader object given encoder configuration - */ - private DatumReader getDatumReader(Schema writerSchema) { - boolean writerSchemaIsPrimitive = AvroSchemaUtils.getPrimitiveSchemas().values().contains(writerSchema); - // do not use SpecificDatumReader if writerSchema is a primitive - if (avroSpecificReader && !writerSchemaIsPrimitive) { - return new SpecificDatumReader<>(writerSchema); - } else { - return new GenericDatumReader<>(writerSchema); - } - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroByteEncoder.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroByteEncoder.java deleted file mode 100644 index 266d7cd840cab..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroByteEncoder.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.avro; - -import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.ByteEncoder; -import com.azure.data.schemaregistry.SerializationException; -import org.apache.avro.Schema; -import org.apache.avro.generic.GenericDatumWriter; -import org.apache.avro.io.BinaryEncoder; -import org.apache.avro.io.DatumWriter; -import org.apache.avro.io.EncoderFactory; -import org.apache.avro.specific.SpecificDatumWriter; -import org.apache.avro.specific.SpecificRecord; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * ByteEncoder implementation with all Avro-specific functionality required to serialize Java objects into byte arrays. - */ -public class AvroByteEncoder extends AvroCodec - implements ByteEncoder { - private final ClientLogger logger = new ClientLogger(AvroByteEncoder.class); - private static final EncoderFactory ENCODER_FACTORY = EncoderFactory.get(); - - /** - * @param object Schema object used to generate schema string - * @see AvroSchemaUtils for distinction between primitive and Avro schema generation - * @return string representation of schema - */ - @Override - public String getSchemaString(Object object) { - Schema schema = AvroSchemaUtils.getSchema(object); - return schema.toString(); - } - - /** - * Returns schema name for storing schemas in schema registry store. - * - * @param object Schema object used to generate schema path - * @return schema name as string - */ - @Override - public String getSchemaName(Object object) { - return AvroSchemaUtils.getSchema(object).getFullName(); - } - - /** - * Returns ByteArrayOutputStream containing Avro encoding of object parameter - * @param object Object to be encoded into byte stream - * @return closed ByteArrayOutputStream - * @throws SerializationException wraps runtime exceptions - */ - @Override - public ByteArrayOutputStream encode(Object object) { - Schema schema = AvroSchemaUtils.getSchema(object); - - try { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - if (object instanceof byte[]) { - out.write((byte[]) object); // todo: real avro byte arrays require writing array size to buffer - } else { - BinaryEncoder encoder = ENCODER_FACTORY.directBinaryEncoder(out, null); - DatumWriter writer; - if (object instanceof SpecificRecord) { - writer = new SpecificDatumWriter<>(schema); - } else { - writer = new GenericDatumWriter<>(schema); - } - writer.write(object, encoder); - encoder.flush(); - } - return out; - } catch (IOException | RuntimeException e) { - // Avro serialization can throw AvroRuntimeException, NullPointerException, ClassCastException, etc - throw logger.logExceptionAsError( - new SerializationException("Error serializing Avro message", e)); - } - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroCodec.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroCodec.java deleted file mode 100644 index bbf70f18342c4..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroCodec.java +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.avro; - -import com.azure.data.schemaregistry.Codec; -import org.apache.avro.Schema; - -/** - * Base Codec class for Avro encoder and decoder implementations - */ -abstract class AvroCodec implements Codec { - @Override - public String schemaType() { - return "avro"; - } - - /** - * @param schemaString string representation of schema - * @return avro schema - */ - @Override - public Schema parseSchemaString(String schemaString) { - return (new Schema.Parser()).parse(schemaString); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryUtils.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryUtils.java new file mode 100644 index 0000000000000..1a5e7d5a08c03 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryUtils.java @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.avro; + +import com.azure.core.util.logging.ClientLogger; +import com.azure.data.schemaregistry.models.SerializationType; +import org.apache.avro.Schema; +import org.apache.avro.generic.GenericDatumReader; +import org.apache.avro.generic.GenericDatumWriter; +import org.apache.avro.io.BinaryEncoder; +import org.apache.avro.io.DatumReader; +import org.apache.avro.io.DatumWriter; +import org.apache.avro.io.DecoderFactory; +import org.apache.avro.io.EncoderFactory; +import org.apache.avro.specific.SpecificDatumReader; +import org.apache.avro.specific.SpecificDatumWriter; +import org.apache.avro.specific.SpecificRecord; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Objects; + +/** + * Base Codec class for Avro encoder and decoder implementations + */ +class AvroSchemaRegistryUtils { + private final ClientLogger logger = new ClientLogger(AvroSchemaRegistryUtils.class); + private static final EncoderFactory ENCODER_FACTORY = EncoderFactory.get(); + private static final DecoderFactory DECODER_FACTORY = DecoderFactory.get(); + private static final Boolean AVRO_SPECIFIC_READER_DEFAULT = false; + + private final Boolean avroSpecificReader; + + /** + * Instantiates AvroCodec instance + * @param avroSpecificReader flag indicating if decoder should decode records as SpecificRecords + */ + AvroSchemaRegistryUtils(Boolean avroSpecificReader) { + if (avroSpecificReader == null) { + this.avroSpecificReader = AvroSchemaRegistryUtils.AVRO_SPECIFIC_READER_DEFAULT; + } else { + this.avroSpecificReader = avroSpecificReader; + } + } + + SerializationType getSerializationType() { + return SerializationType.AVRO; + } + + /** + * @param schemaString string representation of schema + * @return avro schema + */ + Schema parseSchemaString(String schemaString) { + return (new Schema.Parser()).parse(schemaString); + } + + + /** + * @param object Schema object used to generate schema string + * @see AvroSchemaUtils for distinction between primitive and Avro schema generation + * @return string representation of schema + */ + String getSchemaString(Object object) { + Schema schema = AvroSchemaUtils.getSchema(object); + return schema.toString(); + } + + /** + * Returns schema name for storing schemas in schema registry store. + * + * @param object Schema object used to generate schema path + * @return schema name as string + */ + String getSchemaName(Object object) { + return AvroSchemaUtils.getSchema(object).getFullName(); + } + + String getSchemaGroup() { + return "$Default"; + } + + /** + * Returns ByteArrayOutputStream containing Avro encoding of object parameter + * @param object Object to be encoded into byte stream + * @return closed ByteArrayOutputStream + */ + byte[] encode(Object object) { + Schema schema = AvroSchemaUtils.getSchema(object); + + try { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + if (object instanceof byte[]) { + out.write((byte[]) object); // todo: real avro byte arrays require writing array size to buffer + } else { + BinaryEncoder encoder = ENCODER_FACTORY.directBinaryEncoder(out, null); + DatumWriter writer; + if (object instanceof SpecificRecord) { + writer = new SpecificDatumWriter<>(schema); + } else { + writer = new GenericDatumWriter<>(schema); + } + writer.write(object, encoder); + encoder.flush(); + } + return out.toByteArray(); + } catch (IOException | RuntimeException e) { + // Avro serialization can throw AvroRuntimeException, NullPointerException, ClassCastException, etc + throw logger.logExceptionAsError( + new IllegalStateException("Error serializing Avro message", e)); + } + } + + + /** + * @param b byte array containing encoded bytes + * @param schemaBytes schema content for Avro reader read - fetched from Azure Schema Registry + * @return deserialized object + */ + T decode(byte[] b, byte[] schemaBytes) { + Objects.requireNonNull(schemaBytes, "Schema must not be null."); + + String schemaString = new String(schemaBytes, StandardCharsets.UTF_8); + Schema schemaObject = parseSchemaString(schemaString); + + DatumReader reader = getDatumReader(schemaObject); + + try { + T result = reader.read(null, DECODER_FACTORY.binaryDecoder(b, null)); + return result; + } catch (IOException | RuntimeException e) { + throw logger.logExceptionAsError(new IllegalStateException("Error deserializing Avro message.", e)); + } + } + + /** + * Returns correct reader for decoding payload. + * + * @param writerSchema Avro schema fetched from schema registry store + * @return correct Avro DatumReader object given encoder configuration + */ + private DatumReader getDatumReader(Schema writerSchema) { + boolean writerSchemaIsPrimitive = AvroSchemaUtils.getPrimitiveSchemas().values().contains(writerSchema); + // do not use SpecificDatumReader if writerSchema is a primitive + if (avroSpecificReader && !writerSchemaIsPrimitive) { + return new SpecificDatumReader<>(writerSchema); + } else { + return new GenericDatumReader<>(writerSchema); + } + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroAsyncDeserializer.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroAsyncDeserializer.java deleted file mode 100644 index e43ab1de10f51..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroAsyncDeserializer.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.avro; - -import com.azure.data.schemaregistry.SerializationException; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; - -import java.util.concurrent.Executors; - -/** - * Asynchronous registry-based deserializer implementation. - */ -public class SchemaRegistryAvroAsyncDeserializer { - private static final int DEFAULT_THREAD_POOL_SIZE = 8; - - private final SchemaRegistryAvroDeserializer deserializer; - private final Scheduler scheduler; - - /** - * Instantiates instance of async deserializer. - * - * @param deserializer synchronous internal deserializer implementation - */ - SchemaRegistryAvroAsyncDeserializer(SchemaRegistryAvroDeserializer deserializer) { - this.deserializer = deserializer; - this.scheduler = Schedulers.fromExecutor(Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE)); - } - - /** - * Async wrapper around synchronous deserialization method - * @param data bytes containing schema ID and encoded byte representation of object - * @return Mono wrapper around deserialized object - * @throws SerializationException if deserialization operation fails - */ - public Mono deserialize(byte[] data) throws SerializationException { - return Mono - .fromCallable(() -> this.deserializer.deserialize(data)) - .subscribeOn(scheduler); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroAsyncSerializer.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroAsyncSerializer.java deleted file mode 100644 index 7d8edfb020bac..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroAsyncSerializer.java +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.avro; - -import com.azure.data.schemaregistry.AbstractDataSerializer; -import com.azure.data.schemaregistry.SerializationException; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; - -import java.util.concurrent.Executors; - -/** - * Asynchronous registry-based serializer implementation. - */ -public class SchemaRegistryAvroAsyncSerializer extends AbstractDataSerializer { - private static final int DEFAULT_THREAD_POOL_SIZE = 8; - - private final SchemaRegistryAvroSerializer serializer; - private final Scheduler scheduler; - - /** - * @param serializer synchronous Avro serializer implementation - */ - SchemaRegistryAvroAsyncSerializer(SchemaRegistryAvroSerializer serializer) { - this.serializer = serializer; - this.scheduler = Schedulers.fromExecutor(Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE)); - } - - /** - * Async wrapper around sync serialization operation - * - * @param object object to be serialized to bytes - * @return Avro byte representation of object - * @throws SerializationException upon serialization operation failure - */ - public Mono serialize(Object object) throws SerializationException { - if (object == null) { - return Mono.empty(); - } - - return Mono - .fromCallable(() -> this.serializer.serialize(object)) - .subscribeOn(scheduler); - } -} - diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserializer.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserializer.java deleted file mode 100644 index c683ebc2ec9d2..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserializer.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.avro; - -import com.azure.data.schemaregistry.AbstractDataDeserializer; -import com.azure.data.schemaregistry.SerializationException; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryClient; - -/** - * A deserializer implementation capable of automatedly deserializing encoded byte array payloads into Java objects by - * fetching payload-specified schemas from the Azure Schema Registry store. - *

- * SchemaRegistryAvroDeserializer instances should be built using the static Builder class. - *

- * Pluggable with the core Azure SDK Deserializer interface. - * - * @see AbstractDataDeserializer See AbstractDataDeserializer for internal deserialization implementation - */ -public class SchemaRegistryAvroDeserializer extends AbstractDataDeserializer { - SchemaRegistryAvroDeserializer(CachedSchemaRegistryClient registryClient, boolean avroSpecificReader) { - super(registryClient); - - loadByteDecoder(new AvroByteDecoder(avroSpecificReader)); - } - - /** - * Deserializes byte array into Java object using payload-specified schema. - * - * @param data Byte array containing serialized bytes - * @return decoded Java object - * - * @throws SerializationException Throws on deserialization failure. - * Exception may contain inner exceptions detailing failure condition. - */ - public Object deserialize(byte[] data) throws SerializationException { - return super.deserialize(data); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserializerBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserializerBuilder.java deleted file mode 100644 index a385d9bbfa748..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserializerBuilder.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.avro; - -import com.azure.core.credential.TokenCredential; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryClient; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryClientBuilder; - -import java.util.Objects; - -/** - * Builder class for constructing {@link SchemaRegistryAvroDeserializer} and {@link SchemaRegistryAvroAsyncDeserializer} - */ -public class SchemaRegistryAvroDeserializerBuilder { - - private String registryUrl; - private TokenCredential credential; - private boolean avroSpecificReader; - private Integer maxSchemaMapSize; - - /** - * Instantiates instance of Builder class. - * Supplies default avro.specific.reader value. - * - */ - public SchemaRegistryAvroDeserializerBuilder() { - this.registryUrl = null; - this.credential = null; - this.avroSpecificReader = false; - this.maxSchemaMapSize = null; - } - - /** - * Sets the service endpoint for the Azure Schema Registry instance. - * - * @return The updated {@link SchemaRegistryAvroDeserializerBuilder} object. - * @param schemaRegistryUrl The URL of the Azure Schema Registry instance - * @throws NullPointerException if {@code schemaRegistryUrl} is null - */ - public SchemaRegistryAvroDeserializerBuilder schemaRegistryUrl(String schemaRegistryUrl) { - Objects.requireNonNull(schemaRegistryUrl, "'schemaRegistryUrl' cannot be null."); - this.registryUrl = schemaRegistryUrl; - return this; - } - - /** - * - * @param credential TokenCredential to be used for authenticating with Azure Schema Registry Service - * @return updated {@link SchemaRegistryAvroDeserializerBuilder} instance - */ - public SchemaRegistryAvroDeserializerBuilder credential(TokenCredential credential) { - this.credential = credential; - return this; - } - - /** - * Specifies if objects should be deserialized into Avro SpecificRecords via Avro SpecificDatumReader - * @param avroSpecificReader specific reader flag - * @return updated {@link SchemaRegistryAvroDeserializerBuilder} instance - */ - public SchemaRegistryAvroDeserializerBuilder avroSpecificReader(boolean avroSpecificReader) { - this.avroSpecificReader = avroSpecificReader; - return this; - } - - /** - * Specifies maximum schema object cache size for underlying CachedSchemaRegistryClient. If specified cache - * size is exceeded, all caches are recycled. - * - * @param maxSchemaMapSize maximum number of schemas per cache - * @return updated {@link SchemaRegistryAvroDeserializerBuilder} instance - */ - public SchemaRegistryAvroDeserializerBuilder maxSchemaMapSize(int maxSchemaMapSize) { - this.maxSchemaMapSize = maxSchemaMapSize; - return this; - } - - /** - * Construct instance of {@link SchemaRegistryAvroAsyncDeserializer} - * - * @return {@link SchemaRegistryAvroAsyncDeserializer} instance - * - * @throws NullPointerException if parameters are incorrectly set. - * @throws IllegalArgumentException if credential is not set. - */ - public SchemaRegistryAvroAsyncDeserializer buildAsyncClient() { - return new SchemaRegistryAvroAsyncDeserializer(this.buildSyncClient()); - } - - /** - * Construct instance of {@link SchemaRegistryAvroDeserializer} - * - * @return {@link SchemaRegistryAvroDeserializer} instance - * - * @throws NullPointerException if parameters are incorrectly set. - * @throws IllegalArgumentException if credential is not set. - */ - public SchemaRegistryAvroDeserializer buildSyncClient() { - CachedSchemaRegistryClientBuilder builder = new CachedSchemaRegistryClientBuilder() - .endpoint(registryUrl) - .credential(credential); - - if (maxSchemaMapSize != null) { - builder.maxSchemaMapSize(maxSchemaMapSize); - } - - CachedSchemaRegistryClient client = builder.buildClient(); - - return new SchemaRegistryAvroDeserializer(client, this.avroSpecificReader); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializer.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializer.java index 03791b6ba2646..4017ae3dd482d 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializer.java +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializer.java @@ -3,43 +3,157 @@ package com.azure.data.schemaregistry.avro; -import com.azure.data.schemaregistry.AbstractDataSerializer; -import com.azure.data.schemaregistry.SerializationException; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryClient; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.serializer.ObjectSerializer; +import com.azure.core.util.serializer.TypeReference; +import com.azure.data.schemaregistry.SchemaRegistryAsyncClient; +import com.azure.data.schemaregistry.models.SchemaProperties; +import com.azure.data.schemaregistry.models.SerializationType; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +import static com.azure.core.util.FluxUtil.monoError; /** - * A serializer implementation capable of serializing objects and automatedly storing serialization schemas - * in the Azure Schema Registry store. - * - * SchemaRegistryAvroSerializer instances should be built using the static Builder class. - * - * Pluggable with the core Azure SDK Serializer interface. - * - * @see AbstractDataSerializer See AbstractDataSerializer for internal serialization implementation + * Schema Registry-based serializer implementation for Avro data format. */ -public class SchemaRegistryAvroSerializer extends AbstractDataSerializer { - SchemaRegistryAvroSerializer(CachedSchemaRegistryClient registryClient, - String schemaGroup, - boolean autoRegisterSchemas) { - super(registryClient); +public final class SchemaRegistryAvroSerializer implements ObjectSerializer { + private final ClientLogger logger = new ClientLogger(SchemaRegistryAvroSerializer.class); - setByteEncoder(new AvroByteEncoder()); + static final int SCHEMA_ID_SIZE = 32; + private final SchemaRegistryAsyncClient schemaRegistryClient; + private final AvroSchemaRegistryUtils codec; + private final String schemaGroup; + private final Boolean autoRegisterSchemas; - this.autoRegisterSchemas = autoRegisterSchemas; + SchemaRegistryAvroSerializer(SchemaRegistryAsyncClient registryClient, AvroSchemaRegistryUtils codec, + String schemaGroup, Boolean autoRegisterSchemas) { + this.schemaRegistryClient = registryClient; + this.codec = codec; this.schemaGroup = schemaGroup; + this.autoRegisterSchemas = autoRegisterSchemas; + } + + @Override + public T deserialize(InputStream stream, TypeReference typeReference) { + return deserializeAsync(stream, typeReference).block(); + } + + @Override + public Mono deserializeAsync(InputStream stream, + TypeReference typeReference) { + + if (stream == null) { + return Mono.empty(); + } + + return Mono.fromCallable(() -> { + byte[] payload = new byte[stream.available()]; + + while (true) { + if (stream.read(payload) == -1) { + break; + } + } + return payload; + }) + .flatMap(payload -> { + if (payload == null || payload.length == 0) { + return Mono.empty(); + } + + ByteBuffer buffer = ByteBuffer.wrap(payload); + String schemaId = getSchemaIdFromPayload(buffer); + + return this.schemaRegistryClient.getSchema(schemaId) + .handle((registryObject, sink) -> { + byte[] payloadSchema = registryObject.getSchema(); + + if (payloadSchema == null) { + sink.error(logger.logExceptionAsError( + new NullPointerException( + String.format("Payload schema returned as null. Schema type: %s, Schema ID: %s", + registryObject.getSerializationType(), registryObject.getSchemaId())))); + return; + } + + int start = buffer.position() + buffer.arrayOffset(); + int length = buffer.limit() - SCHEMA_ID_SIZE; + byte[] b = Arrays.copyOfRange(buffer.array(), start, start + length); + + sink.next(codec.decode(b, payloadSchema)); + }); + }); + } + + @Override + public void serialize(OutputStream outputStream, Object value) { + serializeAsync(outputStream, value).block(); + } + + @Override + public Mono serializeAsync(OutputStream outputStream, Object object) { + + if (object == null) { + return monoError(logger, new NullPointerException( + "Null object, behavior should be defined in concrete serializer implementation.")); + } + + String schemaString = codec.getSchemaString(object); + String schemaName = codec.getSchemaName(object); + + return this.maybeRegisterSchema(this.schemaGroup, schemaName, schemaString) + .handle((id, sink) -> { + ByteBuffer idBuffer = ByteBuffer.allocate(SCHEMA_ID_SIZE) + .put(id.getBytes(StandardCharsets.UTF_8)); + try { + outputStream.write(idBuffer.array()); + outputStream.write(codec.encode(object)); + sink.complete(); + } catch (IOException e) { + sink.error(new UncheckedIOException(e.getMessage(), e)); + } + }); } /** - * Serializes object into byte array payload using the configured byte encoder. - * @param object target of serialization - * @return byte array containing GUID reference to schema, then the object serialized into bytes - * @throws SerializationException Throws on serialization failure. + * @param buffer full payload bytes + * @return String representation of schema ID */ - public byte[] serialize(Object object) throws SerializationException { - if (object == null) { - return null; + private String getSchemaIdFromPayload(ByteBuffer buffer) { + byte[] schemaGuidByteArray = new byte[SCHEMA_ID_SIZE]; + buffer.get(schemaGuidByteArray); + + return new String(schemaGuidByteArray, StandardCharsets.UTF_8); + } + + /** + * If auto-registering is enabled, register schema against Schema Registry. + * If auto-registering is disabled, fetch schema ID for provided schema. Requires pre-registering of schema + * against registry. + * + * @param schemaGroup Schema group where schema should be registered. + * @param schemaName name of schema + * @param schemaString string representation of schema being stored - must match group schema type + * @return string representation of schema ID + */ + private Mono maybeRegisterSchema( + String schemaGroup, String schemaName, String schemaString) { + if (this.autoRegisterSchemas) { + return this.schemaRegistryClient + .registerSchema(schemaGroup, schemaName, schemaString, SerializationType.AVRO) + .map(SchemaProperties::getSchemaId); + } else { + return this.schemaRegistryClient.getSchemaId( + schemaGroup, schemaName, schemaString, SerializationType.AVRO); } - return serializeImpl(object); } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializerBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializerBuilder.java index 2cd693190016c..403c1aa74535b 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializerBuilder.java +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializerBuilder.java @@ -3,46 +3,24 @@ package com.azure.data.schemaregistry.avro; -import com.azure.core.credential.TokenCredential; -import com.azure.data.schemaregistry.AbstractDataSerializer; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryClient; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryClientBuilder; - -import java.util.Objects; +import com.azure.data.schemaregistry.SchemaRegistryAsyncClient; /** - * Builder implemenation for building {@link SchemaRegistryAvroSerializer} and {@link SchemaRegistryAvroAsyncSerializer} + * Builder implementation for building {@link SchemaRegistryAvroSerializer} and {@link SchemaRegistryAvroSerializer} */ public final class SchemaRegistryAvroSerializerBuilder { - private String registryUrl; - private TokenCredential credential; - private boolean autoRegisterSchemas; + private Boolean autoRegisterSchemas; + private Boolean avroSpecificReader; + private SchemaRegistryAsyncClient schemaRegistryAsyncClient; private String schemaGroup; - private Integer maxSchemaMapSize; /** * Instantiates instance of Builder class. * Supplies client defaults. */ public SchemaRegistryAvroSerializerBuilder() { - this.registryUrl = null; - this.credential = null; - this.autoRegisterSchemas = AbstractDataSerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; - this.schemaGroup = AbstractDataSerializer.SCHEMA_GROUP_DEFAULT; - this.maxSchemaMapSize = null; - } - - /** - * Sets the service endpoint for the Azure Schema Registry instance. - * - * @return The updated {@link SchemaRegistryAvroSerializerBuilder} object. - * @param schemaRegistryUrl The URL of the Azure Schema Registry instance - * @throws NullPointerException if {@code schemaRegistryUrl} is null - */ - public SchemaRegistryAvroSerializerBuilder schemaRegistryUrl(String schemaRegistryUrl) { - Objects.requireNonNull(schemaRegistryUrl, "'schemaRegistryUrl' cannot be null."); - this.registryUrl = schemaRegistryUrl; - return this; + this.autoRegisterSchemas = false; + this.avroSpecificReader = false; } /** @@ -59,16 +37,6 @@ public SchemaRegistryAvroSerializerBuilder schemaGroup(String schemaGroup) { return this; } - /** - * Specifies authentication behavior with Azure Schema Registry - * @param credential TokenCredential to be used to authenticate with Azure Schema Registry service - * @return updated {@link SchemaRegistryAvroSerializerBuilder} instance - */ - public SchemaRegistryAvroSerializerBuilder credential(TokenCredential credential) { - this.credential = credential; - return this; - } - /** * If specified true, serializer will register schemas against Azure Schema Registry service under the specified * group. See Azure Schema Registry documentation for a description of schema registration behavior. @@ -87,46 +55,37 @@ public SchemaRegistryAvroSerializerBuilder autoRegisterSchema(boolean autoRegist } /** - * Specifies maximum schema object cache size for underlying CachedSchemaRegistryClient. If specified cache - * size is exceeded, all caches are recycled. - * - * @param maxSchemaMapSize maximum number of schemas per cache + * Specifies if objects should be deserialized into Avro SpecificRecords via Avro SpecificDatumReader + * @param avroSpecificReader specific reader flag * @return updated {@link SchemaRegistryAvroSerializerBuilder} instance */ - public SchemaRegistryAvroSerializerBuilder maxSchemaMapSize(int maxSchemaMapSize) { - this.maxSchemaMapSize = maxSchemaMapSize; + public SchemaRegistryAvroSerializerBuilder avroSpecificReader(boolean avroSpecificReader) { + this.avroSpecificReader = avroSpecificReader; return this; } + /** - * Instantiates SchemaRegistry - * @return {@link SchemaRegistryAvroAsyncSerializer} instance - * - * @throws NullPointerException if parameters are incorrectly set. - * @throws IllegalArgumentException if credential is not set. + * The {@link SchemaRegistryAsyncClient} to use to interact with the Schema Registry service. + * @param schemaRegistryAsyncClient The {@link SchemaRegistryAsyncClient}. + * @return updated {@link SchemaRegistryAvroSerializerBuilder} instance. */ - public SchemaRegistryAvroAsyncSerializer buildAsyncClient() { - return new SchemaRegistryAvroAsyncSerializer(this.buildSyncClient()); + public SchemaRegistryAvroSerializerBuilder schemaRegistryAsyncClient( + SchemaRegistryAsyncClient schemaRegistryAsyncClient) { + this.schemaRegistryAsyncClient = schemaRegistryAsyncClient; + return this; } /** - * Instantiates {@link SchemaRegistryAvroSerializer} + * Instantiates SchemaRegistry avro serializer. * @return {@link SchemaRegistryAvroSerializer} instance * * @throws NullPointerException if parameters are incorrectly set. * @throws IllegalArgumentException if credential is not set. */ - public SchemaRegistryAvroSerializer buildSyncClient() { - CachedSchemaRegistryClientBuilder builder = new CachedSchemaRegistryClientBuilder() - .endpoint(registryUrl) - .credential(credential); - - if (maxSchemaMapSize != null) { - builder.maxSchemaMapSize(maxSchemaMapSize); - } - - CachedSchemaRegistryClient client = builder.buildClient(); - - return new SchemaRegistryAvroSerializer(client, this.schemaGroup, this.autoRegisterSchemas); + public SchemaRegistryAvroSerializer buildSerializer() { + AvroSchemaRegistryUtils codec = new AvroSchemaRegistryUtils(this.avroSpecificReader); + return new SchemaRegistryAvroSerializer(schemaRegistryAsyncClient, codec, this.schemaGroup, + this.autoRegisterSchemas); } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/README.md b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/README.md new file mode 100644 index 0000000000000..d31ddf33daa29 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/README.md @@ -0,0 +1,46 @@ +--- +page_type: sample +languages: + - java +products: + - azure + - azure-data-schemaregistry-avro +urlFragment: schemaregistry-avro-samples +--- + +# Azure Schema Registry serializer library samples for Java + +Azure Schema Registry Avro Serializer samples are a set of self-contained Java programs that demonstrate serialization +and deserialization of data for which the schema is stored in Schema Registry service. Each sample focuses on a +specific scenario and can be executed independently. + +## Key concepts +Key concepts are explained in detail [here][sdk_readme_key_concepts]. + +## Getting started +Please refer to the [Getting Started][sdk_readme_getting_started] section. + +## Examples + +- [Serialize an object into avro schema bytes][sample_avro_serialization] +- [Deserialize avro serialized bytes into a strongly-typed object][sample_avro_deserialization] + +## Troubleshooting +See [Troubleshooting][sdk_readme_troubleshooting]. + +## Next steps +See [Next steps][sdk_readme_next_steps]. + +## Contributing +This project welcomes contributions and suggestions. See [Contributing][sdk_readme_contributing] for guidelines. + + +[sdk_readme_key_concepts]: ../../README.md#key-concepts +[sdk_readme_getting_started]: ../../README.md#getting-started +[sdk_readme_troubleshooting]: ../../README.md#troubleshooting +[sdk_readme_next_steps]: ../../README.md#next-steps +[sdk_readme_contributing]: ../../README.md#contributing +[sample_avro_serialization]: ./java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializationSample.java +[sample_avro_deserialization]: ./java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializationSample.java + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%schemaregistry%2Fazure-data-schemaregistry-avro%2Fsrc%2Fsamples%2README.png) diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserilizationSample.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserilizationSample.java new file mode 100644 index 0000000000000..4f4c5527cdddb --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroDeserilizationSample.java @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.avro; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.util.serializer.TypeReference; +import com.azure.data.schemaregistry.SchemaRegistryAsyncClient; +import com.azure.data.schemaregistry.SchemaRegistryClientBuilder; +import com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard; +import com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * Sample application to demonstrate deserializing data into a strongly-typed object using Schema Registry-based Avro + * Serializer. + */ +public class SchemaRegistryAvroDeserilizationSample { + /** + * Main method to run this sample. + * + * @param args Ignore arguments. + */ + public static void main(String[] args) throws IOException { + // Create AAD token credential + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + // Create the schema registry async client + SchemaRegistryAsyncClient schemaRegistryAsyncClient = new SchemaRegistryClientBuilder() + .credential(tokenCredential) + .endpoint("{schema-registry-endpoint}") + .buildAsyncClient(); + + // Create the serializer instance by configuring the serializer with the schema registry client and + // enabling auto registering of new schemas + SchemaRegistryAvroSerializer schemaRegistryAvroSerializer = new SchemaRegistryAvroSerializerBuilder() + .schemaRegistryAsyncClient(schemaRegistryAsyncClient) + .schemaGroup("{schema-group}") + .avroSpecificReader(true) + .autoRegisterSchema(true) + .buildSerializer(); + + // Get serialized avro data to deserialize into strongly-typed object. + InputStream inputStream = getDataToDeserialize(); + PlayingCard deserializedObject = schemaRegistryAvroSerializer.deserialize(inputStream, + TypeReference.createInstance(PlayingCard.class)); + } + + private static InputStream getDataToDeserialize() throws IOException { + PlayingCard playingCard = new PlayingCard(); + playingCard.setCardValue(5); + playingCard.setIsFaceCard(false); + playingCard.setPlayingCardSuit(PlayingCardSuit.SPADES); + // get byte array of PlayingCard + InputStream inputStream = new ByteArrayInputStream(playingCard.toByteBuffer().array()); + return inputStream; + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializationSample.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializationSample.java new file mode 100644 index 0000000000000..5d5070959fe3b --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializationSample.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.avro; + +import com.azure.core.credential.TokenCredential; +import com.azure.data.schemaregistry.SchemaRegistryAsyncClient; +import com.azure.data.schemaregistry.SchemaRegistryClientBuilder; +import com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard; +import com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; + +/** + * Sample to demonstrate using {@link SchemaRegistryAvroSerializer} for serialization of data. + */ +public class SchemaRegistryAvroSerializationSample { + /** + * Main method to run this sample. + * + * @param args Ignore arguments. + */ + public static void main(String[] args) { + // Create AAD token credential + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + // Create the schema registry async client + SchemaRegistryAsyncClient schemaRegistryAsyncClient = new SchemaRegistryClientBuilder() + .credential(tokenCredential) + .endpoint("{schema-registry-endpoint}") + .buildAsyncClient(); + + // Create the serializer instance by configuring the serializer with the schema registry client and + // enabling auto registering of new schemas + SchemaRegistryAvroSerializer schemaRegistryAvroSerializer = new SchemaRegistryAvroSerializerBuilder() + .schemaRegistryAsyncClient(schemaRegistryAsyncClient) + .schemaGroup("{schema-group}") + .avroSpecificReader(true) + .buildSerializer(); + + PlayingCard playingCard = new PlayingCard(); + playingCard.setCardValue(5); + playingCard.setIsFaceCard(false); + playingCard.setPlayingCardSuit(PlayingCardSuit.SPADES); + + OutputStream outputStream = new ByteArrayOutputStream(); + + // Serialize the playing card object and write to the output stream. + schemaRegistryAvroSerializer.serialize(outputStream, playingCard); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/HandOfCards.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/HandOfCards.java new file mode 100644 index 0000000000000..8f096cace3310 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/HandOfCards.java @@ -0,0 +1,354 @@ +/** + * Autogenerated by Avro + * + * DO NOT EDIT DIRECTLY + */ +package com.azure.data.schemaregistry.avro.generatedtestsources; + +import org.apache.avro.generic.GenericArray; +import org.apache.avro.specific.SpecificData; +import org.apache.avro.util.Utf8; +import org.apache.avro.message.BinaryMessageEncoder; +import org.apache.avro.message.BinaryMessageDecoder; +import org.apache.avro.message.SchemaStore; + +@org.apache.avro.specific.AvroGenerated +public class HandOfCards extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord { + private static final long serialVersionUID = 5886600203104367370L; + public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"HandOfCards\",\"namespace\":\"com.azure.data.schemaregistry.avro.generatedtestsources\",\"fields\":[{\"name\":\"cards\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"record\",\"name\":\"PlayingCard\",\"fields\":[{\"name\":\"isFaceCard\",\"type\":\"boolean\"},{\"name\":\"cardValue\",\"type\":\"int\"},{\"name\":\"playingCardSuit\",\"type\":{\"type\":\"enum\",\"name\":\"PlayingCardSuit\",\"symbols\":[\"SPADES\",\"HEARTS\",\"DIAMONDS\",\"CLUBS\"]}}]}}}]}"); + public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; } + + private static SpecificData MODEL$ = new SpecificData(); + + private static final BinaryMessageEncoder ENCODER = + new BinaryMessageEncoder(MODEL$, SCHEMA$); + + private static final BinaryMessageDecoder DECODER = + new BinaryMessageDecoder(MODEL$, SCHEMA$); + + /** + * Return the BinaryMessageEncoder instance used by this class. + * @return the message encoder used by this class + */ + public static BinaryMessageEncoder getEncoder() { + return ENCODER; + } + + /** + * Return the BinaryMessageDecoder instance used by this class. + * @return the message decoder used by this class + */ + public static BinaryMessageDecoder getDecoder() { + return DECODER; + } + + /** + * Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}. + * @param resolver a {@link SchemaStore} used to find schemas by fingerprint + * @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore + */ + public static BinaryMessageDecoder createDecoder(SchemaStore resolver) { + return new BinaryMessageDecoder(MODEL$, SCHEMA$, resolver); + } + + /** + * Serializes this HandOfCards to a ByteBuffer. + * @return a buffer holding the serialized data for this instance + * @throws java.io.IOException if this instance could not be serialized + */ + public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException { + return ENCODER.encode(this); + } + + /** + * Deserializes a HandOfCards from a ByteBuffer. + * @param b a byte buffer holding serialized data for an instance of this class + * @return a HandOfCards instance decoded from the given buffer + * @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class + */ + public static HandOfCards fromByteBuffer( + java.nio.ByteBuffer b) throws java.io.IOException { + return DECODER.decode(b); + } + + @Deprecated public java.util.List cards; + + /** + * Default constructor. Note that this does not initialize fields + * to their default values from the schema. If that is desired then + * one should use newBuilder(). + */ + public HandOfCards() {} + + /** + * All-args constructor. + * @param cards The new value for cards + */ + public HandOfCards(java.util.List cards) { + this.cards = cards; + } + + public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; } + public org.apache.avro.Schema getSchema() { return SCHEMA$; } + // Used by DatumWriter. Applications should not call. + public java.lang.Object get(int field$) { + switch (field$) { + case 0: return cards; + default: throw new org.apache.avro.AvroRuntimeException("Bad index"); + } + } + + // Used by DatumReader. Applications should not call. + @SuppressWarnings(value="unchecked") + public void put(int field$, java.lang.Object value$) { + switch (field$) { + case 0: cards = (java.util.List)value$; break; + default: throw new org.apache.avro.AvroRuntimeException("Bad index"); + } + } + + /** + * Gets the value of the 'cards' field. + * @return The value of the 'cards' field. + */ + public java.util.List getCards() { + return cards; + } + + + /** + * Sets the value of the 'cards' field. + * @param value the value to set. + */ + public void setCards(java.util.List value) { + this.cards = value; + } + + /** + * Creates a new HandOfCards RecordBuilder. + * @return A new HandOfCards RecordBuilder + */ + public static com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder newBuilder() { + return new com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder(); + } + + /** + * Creates a new HandOfCards RecordBuilder by copying an existing Builder. + * @param other The existing builder to copy. + * @return A new HandOfCards RecordBuilder + */ + public static com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder newBuilder(com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder other) { + if (other == null) { + return new com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder(); + } else { + return new com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder(other); + } + } + + /** + * Creates a new HandOfCards RecordBuilder by copying an existing HandOfCards instance. + * @param other The existing instance to copy. + * @return A new HandOfCards RecordBuilder + */ + public static com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder newBuilder(com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards other) { + if (other == null) { + return new com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder(); + } else { + return new com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder(other); + } + } + + /** + * RecordBuilder for HandOfCards instances. + */ + @org.apache.avro.specific.AvroGenerated + public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase + implements org.apache.avro.data.RecordBuilder { + + private java.util.List cards; + + /** Creates a new Builder */ + private Builder() { + super(SCHEMA$); + } + + /** + * Creates a Builder by copying an existing Builder. + * @param other The existing Builder to copy. + */ + private Builder(com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder other) { + super(other); + if (isValidValue(fields()[0], other.cards)) { + this.cards = data().deepCopy(fields()[0].schema(), other.cards); + fieldSetFlags()[0] = other.fieldSetFlags()[0]; + } + } + + /** + * Creates a Builder by copying an existing HandOfCards instance + * @param other The existing instance to copy. + */ + private Builder(com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards other) { + super(SCHEMA$); + if (isValidValue(fields()[0], other.cards)) { + this.cards = data().deepCopy(fields()[0].schema(), other.cards); + fieldSetFlags()[0] = true; + } + } + + /** + * Gets the value of the 'cards' field. + * @return The value. + */ + public java.util.List getCards() { + return cards; + } + + + /** + * Sets the value of the 'cards' field. + * @param value The value of 'cards'. + * @return This builder. + */ + public com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder setCards(java.util.List value) { + validate(fields()[0], value); + this.cards = value; + fieldSetFlags()[0] = true; + return this; + } + + /** + * Checks whether the 'cards' field has been set. + * @return True if the 'cards' field has been set, false otherwise. + */ + public boolean hasCards() { + return fieldSetFlags()[0]; + } + + + /** + * Clears the value of the 'cards' field. + * @return This builder. + */ + public com.azure.data.schemaregistry.avro.generatedtestsources.HandOfCards.Builder clearCards() { + cards = null; + fieldSetFlags()[0] = false; + return this; + } + + @Override + @SuppressWarnings("unchecked") + public HandOfCards build() { + try { + HandOfCards record = new HandOfCards(); + record.cards = fieldSetFlags()[0] ? this.cards : (java.util.List) defaultValue(fields()[0]); + return record; + } catch (org.apache.avro.AvroMissingFieldException e) { + throw e; + } catch (java.lang.Exception e) { + throw new org.apache.avro.AvroRuntimeException(e); + } + } + } + + @SuppressWarnings("unchecked") + private static final org.apache.avro.io.DatumWriter + WRITER$ = (org.apache.avro.io.DatumWriter)MODEL$.createDatumWriter(SCHEMA$); + + @Override public void writeExternal(java.io.ObjectOutput out) + throws java.io.IOException { + WRITER$.write(this, SpecificData.getEncoder(out)); + } + + @SuppressWarnings("unchecked") + private static final org.apache.avro.io.DatumReader + READER$ = (org.apache.avro.io.DatumReader)MODEL$.createDatumReader(SCHEMA$); + + @Override public void readExternal(java.io.ObjectInput in) + throws java.io.IOException { + READER$.read(this, SpecificData.getDecoder(in)); + } + + @Override protected boolean hasCustomCoders() { return true; } + + @Override public void customEncode(org.apache.avro.io.Encoder out) + throws java.io.IOException + { + long size0 = this.cards.size(); + out.writeArrayStart(); + out.setItemCount(size0); + long actualSize0 = 0; + for (com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard e0: this.cards) { + actualSize0++; + out.startItem(); + e0.customEncode(out); + } + out.writeArrayEnd(); + if (actualSize0 != size0) + throw new java.util.ConcurrentModificationException("Array-size written was " + size0 + ", but element count was " + actualSize0 + "."); + + } + + @Override public void customDecode(org.apache.avro.io.ResolvingDecoder in) + throws java.io.IOException + { + org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff(); + if (fieldOrder == null) { + long size0 = in.readArrayStart(); + java.util.List a0 = this.cards; + if (a0 == null) { + a0 = new SpecificData.Array((int)size0, SCHEMA$.getField("cards").schema()); + this.cards = a0; + } else a0.clear(); + SpecificData.Array ga0 = (a0 instanceof SpecificData.Array ? (SpecificData.Array)a0 : null); + for ( ; 0 < size0; size0 = in.arrayNext()) { + for ( ; size0 != 0; size0--) { + com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard e0 = (ga0 != null ? ga0.peek() : null); + if (e0 == null) { + e0 = new com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard(); + } + e0.customDecode(in); + a0.add(e0); + } + } + + } else { + for (int i = 0; i < 1; i++) { + switch (fieldOrder[i].pos()) { + case 0: + long size0 = in.readArrayStart(); + java.util.List a0 = this.cards; + if (a0 == null) { + a0 = new SpecificData.Array((int)size0, SCHEMA$.getField("cards").schema()); + this.cards = a0; + } else a0.clear(); + SpecificData.Array ga0 = (a0 instanceof SpecificData.Array ? (SpecificData.Array)a0 : null); + for ( ; 0 < size0; size0 = in.arrayNext()) { + for ( ; size0 != 0; size0--) { + com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard e0 = (ga0 != null ? ga0.peek() : null); + if (e0 == null) { + e0 = new com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard(); + } + e0.customDecode(in); + a0.add(e0); + } + } + break; + + default: + throw new java.io.IOException("Corrupt ResolvingDecoder."); + } + } + } + } +} + + + + + + + + + + diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/PlayingCard.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/PlayingCard.java new file mode 100644 index 0000000000000..9d7835be0d727 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/PlayingCard.java @@ -0,0 +1,469 @@ +/** + * Autogenerated by Avro + * + * DO NOT EDIT DIRECTLY + */ +package com.azure.data.schemaregistry.avro.generatedtestsources; + +import org.apache.avro.generic.GenericArray; +import org.apache.avro.specific.SpecificData; +import org.apache.avro.util.Utf8; +import org.apache.avro.message.BinaryMessageEncoder; +import org.apache.avro.message.BinaryMessageDecoder; +import org.apache.avro.message.SchemaStore; + +@org.apache.avro.specific.AvroGenerated +public class PlayingCard extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord { + private static final long serialVersionUID = 2522401015271889859L; + public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"PlayingCard\",\"namespace\":\"com.azure.data.schemaregistry.avro.generatedtestsources\",\"fields\":[{\"name\":\"isFaceCard\",\"type\":\"boolean\"},{\"name\":\"cardValue\",\"type\":\"int\"},{\"name\":\"playingCardSuit\",\"type\":{\"type\":\"enum\",\"name\":\"PlayingCardSuit\",\"symbols\":[\"SPADES\",\"HEARTS\",\"DIAMONDS\",\"CLUBS\"]}}]}"); + public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; } + + private static SpecificData MODEL$ = new SpecificData(); + + private static final BinaryMessageEncoder ENCODER = + new BinaryMessageEncoder(MODEL$, SCHEMA$); + + private static final BinaryMessageDecoder DECODER = + new BinaryMessageDecoder(MODEL$, SCHEMA$); + + /** + * Return the BinaryMessageEncoder instance used by this class. + * @return the message encoder used by this class + */ + public static BinaryMessageEncoder getEncoder() { + return ENCODER; + } + + /** + * Return the BinaryMessageDecoder instance used by this class. + * @return the message decoder used by this class + */ + public static BinaryMessageDecoder getDecoder() { + return DECODER; + } + + /** + * Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}. + * @param resolver a {@link SchemaStore} used to find schemas by fingerprint + * @return a BinaryMessageDecoder instance for this class backed by the given SchemaStore + */ + public static BinaryMessageDecoder createDecoder(SchemaStore resolver) { + return new BinaryMessageDecoder(MODEL$, SCHEMA$, resolver); + } + + /** + * Serializes this PlayingCard to a ByteBuffer. + * @return a buffer holding the serialized data for this instance + * @throws java.io.IOException if this instance could not be serialized + */ + public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException { + return ENCODER.encode(this); + } + + /** + * Deserializes a PlayingCard from a ByteBuffer. + * @param b a byte buffer holding serialized data for an instance of this class + * @return a PlayingCard instance decoded from the given buffer + * @throws java.io.IOException if the given bytes could not be deserialized into an instance of this class + */ + public static PlayingCard fromByteBuffer( + java.nio.ByteBuffer b) throws java.io.IOException { + return DECODER.decode(b); + } + + @Deprecated public boolean isFaceCard; + @Deprecated public int cardValue; + @Deprecated public com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit playingCardSuit; + + /** + * Default constructor. Note that this does not initialize fields + * to their default values from the schema. If that is desired then + * one should use newBuilder(). + */ + public PlayingCard() {} + + /** + * All-args constructor. + * @param isFaceCard The new value for isFaceCard + * @param cardValue The new value for cardValue + * @param playingCardSuit The new value for playingCardSuit + */ + public PlayingCard(java.lang.Boolean isFaceCard, java.lang.Integer cardValue, com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit playingCardSuit) { + this.isFaceCard = isFaceCard; + this.cardValue = cardValue; + this.playingCardSuit = playingCardSuit; + } + + public org.apache.avro.specific.SpecificData getSpecificData() { return MODEL$; } + public org.apache.avro.Schema getSchema() { return SCHEMA$; } + // Used by DatumWriter. Applications should not call. + public java.lang.Object get(int field$) { + switch (field$) { + case 0: return isFaceCard; + case 1: return cardValue; + case 2: return playingCardSuit; + default: throw new org.apache.avro.AvroRuntimeException("Bad index"); + } + } + + // Used by DatumReader. Applications should not call. + @SuppressWarnings(value="unchecked") + public void put(int field$, java.lang.Object value$) { + switch (field$) { + case 0: isFaceCard = (java.lang.Boolean)value$; break; + case 1: cardValue = (java.lang.Integer)value$; break; + case 2: playingCardSuit = (com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit)value$; break; + default: throw new org.apache.avro.AvroRuntimeException("Bad index"); + } + } + + /** + * Gets the value of the 'isFaceCard' field. + * @return The value of the 'isFaceCard' field. + */ + public boolean getIsFaceCard() { + return isFaceCard; + } + + + /** + * Sets the value of the 'isFaceCard' field. + * @param value the value to set. + */ + public void setIsFaceCard(boolean value) { + this.isFaceCard = value; + } + + /** + * Gets the value of the 'cardValue' field. + * @return The value of the 'cardValue' field. + */ + public int getCardValue() { + return cardValue; + } + + + /** + * Sets the value of the 'cardValue' field. + * @param value the value to set. + */ + public void setCardValue(int value) { + this.cardValue = value; + } + + /** + * Gets the value of the 'playingCardSuit' field. + * @return The value of the 'playingCardSuit' field. + */ + public com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit getPlayingCardSuit() { + return playingCardSuit; + } + + + /** + * Sets the value of the 'playingCardSuit' field. + * @param value the value to set. + */ + public void setPlayingCardSuit(com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit value) { + this.playingCardSuit = value; + } + + /** + * Creates a new PlayingCard RecordBuilder. + * @return A new PlayingCard RecordBuilder + */ + public static com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder newBuilder() { + return new com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder(); + } + + /** + * Creates a new PlayingCard RecordBuilder by copying an existing Builder. + * @param other The existing builder to copy. + * @return A new PlayingCard RecordBuilder + */ + public static com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder newBuilder(com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder other) { + if (other == null) { + return new com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder(); + } else { + return new com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder(other); + } + } + + /** + * Creates a new PlayingCard RecordBuilder by copying an existing PlayingCard instance. + * @param other The existing instance to copy. + * @return A new PlayingCard RecordBuilder + */ + public static com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder newBuilder(com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard other) { + if (other == null) { + return new com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder(); + } else { + return new com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder(other); + } + } + + /** + * RecordBuilder for PlayingCard instances. + */ + @org.apache.avro.specific.AvroGenerated + public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase + implements org.apache.avro.data.RecordBuilder { + + private boolean isFaceCard; + private int cardValue; + private com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit playingCardSuit; + + /** Creates a new Builder */ + private Builder() { + super(SCHEMA$); + } + + /** + * Creates a Builder by copying an existing Builder. + * @param other The existing Builder to copy. + */ + private Builder(com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder other) { + super(other); + if (isValidValue(fields()[0], other.isFaceCard)) { + this.isFaceCard = data().deepCopy(fields()[0].schema(), other.isFaceCard); + fieldSetFlags()[0] = other.fieldSetFlags()[0]; + } + if (isValidValue(fields()[1], other.cardValue)) { + this.cardValue = data().deepCopy(fields()[1].schema(), other.cardValue); + fieldSetFlags()[1] = other.fieldSetFlags()[1]; + } + if (isValidValue(fields()[2], other.playingCardSuit)) { + this.playingCardSuit = data().deepCopy(fields()[2].schema(), other.playingCardSuit); + fieldSetFlags()[2] = other.fieldSetFlags()[2]; + } + } + + /** + * Creates a Builder by copying an existing PlayingCard instance + * @param other The existing instance to copy. + */ + private Builder(com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard other) { + super(SCHEMA$); + if (isValidValue(fields()[0], other.isFaceCard)) { + this.isFaceCard = data().deepCopy(fields()[0].schema(), other.isFaceCard); + fieldSetFlags()[0] = true; + } + if (isValidValue(fields()[1], other.cardValue)) { + this.cardValue = data().deepCopy(fields()[1].schema(), other.cardValue); + fieldSetFlags()[1] = true; + } + if (isValidValue(fields()[2], other.playingCardSuit)) { + this.playingCardSuit = data().deepCopy(fields()[2].schema(), other.playingCardSuit); + fieldSetFlags()[2] = true; + } + } + + /** + * Gets the value of the 'isFaceCard' field. + * @return The value. + */ + public boolean getIsFaceCard() { + return isFaceCard; + } + + + /** + * Sets the value of the 'isFaceCard' field. + * @param value The value of 'isFaceCard'. + * @return This builder. + */ + public com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder setIsFaceCard(boolean value) { + validate(fields()[0], value); + this.isFaceCard = value; + fieldSetFlags()[0] = true; + return this; + } + + /** + * Checks whether the 'isFaceCard' field has been set. + * @return True if the 'isFaceCard' field has been set, false otherwise. + */ + public boolean hasIsFaceCard() { + return fieldSetFlags()[0]; + } + + + /** + * Clears the value of the 'isFaceCard' field. + * @return This builder. + */ + public com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder clearIsFaceCard() { + fieldSetFlags()[0] = false; + return this; + } + + /** + * Gets the value of the 'cardValue' field. + * @return The value. + */ + public int getCardValue() { + return cardValue; + } + + + /** + * Sets the value of the 'cardValue' field. + * @param value The value of 'cardValue'. + * @return This builder. + */ + public com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder setCardValue(int value) { + validate(fields()[1], value); + this.cardValue = value; + fieldSetFlags()[1] = true; + return this; + } + + /** + * Checks whether the 'cardValue' field has been set. + * @return True if the 'cardValue' field has been set, false otherwise. + */ + public boolean hasCardValue() { + return fieldSetFlags()[1]; + } + + + /** + * Clears the value of the 'cardValue' field. + * @return This builder. + */ + public com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder clearCardValue() { + fieldSetFlags()[1] = false; + return this; + } + + /** + * Gets the value of the 'playingCardSuit' field. + * @return The value. + */ + public com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit getPlayingCardSuit() { + return playingCardSuit; + } + + + /** + * Sets the value of the 'playingCardSuit' field. + * @param value The value of 'playingCardSuit'. + * @return This builder. + */ + public com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder setPlayingCardSuit(com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit value) { + validate(fields()[2], value); + this.playingCardSuit = value; + fieldSetFlags()[2] = true; + return this; + } + + /** + * Checks whether the 'playingCardSuit' field has been set. + * @return True if the 'playingCardSuit' field has been set, false otherwise. + */ + public boolean hasPlayingCardSuit() { + return fieldSetFlags()[2]; + } + + + /** + * Clears the value of the 'playingCardSuit' field. + * @return This builder. + */ + public com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCard.Builder clearPlayingCardSuit() { + playingCardSuit = null; + fieldSetFlags()[2] = false; + return this; + } + + @Override + @SuppressWarnings("unchecked") + public PlayingCard build() { + try { + PlayingCard record = new PlayingCard(); + record.isFaceCard = fieldSetFlags()[0] ? this.isFaceCard : (java.lang.Boolean) defaultValue(fields()[0]); + record.cardValue = fieldSetFlags()[1] ? this.cardValue : (java.lang.Integer) defaultValue(fields()[1]); + record.playingCardSuit = fieldSetFlags()[2] ? this.playingCardSuit : (com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit) defaultValue(fields()[2]); + return record; + } catch (org.apache.avro.AvroMissingFieldException e) { + throw e; + } catch (java.lang.Exception e) { + throw new org.apache.avro.AvroRuntimeException(e); + } + } + } + + @SuppressWarnings("unchecked") + private static final org.apache.avro.io.DatumWriter + WRITER$ = (org.apache.avro.io.DatumWriter)MODEL$.createDatumWriter(SCHEMA$); + + @Override public void writeExternal(java.io.ObjectOutput out) + throws java.io.IOException { + WRITER$.write(this, SpecificData.getEncoder(out)); + } + + @SuppressWarnings("unchecked") + private static final org.apache.avro.io.DatumReader + READER$ = (org.apache.avro.io.DatumReader)MODEL$.createDatumReader(SCHEMA$); + + @Override public void readExternal(java.io.ObjectInput in) + throws java.io.IOException { + READER$.read(this, SpecificData.getDecoder(in)); + } + + @Override protected boolean hasCustomCoders() { return true; } + + @Override public void customEncode(org.apache.avro.io.Encoder out) + throws java.io.IOException + { + out.writeBoolean(this.isFaceCard); + + out.writeInt(this.cardValue); + + out.writeEnum(this.playingCardSuit.ordinal()); + + } + + @Override public void customDecode(org.apache.avro.io.ResolvingDecoder in) + throws java.io.IOException + { + org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff(); + if (fieldOrder == null) { + this.isFaceCard = in.readBoolean(); + + this.cardValue = in.readInt(); + + this.playingCardSuit = com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit.values()[in.readEnum()]; + + } else { + for (int i = 0; i < 3; i++) { + switch (fieldOrder[i].pos()) { + case 0: + this.isFaceCard = in.readBoolean(); + break; + + case 1: + this.cardValue = in.readInt(); + break; + + case 2: + this.playingCardSuit = com.azure.data.schemaregistry.avro.generatedtestsources.PlayingCardSuit.values()[in.readEnum()]; + break; + + default: + throw new java.io.IOException("Corrupt ResolvingDecoder."); + } + } + } + } +} + + + + + + + + + + diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/PlayingCardSuit.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/PlayingCardSuit.java new file mode 100644 index 0000000000000..e1c8206e420ad --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/generatedtestsources/PlayingCardSuit.java @@ -0,0 +1,13 @@ +/** + * Autogenerated by Avro + * + * DO NOT EDIT DIRECTLY + */ +package com.azure.data.schemaregistry.avro.generatedtestsources; +@org.apache.avro.specific.AvroGenerated +public enum PlayingCardSuit implements org.apache.avro.generic.GenericEnumSymbol { + SPADES, HEARTS, DIAMONDS, CLUBS ; + public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"PlayingCardSuit\",\"namespace\":\"com.azure.data.schemaregistry.avro.generatedtestsources\",\"symbols\":[\"SPADES\",\"HEARTS\",\"DIAMONDS\",\"CLUBS\"]}"); + public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; } + public org.apache.avro.Schema getSchema() { return SCHEMA$; } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/resources/avro/HandOfCards.avro b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/resources/avro/HandOfCards.avro new file mode 100644 index 0000000000000..6050db56f1205 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/resources/avro/HandOfCards.avro @@ -0,0 +1,29 @@ +{ + "namespace": "com.azure.data.schemaregistry.avro.generatedtestsources", + "type": "record", + "name": "HandOfCards", + "fields": [ + { + "name": "cards", + "type": { + "type": "array", + "items": { + "namespace": "com.azure.data.schemaregistry.avro.generatedtestsources", + "type": "record", + "name": "PlayingCard", + "fields": [ + {"name": "isFaceCard", "type": "boolean"}, + {"name": "cardValue", "type": "int"}, + {"name": "playingCardSuit", "type": { + "namespace": "com.azure.data.schemaregistry.avro.generatedtestsources", + "type": "enum", + "name": "PlayingCardSuit", + "symbols": ["SPADES", "HEARTS", "DIAMONDS", "CLUBS"] + } + } + ] + } + } + } + ] +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/test/java/com/azure/data/schemaregistry/avro/AvroByteDecoderTest.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/test/java/com/azure/data/schemaregistry/avro/AvroByteDecoderTest.java deleted file mode 100644 index 6732085e8911d..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/test/java/com/azure/data/schemaregistry/avro/AvroByteDecoderTest.java +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.avro; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class AvroByteDecoderTest { - @Test - public void testShouldAnswerWithTrue() { - assertTrue(true); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/test/java/com/azure/data/schemaregistry/avro/AvroByteEncoderTest.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/test/java/com/azure/data/schemaregistry/avro/AvroByteEncoderTest.java deleted file mode 100644 index 2f31889899175..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/test/java/com/azure/data/schemaregistry/avro/AvroByteEncoderTest.java +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.avro; - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class AvroByteEncoderTest { - private static final String MOCK_AVRO_SCHEMA_STRING = "{\"namespace\":\"example2.avro\",\"type\":\"record\",\"name\":\"User\",\"fields\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"favorite_number\",\"type\": [\"int\", \"null\"]}]}"; - - @Test - public void testPlaceholder() { - getEncoder(); - assertTrue(true); - } - - private AvroByteEncoder getEncoder() { - return new AvroByteEncoder(); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/CHANGELOG.md b/sdk/schemaregistry/azure-data-schemaregistry/CHANGELOG.md index b660f333d2488..068f7ae7d1dd1 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/CHANGELOG.md +++ b/sdk/schemaregistry/azure-data-schemaregistry/CHANGELOG.md @@ -1,9 +1,11 @@ # Release History -## 1.0.0-beta.3 (Unreleased) +## 1.0.0-beta.3 (2020-09-10) +- Removed `SchemaRegistryCodec` and `SchemaRegistrySerializer` +- Updated Schema Registry client APIs to use `SchemaProperties` ## 1.0.0-beta.2 (2020-06-19) - Fix 4xx HTTP response handling ## 1.0.0-beta.1 (2020-06-04) -- Initial add \ No newline at end of file +- Initial add diff --git a/sdk/schemaregistry/azure-data-schemaregistry/README.md b/sdk/schemaregistry/azure-data-schemaregistry/README.md index 19eaf0f2e8e42..f94d8c3009fd4 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry/README.md @@ -1,19 +1,203 @@ -# Azure Schema Registry shared library for Java +# Azure Schema Registry client library for Java -This library contains common implementations for Azure Schema Registry-backed serializers and deserializers. +Azure Schema Registry is a schema repository service hosted by Azure Event Hubs, providing schema storage, versioning, +and management. The registry is leveraged by serializers to reduce payload size while describing payload structure with +schema identifiers rather than full schemas. + +[Source code][source_code] | Package (Maven) | [API reference documentation][api_reference_doc] | [Product Documentation][product_documentation] | [Samples][sample_readme] ## Getting started +### Prerequisites + +- Java Development Kit (JDK) with version 8 or above +- [Azure Subscription][azure_subscription] +- An [Event Hubs namespace][event_hubs_namespace] + +### Include the Package + +[//]: # ({x-version-update-start;com.azure:azure-data-schemaregistry;current}) +```xml + + com.azure + azure-data-schemaregistry + 1.0.0-beta.3 + +``` +[//]: # ({x-version-update-end}) + +### Authenticate the client +In order to interact with the Azure Schema Registry service, you'll need to create an instance of the +`SchemaRegistryClient` class through the `SchemaRegistryClientBuilder`. You will need an **endpoint** and an +**API key** to instantiate a client object. + +#### Create SchemaRegistryClient with Azure Active Directory Credential + +You can authenticate with Azure Active Directory using the [Azure Identity library][azure_identity]. Note that regional endpoints do not support AAD authentication. Create a [custom subdomain][custom_subdomain] for your resource in order to use this type of authentication. + +To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below, or other credential providers provided with the Azure SDK, please include the `azure-identity` package: + +[//]: # ({x-version-update-start;com.azure:azure-identity;dependency}) +```xml + + com.azure + azure-identity + 1.1.2 + +``` + +You will also need to [register a new AAD application][register_aad_app] and [grant access][aad_grant_access] to + Schema Registry service. + +Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET. + +##### Async client + +```java +TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + +SchemaRegistryAsyncClient schemaRegistryAsyncClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildAsyncClient(); +``` + +##### Sync client + +```java +TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + +SchemaRegistryClient schemaRegistryClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildClient(); +``` + ## Key concepts +### Schemas -Using registry-backed serializers and deserializers allows schema information such as names and types of fields to be held externally in schema documents, allowing serialization and deserialization frameworks to produce very compact on-wire representations of structured data (e.g. payload of events and messages). To democratize schema handling for all clients, all parties who need to serialize or deserialize event or message payloads require consistent access to the same schema store. +A schema has 6 components: +- Group Name: The name of the group of schemas in the Schema Registry instance. +- Schema Name: The name of the schema. +- Schema ID: The ID assigned by the Schema Registry instance for the schema. +- Serialization Type: The format used for serialization of the schema. For example, Avro. +- Schema Content: The string representation of the schema. +- Schema Version: The version assigned to the schema in the Schema Registry instance. -The serialization and deserialization implementations in this library utilize the `CachedSchemaRegistryClient` class to register and fetch schemas in Azure Schema Registry. +These components play different roles. Some are used as input into the operations and some are outputs. Currently, +[SchemaProperties][schema_properties] only exposes those properties that are potential outputs that are used in +SchemaRegistry operations. Those exposed properties are `Content` and `Id`. ## Examples +* [Register a schema](#register-a-schema) +* [Retrieve a schema ID](#retrieve-a-schema-id) +* [Retrieve a schema](#retrieve-a-schema) + +### Register a schema +Register a schema to be stored in the Azure Schema Registry. + +```java +TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + +SchemaRegistryClient schemaRegistryClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildClient(); + +String schemaContent = "{\n" + + " \"type\" : \"record\", \n" + + " \"namespace\" : \"SampleSchemaNameSpace\", \n" + + " \"name\" : \"Person\", \n" + + " \"fields\" : [\n" + + " { \n" + + " \"name\" : \"FirstName\" , \"type\" : \"string\" \n" + + " }, \n" + + " { \n" + + " \"name\" : \"LastName\", \"type\" : \"string\" \n" + + " }\n" + + " ]\n" + + "}"; +SchemaProperties schemaProperties = schemaRegistryClient.registerSchema("{schema-group}", "{schema-name}", + schemaContent, SerializationType.AVRO); +System.out.println("Registered schema: " + schemaProperties.getSchemaId()); +``` + +### Retrieve a schema ID +Retrieve a previously registered schema ID from the Azure Schema Registry. + + +```java +TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + +SchemaRegistryClient schemaRegistryClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildClient(); + +SchemaProperties schemaProperties = schemaRegistryClient.getSchema("{schema-id}"); +System.out.println("Retrieved schema: " + schemaProperties.getSchemaName()); +``` +### Retrieve a schema +Retrieve a previously registered schema's content from the Azure Schema Registry. + + +```java +TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + +SchemaRegistryClient schemaRegistryClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildClient(); + +String schemaContent = "{\n" + + " \"type\" : \"record\", \n" + + " \"namespace\" : \"SampleSchemaNameSpace\", \n" + + " \"name\" : \"Person\", \n" + + " \"fields\" : [\n" + + " { \n" + + " \"name\" : \"FirstName\" , \"type\" : \"string\" \n" + + " }, \n" + + " { \n" + + " \"name\" : \"LastName\", \"type\" : \"string\" \n" + + " }\n" + + " ]\n" + + "}"; +String schemaId = schemaRegistryClient.getSchemaId("{schema-group}", "{schema-name}", + schemaContent, SerializationType.AVRO); +System.out.println("Retreived schema id: " + schemaId); +``` + ## Troubleshooting +### Enabling Logging + +Azure SDKs for Java offer a consistent logging story to help aid in troubleshooting application errors and expedite +their resolution. The logs produced will capture the flow of an application before reaching the terminal state to help +locate the root issue. View the [logging][logging] wiki for guidance about enabling logging. + ## Next steps +More samples can be found [here][samples]. ## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a [Contributor License Agreement (CLA)][cla] declaring that you have the right to, and actually do, grant us the rights to use your contribution. + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments. + + +[samples]: src/samples/java/com/azure/data/schemaregistry +[source_code]: src +[samples_code]: src/samples/ +[azure_subscription]: https://azure.microsoft.com/free/ +[api_reference_doc]: https://aka.ms/schemaregistry +[azure_cli]: https://docs.microsoft.com/cli/azure +[azure_portal]: https://portal.azure.com +[azure_identity]: https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/identity/azure-identity +[DefaultAzureCredential]: https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/identity/azure-identity/README.md#defaultazurecredential +[event_hubs_namespace]: https://docs.microsoft.com/azure/event-hubs/event-hubs-about +[product_documentation]: https://aka.ms/schemaregistry + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fschemaregistry%2Fazure-data-schemaregistry%2FREADME.png) diff --git a/sdk/schemaregistry/azure-data-schemaregistry/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry/pom.xml index 86b1a44f1b308..d37096b6d50a0 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry/pom.xml @@ -86,5 +86,11 @@ 1.9.2 test + + com.azure + azure-identity + 1.1.2 + test + diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataDeserializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataDeserializer.java deleted file mode 100644 index d757e3876ab38..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataDeserializer.java +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.client.SchemaRegistryObject; -import com.azure.data.schemaregistry.client.SchemaRegistryClient; -import com.azure.data.schemaregistry.client.SchemaRegistryClientException; - -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.Map; -import java.util.concurrent.ConcurrentSkipListMap; - -/** - * Common implementation for all registry-based deserializers. - */ -public abstract class AbstractDataDeserializer extends AbstractDataSerDe { - private final ClientLogger logger = new ClientLogger(AbstractDataDeserializer.class); - - private final Map byteDecoderMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); - - /** - * Constructor called by all concrete implementation constructors. - * Should only call parent constructor. - * @param schemaRegistryClient client to be used for fetching schemas by ID - */ - protected AbstractDataDeserializer(SchemaRegistryClient schemaRegistryClient) { - super(schemaRegistryClient); - } - - /** - * Special case constructor for Kafka deserializer's empty constructors. - */ - protected AbstractDataDeserializer() { } - - /** - * Fetches schema referenced by prefixed ID and deserializes the subsequent payload into Java object. - * - * @param payload byte payload, produced by an Azure Schema Registry client producer - * @return object, deserialized with the prefixed schema - * @throws SerializationException if deserialization of registry schema or message payload fails. - */ - protected Object deserialize(byte[] payload) throws SerializationException { - if (payload == null) { - return null; - } - - ByteBuffer buffer = ByteBuffer.wrap(payload); - String schemaGuid = getSchemaGuidFromPayload(buffer); - SchemaRegistryObject registryObject; - Object payloadSchema; - - try { - registryObject = this.schemaRegistryClient.getSchemaByGuid(schemaGuid); - payloadSchema = registryObject.deserialize(); - } catch (SchemaRegistryClientException e) { - throw logger.logExceptionAsError( - new SerializationException(String.format("Failed to retrieve schema for id %s", schemaGuid), e)); - } - - if (payloadSchema == null) { - throw logger.logExceptionAsError( - new SerializationException( - String.format("Payload schema returned as null. Schema type: %s, Schema ID: %s", - registryObject.getSchemaType(), registryObject.getSchemaId()))); - } - - int start = buffer.position() + buffer.arrayOffset(); - int length = buffer.limit() - AbstractDataSerDe.SCHEMA_ID_SIZE; - byte[] b = Arrays.copyOfRange(buffer.array(), start, start + length); - - ByteDecoder byteDecoder = getByteDecoder(registryObject); - return byteDecoder.decodeBytes(b, payloadSchema); - } - - - /** - * Fetches the correct ByteDecoder based on schema type of the message. - * - * @param registryObject object returned from SchemaRegistryClient, contains schema type - * @return ByteDecoder to be used to deserialize encoded payload bytes - * @throws SerializationException if decoder for the required schema type has not been loaded - */ - private ByteDecoder getByteDecoder(SchemaRegistryObject registryObject) throws SerializationException { - ByteDecoder decoder = byteDecoderMap.get(registryObject.getSchemaType()); - if (decoder == null) { - throw logger.logExceptionAsError( - new SerializationException( - String.format("No decoder class found for schema type '%s'.", registryObject.getSchemaType()) - )); - } - return decoder; - } - - /** - * @param buffer full payload bytes - * @return String representation of schema ID - * @throws SerializationException if schema ID could not be extracted from payload - */ - private String getSchemaGuidFromPayload(ByteBuffer buffer) throws SerializationException { - byte[] schemaGuidByteArray = new byte[AbstractDataSerDe.SCHEMA_ID_SIZE]; - try { - buffer.get(schemaGuidByteArray); - } catch (BufferUnderflowException e) { - throw logger.logExceptionAsError(new SerializationException("Payload too short, no readable guid.", e)); - } - - return new String(schemaGuidByteArray, schemaRegistryClient.getEncoding()); - } - - /** - * Loads a ByteDecoder to be used for decoding message payloads of specified schema type. - * @param decoder ByteDecoder class instance to be loaded - */ - protected void loadByteDecoder(ByteDecoder decoder) { - if (decoder == null) { - throw logger.logExceptionAsError(new SerializationException("ByteDecoder cannot be null")); - } - - this.byteDecoderMap.put(decoder.schemaType(), decoder); - this.schemaRegistryClient.addSchemaParser(decoder); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataSerDe.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataSerDe.java deleted file mode 100644 index b2bc450371b63..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataSerDe.java +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.client.SchemaRegistryClient; - -/** - * Common fields and helper methods for both the serializer and the deserializer. - */ -public abstract class AbstractDataSerDe { - private final ClientLogger logger = new ClientLogger(AbstractDataSerDe.class); - - public static final int SCHEMA_ID_SIZE = 32; - - protected SchemaRegistryClient schemaRegistryClient; - - /** - * Base constructor for all SerDe implementations. - * @param schemaRegistryClient client to be used for sending or fetching schemas. - * @throws IllegalArgumentException schemaRegistryClient parameter cannot be null - */ - protected AbstractDataSerDe(SchemaRegistryClient schemaRegistryClient) { - if (schemaRegistryClient == null) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Schema registry client must be initialized and passed into builder.")); - } - this.schemaRegistryClient = schemaRegistryClient; - } - - /** - * Special case for Kafka serializer/deserializer implementations. - */ - // special case for Kafka serializer/deserializer - public AbstractDataSerDe() { - - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataSerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataSerializer.java deleted file mode 100644 index 74784e54e37d6..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractDataSerializer.java +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.client.SchemaRegistryClient; -import com.azure.data.schemaregistry.client.SchemaRegistryClientException; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; - -/** - * Common implementation for all registry-based serializers. - */ -public abstract class AbstractDataSerializer extends AbstractDataSerDe { - private final ClientLogger logger = new ClientLogger(AbstractDataSerializer.class); - - public static final Boolean AUTO_REGISTER_SCHEMAS_DEFAULT = false; - public static final String SCHEMA_GROUP_DEFAULT = "$default"; - - protected ByteEncoder byteEncoder = null; - protected String schemaType; - protected Boolean autoRegisterSchemas = AbstractDataSerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; - protected String schemaGroup = AbstractDataSerializer.SCHEMA_GROUP_DEFAULT; - - /** - * @param schemaRegistryClient registry client to be used for storing schemas. Not null. - */ - public AbstractDataSerializer(SchemaRegistryClient schemaRegistryClient) { - super(schemaRegistryClient); - } - - /** - * Special case constructor for Kafka serializer. - */ - public AbstractDataSerializer() { - } - - /** - * Set ByteEncoder class to be used for serialized objects into bytes - * @param byteEncoder ByteEncoder instance - */ - protected void setByteEncoder(ByteEncoder byteEncoder) { - if (this.byteEncoder != null) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Setting multiple encoders on serializer not permitted")); - } - this.byteEncoder = byteEncoder; - this.schemaType = byteEncoder.schemaType(); - this.schemaRegistryClient.addSchemaParser(byteEncoder); - } - - /** - * Core implementation of registry-based serialization. - * ID for data schema is fetched from the registry and prefixed to the encoded byte array - * representation of the object param. - * - * @param object object to be serialized - * @return byte array containing encoded bytes with prefixed schema ID - * @throws SerializationException if serialization operation fails during runtime. - */ - protected byte[] serializeImpl(Object object) { - if (object == null) { - throw logger.logExceptionAsError(new SerializationException( - "Null object, behavior should be defined in concrete serializer implementation.")); - } - - if (byteEncoder == null) { - throw logger.logExceptionAsError( - new SerializationException("Byte encoder null, serializer must be initialized with a byte encoder.")); - } - - if (schemaType == null) { - schemaType = byteEncoder.schemaType(); - } - - String schemaString = byteEncoder.getSchemaString(object); - String schemaName = byteEncoder.getSchemaName(object); - - try { - String schemaGuid = maybeRegisterSchema( - this.schemaGroup, schemaName, schemaString, this.schemaType); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteBuffer guidBuffer = ByteBuffer.allocate(AbstractDataSerDe.SCHEMA_ID_SIZE) - .put(schemaGuid.getBytes(StandardCharsets.UTF_8)); - out.write(guidBuffer.array()); - byteEncoder.encode(object).writeTo(out); - return out.toByteArray(); - } catch (SchemaRegistryClientException | IOException e) { - if (this.autoRegisterSchemas) { - throw logger.logExceptionAsError( - new SerializationException( - String.format("Error registering Avro schema. Group: %s, name: %s", schemaGroup, schemaName), - e)); - } else { - throw logger.logExceptionAsError( - new SerializationException( - String.format("Error retrieving Avro schema. Group: %s, name: %s", schemaGroup, schemaName), - e)); - } - } - } - - /** - * If auto-registering is enabled, register schema against SchemaRegistryClient. - * If auto-registering is disabled, fetch schema ID for provided schema. Requires pre-registering of schema - * against registry. - * - * @param schemaGroup Schema group where schema should be registered. - * @param schemaName name of schema - * @param schemaString string representation of schema being stored - must match group schema type - * @param schemaType type of schema being stored, e.g. avro - * @return string representation of schema ID - * @throws SchemaRegistryClientException upon registry client operation failure - */ - private String maybeRegisterSchema( - String schemaGroup, String schemaName, String schemaString, String schemaType) - throws SchemaRegistryClientException { - if (this.autoRegisterSchemas) { - return this.schemaRegistryClient.register(schemaGroup, schemaName, schemaString, schemaType) - .getSchemaId(); - } else { - return this.schemaRegistryClient.getSchemaId( - schemaGroup, schemaName, schemaString, schemaType); - } - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/ByteDecoder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/ByteDecoder.java deleted file mode 100644 index 70a06f339afbf..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/ByteDecoder.java +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -/** - * An interface defining operations required for registry deserializer to convert encoded bytes to Java object. - */ -public interface ByteDecoder extends Codec { - /** - * Decodes byte array into Object given provided schema object. - * @param encodedBytes payload to be decoded - * @param schemaObject object used to decode the payload - * @return deserialized object - * @throws SerializationException if decode operation fails - */ - Object decodeBytes(byte[] encodedBytes, Object schemaObject) throws SerializationException; -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/ByteEncoder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/ByteEncoder.java deleted file mode 100644 index 65116e7722507..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/ByteEncoder.java +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import java.io.ByteArrayOutputStream; - -/** - * An interface defining operations required for registry serializer to convert object to bytes. - */ -public interface ByteEncoder extends Codec { - /** - * Return schema name for storing in registry store - * @param object Schema object - * Refer to Schema Registry documentation for information on schema grouping and naming. - * - * @return schema name - * @throws SerializationException runtime exception in error cases - */ - String getSchemaName(Object object) throws SerializationException; - - /** - * Returns string representation of schema object to be stored in the service. - * - * @param object Schema object used to generate schema string - * @return String representation of schema object parameter - * @throws SerializationException if generating string representation of schema fails - */ - String getSchemaString(Object object); - - // TODO: Method does not currently require schema object to be passed since schemas can be derived from - // Avro objects. JSON implementation would be the same. - /** - * Converts object into stream containing the encoded representation of the object. - * @param object Object to be encoded into byte stream - * @return output stream containing byte representation of object - * @throws SerializationException if generating byte representation of object fails - */ - ByteArrayOutputStream encode(Object object); -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/Codec.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/Codec.java deleted file mode 100644 index cf99962f9ff6f..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/Codec.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -/** - * Base interface for all ByteEncoder and ByteDecoder interfaces - */ -public interface Codec { - /** - * @return String representation of schema type, e.g. "avro" or "json". - * - * Utilized by schema registry store and client as non-case-sensitive tags for - * schemas of a specific type. - */ - String schemaType(); - - /** - * Parses string representation of schema into schema Object - * @param schemaString string representation of schema - * @return schema object to be used for decoding payloads - */ - Object parseSchemaString(String schemaString); -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java new file mode 100644 index 0000000000000..5f305c980d78b --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java @@ -0,0 +1,314 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.logging.ClientLogger; +import com.azure.data.schemaregistry.models.SchemaProperties; +import com.azure.data.schemaregistry.models.SerializationType; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentSkipListMap; +import java.util.function.Function; + +import com.azure.data.schemaregistry.implementation.AzureSchemaRegistry; +import com.azure.data.schemaregistry.implementation.models.SchemaId; +import reactor.core.publisher.Mono; + +/** + * HTTP-based client that interacts with Azure Schema Registry service to store and retrieve schemas on demand. + * @see SchemaRegistryClientBuilder Follows builder pattern for object instantiation + */ +@ServiceClient(builder = SchemaRegistryClientBuilder.class, isAsync = true) +public final class SchemaRegistryAsyncClient { + + private final ClientLogger logger = new ClientLogger(SchemaRegistryAsyncClient.class); + + static final Charset SCHEMA_REGISTRY_SERVICE_ENCODING = StandardCharsets.UTF_8; + static final int MAX_SCHEMA_MAP_SIZE_DEFAULT = 1000; + static final int MAX_SCHEMA_MAP_SIZE_MINIMUM = 10; + + private final AzureSchemaRegistry restService; + private final Integer maxSchemaMapSize; + private final ConcurrentSkipListMap> typeParserMap; + private final Map idCache; + private final Map schemaStringCache; + + SchemaRegistryAsyncClient( + AzureSchemaRegistry restService, + int maxSchemaMapSize, + ConcurrentSkipListMap> typeParserMap) { + this.restService = restService; + this.maxSchemaMapSize = maxSchemaMapSize; + this.typeParserMap = typeParserMap; + this.idCache = new ConcurrentHashMap<>(); + this.schemaStringCache = new ConcurrentHashMap<>(); + } + + // testing - todo remove constructor and replace with mock + SchemaRegistryAsyncClient( + AzureSchemaRegistry restService, + Map idCache, + Map schemaStringCache, + ConcurrentSkipListMap> typeParserMap) { + this.restService = restService; // mockable + this.idCache = idCache; + this.schemaStringCache = schemaStringCache; + this.typeParserMap = typeParserMap; + this.maxSchemaMapSize = MAX_SCHEMA_MAP_SIZE_DEFAULT; + } + + /** + * Registers a schema with the provided schema details. + * @param schemaGroup The schema group. + * @param schemaName The schema name. + * @param schemaString The string representation of the schema. + * @param serializationType The serialization type of this schema. + * + * @return The {@link SchemaProperties} of a successfully registered schema. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono registerSchema( + String schemaGroup, String schemaName, String schemaString, SerializationType serializationType) { + + if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { + logger.verbose( + "Cache hit schema string. Group: '{}', name: '{}', schema type: '{}', payload: '{}'", + schemaGroup, schemaName, serializationType, schemaString); + return Mono.fromCallable( + () -> schemaStringCache.get(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))); + } + + return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType) + .map(response -> response.getValue()); + } + + /** + * @param schemaGroup The schema group. + * @param schemaName The schema name. + * @param schemaString The string representation of the schema. + * @param serializationType The serialization type of this schema. + * + * @return The schema properties on successful registration of the schema. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> registerSchemaWithResponse(String schemaGroup, String schemaName, + String schemaString, SerializationType serializationType) { + return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType, Context.NONE); + } + + Mono> registerSchemaWithResponse(String schemaGroup, String schemaName, + String schemaString, SerializationType serializationType, Context context) { + logger.verbose( + "Registering schema. Group: '{}', name: '{}', serialization type: '{}', payload: '{}'", + schemaGroup, schemaName, serializationType, schemaString); + + return this.restService + .getSchemas().registerWithResponseAsync(schemaGroup, schemaName, + com.azure.data.schemaregistry.implementation.models.SerializationType.AVRO, schemaString) + .handle((response, sink) -> { + if (response == null) { + sink.error(logger.logExceptionAsError( + new NullPointerException("Client returned null response"))); + return; + } + + if (response.getStatusCode() == 400) { + sink.error(logger.logExceptionAsError( + new IllegalStateException("Invalid schema registration attempted"))); + return; + } + + SchemaId schemaId = response.getValue(); + + SchemaProperties registered = new SchemaProperties(schemaId.getId(), + serializationType, + schemaName, + schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING)); + + resetIfNeeded(); + schemaStringCache + .putIfAbsent(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString), registered); + logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); + SimpleResponse schemaRegistryObjectSimpleResponse = new SimpleResponse<>( + response.getRequest(), response.getStatusCode(), + response.getHeaders(), registered); + sink.next(schemaRegistryObjectSimpleResponse); + }); + } + + /** + * Gets the schema properties of the schema associated with the unique schemaId. + * @param schemaId The unique identifier of the schema. + * + * @return The {@link SchemaProperties} associated with the given {@code schemaId}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getSchema(String schemaId) { + if (idCache.containsKey(schemaId)) { + logger.verbose("Cache hit for schema id '{}'", schemaId); + return Mono.fromCallable(() -> idCache.get(schemaId)); + } + return getSchemaWithResponse(schemaId).map(Response::getValue); + } + + /** + * Gets the schema properties of the schema associated with the unique schemaId. + * @param schemaId The unique identifier of the schema. + * + * @return The {@link SchemaProperties} associated with the given {@code schemaId} along with the HTTP + * response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getSchemaWithResponse(String schemaId) { + return getSchemaWithResponse(schemaId, Context.NONE); + } + + Mono> getSchemaWithResponse(String schemaId, Context context) { + Objects.requireNonNull(schemaId, "'schemaId' should not be null"); + return this.restService.getSchemas().getByIdWithResponseAsync(schemaId) + .handle((response, sink) -> { + if (response == null) { + sink.error(logger.logExceptionAsError( + new NullPointerException("Client returned null response"))); + return; + } + + if (response.getStatusCode() == 404) { + sink.error(logger.logExceptionAsError( + new IllegalStateException(String.format("Schema does not exist, id %s", schemaId)))); + return; + } + + SerializationType serializationType = + SerializationType.fromString(response.getDeserializedHeaders().getXSchemaType()); + + SchemaProperties schemaObject = new SchemaProperties(schemaId, + serializationType, + null, + response.getValue().getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING)); + + resetIfNeeded(); + idCache.putIfAbsent(schemaId, schemaObject); + logger.verbose("Cached schema object. Path: '{}'", schemaId); + SimpleResponse schemaRegistryObjectSimpleResponse = new SimpleResponse<>( + response.getRequest(), response.getStatusCode(), + response.getHeaders(), schemaObject); + sink.next(schemaRegistryObjectSimpleResponse); + }); + } + + /** + * @param schemaGroup The schema group. + * @param schemaName The schema name. + * @param schemaString The string representation of the schema. + * @param serializationType The serialization type of this schema. + * + * @return The unique identifier for this schema. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getSchemaId(String schemaGroup, String schemaName, String schemaString, + SerializationType serializationType) { + + String schemaStringCacheKey = getSchemaStringCacheKey(schemaGroup, schemaName, schemaString); + if (schemaStringCache.containsKey(schemaStringCacheKey)) { + logger.verbose("Cache hit schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); + return Mono.fromCallable(() -> schemaStringCache.get(schemaStringCacheKey).getSchemaId()); + } + + return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, serializationType) + .map(response -> response.getValue()); + } + + /** + * @param schemaGroup The schema group. + * @param schemaName The schema name. + * @param schemaString The string representation of the schema. + * @param serializationType The serialization type of this schema. + * + * @return The unique identifier for this schema. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, + SerializationType serializationType) { + return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, serializationType, Context.NONE); + } + + Mono> getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, + SerializationType serializationType, Context context) { + + return this.restService.getSchemas() + .queryIdByContentWithResponseAsync(schemaGroup, schemaName, + com.azure.data.schemaregistry.implementation.models.SerializationType.AVRO, schemaString) + .handle((response, sink) -> { + if (response == null) { + sink.error(logger.logExceptionAsError( + new NullPointerException("Client returned null response"))); + return; + } + + if (response.getStatusCode() == 404) { + sink.error( + logger.logExceptionAsError(new IllegalStateException("Existing matching schema not found."))); + return; + } + + SchemaId schemaId = response.getValue(); + + resetIfNeeded(); + schemaStringCache.putIfAbsent( + getSchemaStringCacheKey(schemaGroup, schemaName, schemaString), + new SchemaProperties( + schemaId.getId(), + serializationType, + schemaName, + schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING))); + logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); + + SimpleResponse schemaIdResponse = new SimpleResponse<>( + response.getRequest(), response.getStatusCode(), + response.getHeaders(), schemaId.getId()); + sink.next(schemaIdResponse); + }); + } + + /** + * Explicit call to clear all caches. + */ + void clearCache() { + idCache.clear(); + schemaStringCache.clear(); + typeParserMap.clear(); + } + + // TODO: max age for schema maps? or will schemas always be immutable? + + /** + * Checks if caches should be reinitialized to satisfy initial configuration + */ + private void resetIfNeeded() { + // todo add verbose log + if (idCache.size() > this.maxSchemaMapSize) { + idCache.clear(); + logger.verbose("Cleared schema ID cache."); + } + if (schemaStringCache.size() > this.maxSchemaMapSize) { + schemaStringCache.clear(); + logger.verbose("Cleared schema string cache."); + } + } + + private String getSchemaStringCacheKey(String schemaGroup, String schemaName, String schemaString) { + return schemaGroup + schemaName + schemaString; + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClient.java new file mode 100644 index 0000000000000..39f2c8e7be137 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClient.java @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry; + +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.data.schemaregistry.models.SchemaProperties; +import com.azure.data.schemaregistry.models.SerializationType; + +/** + * HTTP-based client that interacts with Azure Schema Registry service to store and retrieve schemas on demand. + * + * @see SchemaRegistryClientBuilder Follows builder pattern for object instantiation + */ +@ServiceClient(builder = SchemaRegistryClientBuilder.class) +public final class SchemaRegistryClient { + private final SchemaRegistryAsyncClient asyncClient; + + SchemaRegistryClient(SchemaRegistryAsyncClient asyncClient) { + this.asyncClient = asyncClient; + } + + /** + * + * @param schemaGroup The schema group. + * @param schemaName The schema name. + * @param schemaString The string representation of the schema. + * @param serializationType The serialization type of this schema. + * @return The schema properties on successful registration of the schema. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SchemaProperties registerSchema(String schemaGroup, String schemaName, String schemaString, + SerializationType serializationType) { + return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType, Context.NONE) + .getValue(); + } + + /** + * + * @param schemaGroup The schema group. + * @param schemaName The schema name. + * @param schemaString The string representation of the schema. + * @param serializationType The serialization type of this schema. + * @param context The context to pass to the Http pipeline. + * @return The schema properties on successful registration of the schema. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response registerSchemaWithResponse(String schemaGroup, String schemaName, + String schemaString, SerializationType serializationType, Context context) { + return this.asyncClient.registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType, + context).block(); + } + + /** + * Gets the schema properties of the schema associated with the unique schemaId. + * @param schemaId The unique identifier of the schema. + * + * @return The {@link SchemaProperties} associated with the given {@code schemaId}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SchemaProperties getSchema(String schemaId) { + return getSchemaWithResponse(schemaId, Context.NONE).getValue(); + } + + /** + * Gets the schema properties of the schema associated with the unique schemaId. + * @param schemaId The unique identifier of the schema. + * @param context The context to pass to the Http pipeline. + * @return The {@link SchemaProperties} associated with the given {@code schemaId} along with the HTTP + * response. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getSchemaWithResponse(String schemaId, Context context) { + return this.asyncClient.getSchemaWithResponse(schemaId).block(); + } + + /** + * + * @param schemaGroup The schema group. + * @param schemaName The schema name. + * @param schemaString The string representation of the schema. + * @param serializationType The serialization type of this schema. + * + * @return The unique identifier for this schema. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public String getSchemaId(String schemaGroup, String schemaName, String schemaString, + SerializationType serializationType) { + return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, serializationType, Context.NONE) + .getValue(); + } + + /** + * + * @param schemaGroup The schema group. + * @param schemaName The schema name. + * @param schemaString The string representation of the schema. + * @param serializationType The serialization type of this schema. + * @param context The context to pass to the Http pipeline. + * @return The unique identifier for this schema. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, + SerializationType serializationType, Context context) { + return this.asyncClient + .getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, serializationType, context).block(); + } + + void clearCache() { + this.asyncClient.clearCache(); + } + +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClientBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java similarity index 65% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClientBuilder.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java index 4dcbb71fa9253..eb54892a66830 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClientBuilder.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client; +package com.azure.data.schemaregistry; import com.azure.core.annotation.ServiceClientBuilder; import com.azure.core.credential.TokenCredential; @@ -23,10 +23,8 @@ import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.Codec; -import com.azure.data.schemaregistry.client.implementation.AzureSchemaRegistryRestService; -import com.azure.data.schemaregistry.client.implementation.AzureSchemaRegistryRestServiceClientBuilder; - +import com.azure.data.schemaregistry.implementation.AzureSchemaRegistry; +import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryBuilder; import java.net.MalformedURLException; import java.net.URL; import java.time.temporal.ChronoUnit; @@ -38,11 +36,11 @@ import java.util.function.Function; /** - * Builder implementation for {@link CachedSchemaRegistryClient}. + * Builder implementation for {@link SchemaRegistryAsyncClient}. */ -@ServiceClientBuilder(serviceClients = CachedSchemaRegistryClient.class) -public class CachedSchemaRegistryClientBuilder { - private final ClientLogger logger = new ClientLogger(CachedSchemaRegistryClientBuilder.class); +@ServiceClientBuilder(serviceClients = SchemaRegistryAsyncClient.class) +public class SchemaRegistryClientBuilder { + private final ClientLogger logger = new ClientLogger(SchemaRegistryClientBuilder.class); private static final String DEFAULT_SCOPE = "https://eventhubs.azure.net/.default"; private static final String CLIENT_PROPERTIES = "azure-data-schemaregistry-client.properties"; @@ -57,6 +55,7 @@ public class CachedSchemaRegistryClientBuilder { private final String clientVersion; private String schemaRegistryUrl; + private String host; private HttpClient httpClient; private Integer maxSchemaMapSize; private TokenCredential credential; @@ -67,7 +66,7 @@ public class CachedSchemaRegistryClientBuilder { /** * Constructor for CachedSchemaRegistryClientBuilder. Supplies client defaults. */ - public CachedSchemaRegistryClientBuilder() { + public SchemaRegistryClientBuilder() { this.policies = new ArrayList<>(); this.httpLogOptions = new HttpLogOptions(); this.maxSchemaMapSize = null; @@ -77,7 +76,7 @@ public CachedSchemaRegistryClientBuilder() { this.retryPolicy = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); HttpHeaders headers = new HttpHeaders(); - headers.put("api-version", "2017-04"); + headers.put("api-version", "2020-09-01-preview"); policies.add(new AddHeadersPolicy(headers)); Map properties = CoreUtils.getProperties(CLIENT_PROPERTIES); @@ -88,16 +87,17 @@ public CachedSchemaRegistryClientBuilder() { /** * Sets the service endpoint for the Azure Schema Registry instance. * - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. + * @return The updated {@link SchemaRegistryClientBuilder} object. * @param schemaRegistryUrl The URL of the Azure Schema Registry instance * @throws NullPointerException if {@code schemaRegistryUrl} is null * @throws IllegalArgumentException if {@code schemaRegistryUrl} cannot be parsed into a valid URL */ - public CachedSchemaRegistryClientBuilder endpoint(String schemaRegistryUrl) { + public SchemaRegistryClientBuilder endpoint(String schemaRegistryUrl) { Objects.requireNonNull(schemaRegistryUrl, "'schemaRegistryUrl' cannot be null."); try { - new URL(schemaRegistryUrl); + URL url = new URL(schemaRegistryUrl); + this.host = url.getHost(); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning( new IllegalArgumentException("'schemaRegistryUrl' must be a valid URL.", ex)); @@ -115,18 +115,18 @@ public CachedSchemaRegistryClientBuilder endpoint(String schemaRegistryUrl) { /** * Sets schema cache size limit. If limit is exceeded on any cache, all caches are recycled. * - * @param maxSchemaMapSize max size for internal schema caches in {@link CachedSchemaRegistryClient} - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. - * @throws IllegalArgumentException on invalid maxSchemaMapSize value + * @param maxCacheSize max size for internal schema caches in {@link SchemaRegistryAsyncClient} + * @return The updated {@link SchemaRegistryClientBuilder} object. + * @throws IllegalArgumentException on invalid maxCacheSize value */ - public CachedSchemaRegistryClientBuilder maxSchemaMapSize(int maxSchemaMapSize) { - if (maxSchemaMapSize < CachedSchemaRegistryClient.MAX_SCHEMA_MAP_SIZE_MINIMUM) { + public SchemaRegistryClientBuilder maxCacheSize(int maxCacheSize) { + if (maxCacheSize < SchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM) { throw logger.logExceptionAsError(new IllegalArgumentException( String.format("Schema map size must be greater than %s entries", - CachedSchemaRegistryClient.MAX_SCHEMA_MAP_SIZE_MINIMUM))); + SchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM))); } - this.maxSchemaMapSize = maxSchemaMapSize; + this.maxSchemaMapSize = maxCacheSize; return this; } @@ -134,9 +134,9 @@ public CachedSchemaRegistryClientBuilder maxSchemaMapSize(int maxSchemaMapSize) * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param httpClient The HTTP client to use for requests. - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. + * @return The updated {@link SchemaRegistryClientBuilder} object. */ - public CachedSchemaRegistryClientBuilder httpClient(HttpClient httpClient) { + public SchemaRegistryClientBuilder httpClient(HttpClient httpClient) { this.httpClient = httpClient; return this; } @@ -144,12 +144,12 @@ public CachedSchemaRegistryClientBuilder httpClient(HttpClient httpClient) { /** * Sets the HTTP pipeline to use for the service client. *

- * If {@code pipeline} is set, all other HTTP settings are ignored to build {@link CachedSchemaRegistryClient}. + * If {@code pipeline} is set, all other HTTP settings are ignored to build {@link SchemaRegistryAsyncClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. + * @return The updated {@link SchemaRegistryClientBuilder} object. */ - public CachedSchemaRegistryClientBuilder pipeline(HttpPipeline httpPipeline) { + public SchemaRegistryClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } @@ -161,13 +161,13 @@ public CachedSchemaRegistryClientBuilder pipeline(HttpPipeline httpPipeline) { /** * Sets the {@link TokenCredential} to use when authenticating HTTP requests for this - * {@link CachedSchemaRegistryClient}. + * {@link SchemaRegistryAsyncClient}. * * @param credential {@link TokenCredential} - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. + * @return The updated {@link SchemaRegistryClientBuilder} object. * @throws NullPointerException If {@code credential} is {@code null} */ - public CachedSchemaRegistryClientBuilder credential(TokenCredential credential) { + public SchemaRegistryClientBuilder credential(TokenCredential credential) { this.credential = Objects.requireNonNull(credential, "'credential' cannot be null."); return this; } @@ -178,9 +178,9 @@ public CachedSchemaRegistryClientBuilder credential(TokenCredential credential) *

If logLevel is not provided, default value of {@link HttpLogDetailLevel#NONE} is set.

* * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. + * @return The updated {@link SchemaRegistryClientBuilder} object. */ - public CachedSchemaRegistryClientBuilder httpLogOptions(HttpLogOptions logOptions) { + public SchemaRegistryClientBuilder httpLogOptions(HttpLogOptions logOptions) { this.httpLogOptions = logOptions; return this; } @@ -188,12 +188,12 @@ public CachedSchemaRegistryClientBuilder httpLogOptions(HttpLogOptions logOption /** * Sets the {@link RetryPolicy} that is used when each request is sent. *

- * The default retry policy will be used if not provided to build {@link CachedSchemaRegistryClient} . + * The default retry policy will be used if not provided to build {@link SchemaRegistryAsyncClient} . * * @param retryPolicy user's retry policy applied to each request. - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. + * @return The updated {@link SchemaRegistryClientBuilder} object. */ - public CachedSchemaRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) { + public SchemaRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } @@ -202,53 +202,26 @@ public CachedSchemaRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) { * Adds a policy to the set of existing policies that are executed after required policies. * * @param policy The retry policy for service requests. - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. + * @return The updated {@link SchemaRegistryClientBuilder} object. * @throws NullPointerException If {@code policy} is {@code null}. */ - public CachedSchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) { + public SchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy, "'policy' cannot be null.")); return this; } /** - * Loads a parser method Function object used to convert schema strings returned from the Schema Registry - * service into useable schema objects. - * - * Any com.azure.data.schemaregistry.ByteEncoder or com.azure.data.schemaregistry.ByteDecoder class will implement - * - schemaType(), which specifies schema type, and - * - parseSchemaString(), which parses schemas of the specified schema type from String to Object. - * - * The parseMethod argument should be a stateless, idempotent function. - * - * @param codec Codec class implementation - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. - */ - public CachedSchemaRegistryClientBuilder addSchemaParser(Codec codec) { - Objects.requireNonNull(codec, "'codec' cannot be null."); - if (CoreUtils.isNullOrEmpty(codec.schemaType())) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Serialization type cannot be null or empty.")); - } - if (this.typeParserMap.containsKey(codec.schemaType())) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Multiple parse methods for single serialization type may not be added.")); - } - this.typeParserMap.put(codec.schemaType(), codec::parseSchemaString); - return this; - } - - /** - * Creates a {@link CachedSchemaRegistryClient} based on options set in the builder. - * Every time {@code buildClient()} is called a new instance of {@link CachedSchemaRegistryClient} is created. + * Creates a {@link SchemaRegistryAsyncClient} based on options set in the builder. + * Every time {@code buildClient()} is called a new instance of {@link SchemaRegistryAsyncClient} is created. * * If {@link #pipeline(HttpPipeline) pipeline} is set, then all HTTP pipeline related settings are ignored - * endpoint} are when creating the {@link CachedSchemaRegistryClient client}. + * endpoint} are when creating the {@link SchemaRegistryAsyncClient client}. * - * @return A {@link CachedSchemaRegistryClient} with the options set from the builder. + * @return A {@link SchemaRegistryAsyncClient} with the options set from the builder. * @throws NullPointerException if parameters are incorrectly set. * @throws IllegalArgumentException if credential is not set. */ - public CachedSchemaRegistryClient buildClient() { + public SchemaRegistryAsyncClient buildAsyncClient() { // Authentications if (credential == null) { // Throw exception that credential and tokenCredential cannot be null @@ -285,15 +258,25 @@ public CachedSchemaRegistryClient buildClient() { .build(); } - AzureSchemaRegistryRestService restService = new AzureSchemaRegistryRestServiceClientBuilder() - .host(this.schemaRegistryUrl) + AzureSchemaRegistry restService = new AzureSchemaRegistryBuilder() + .endpoint(host) .pipeline(pipeline) .buildClient(); this.maxSchemaMapSize = this.maxSchemaMapSize != null ? this.maxSchemaMapSize - : CachedSchemaRegistryClient.MAX_SCHEMA_MAP_SIZE_DEFAULT; + : SchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_DEFAULT; - return new CachedSchemaRegistryClient(restService, maxSchemaMapSize, typeParserMap); + return new SchemaRegistryAsyncClient(restService, maxSchemaMapSize, typeParserMap); + } + + /** + * Creates synchronous {@link SchemaRegistryClient} instance. + * See async builder method for options validation. + * + * @return {@link SchemaRegistryClient} with the options set from the builder. + */ + public SchemaRegistryClient buildClient() { + return new SchemaRegistryClient(this.buildAsyncClient()); } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SerializationException.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SerializationException.java deleted file mode 100644 index a4f6b5f6065e3..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SerializationException.java +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.core.exception.AzureException; - -/** - * Exception thrown by Schema Registry serializer/deserializer implementations for runtime error cases. - */ -public class SerializationException extends AzureException { - /** - * @param s error message explaining serde operation failure - */ - public SerializationException(String s) { - super(s); - } - - /** - * @param s error message explaining serde operation failure - * @param cause Throwable cause of serialization failure - */ - public SerializationException(String s, Throwable cause) { - super(s, cause); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClient.java deleted file mode 100644 index 07c2a53838bf3..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClient.java +++ /dev/null @@ -1,295 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client; - -import com.azure.core.annotation.ServiceClient; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.util.CoreUtils; -import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.Codec; -import com.azure.data.schemaregistry.client.implementation.AzureSchemaRegistryRestService; -import com.azure.data.schemaregistry.client.implementation.models.CreateSchemaResponse; -import com.azure.data.schemaregistry.client.implementation.models.GetIdBySchemaContentResponse; -import com.azure.data.schemaregistry.client.implementation.models.GetSchemaByIdResponse; -import com.azure.data.schemaregistry.client.implementation.models.SchemaId; - -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentSkipListMap; -import java.util.function.Function; - -/** - * HTTP-based client that interacts with Azure Schema Registry service to store and retrieve schemas on demand. - *

- * Utilizes in-memory {@link Map} caching to minimize network I/O. Max size can be configured when instantiating by - * using {@link CachedSchemaRegistryClientBuilder#maxSchemaMapSize}, otherwise {@code 1000} will be used as the default. - *

- * Two maps are maintained. - *

    - *
  • SchemaRegistryObject cache by GUID - stores GUIDs previously seen in payloads.
  • - *
  • SchemaRegistryObject cache by schema string - minimizes HTTP calls when sending payloads of same schema.
  • - *
- *

- * - * @see SchemaRegistryClient Implements SchemaRegistryClient interface to allow for testing with mock - * @see CachedSchemaRegistryClientBuilder Follows builder pattern for object instantiation - */ -@ServiceClient( - builder = CachedSchemaRegistryClientBuilder.class, - serviceInterfaces = AzureSchemaRegistryRestService.class) -public final class CachedSchemaRegistryClient implements SchemaRegistryClient { - private final ClientLogger logger = new ClientLogger(CachedSchemaRegistryClient.class); - - public static final Charset SCHEMA_REGISTRY_SERVICE_ENCODING = StandardCharsets.UTF_8; - static final int MAX_SCHEMA_MAP_SIZE_DEFAULT = 1000; - static final int MAX_SCHEMA_MAP_SIZE_MINIMUM = 10; - private static final Duration HTTP_REQUEST_TIMEOUT = Duration.ofMillis(20000); - - private final AzureSchemaRegistryRestService restService; - private final Integer maxSchemaMapSize; - private final ConcurrentSkipListMap> typeParserMap; - private final Map idCache; - private final Map schemaStringCache; - - CachedSchemaRegistryClient( - AzureSchemaRegistryRestService restService, - int maxSchemaMapSize, - ConcurrentSkipListMap> typeParserMap) { - this.restService = restService; - this.maxSchemaMapSize = maxSchemaMapSize; - this.typeParserMap = typeParserMap; - this.idCache = new ConcurrentHashMap<>(); - this.schemaStringCache = new ConcurrentHashMap<>(); - } - - // testing - todo remove constructor and replace with mock - CachedSchemaRegistryClient( - AzureSchemaRegistryRestService restService, - Map idCache, - Map schemaStringCache, - ConcurrentSkipListMap> typeParserMap) { - this.restService = restService; // mockable - this.idCache = idCache; - this.schemaStringCache = schemaStringCache; - this.typeParserMap = typeParserMap; - this.maxSchemaMapSize = MAX_SCHEMA_MAP_SIZE_DEFAULT; - } - - /** - * @return Azure Schema Registry service string encoding - */ - @Override - public Charset getEncoding() { - return CachedSchemaRegistryClient.SCHEMA_REGISTRY_SERVICE_ENCODING; - } - - /** - * @param codec Codec class implementation - * @throws IllegalArgumentException on bad schema type or if parser for schema type has already been registered - */ - public void addSchemaParser(Codec codec) { - if (CoreUtils.isNullOrEmpty(codec.schemaType())) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Serialization type cannot be null or empty.")); - } - if (this.typeParserMap.containsKey(codec.schemaType())) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Multiple parse methods for single serialization type may not be added.")); - } - this.typeParserMap.putIfAbsent(codec.schemaType(), codec::parseSchemaString); - logger.verbose( - "Loaded parser for '{}' serialization format.", codec.schemaType().toLowerCase(Locale.ROOT)); - } - - @Override - public SchemaRegistryObject register( - String schemaGroup, String schemaName, String schemaString, String schemaType) { - if (schemaStringCache.containsKey(schemaString)) { - logger.verbose( - "Cache hit schema string. Group: '{}', name: '{}', schema type: '{}', payload: '{}'", - schemaGroup, schemaName, schemaType, schemaString); - return schemaStringCache.get(schemaString); - } - - logger.verbose( - "Registering schema. Group: '{}', name: '{}', serialization type: '{}', payload: '{}'", - schemaGroup, schemaName, schemaType, schemaString); - - CreateSchemaResponse response; - try { - response = this.restService.createSchemaWithResponseAsync(schemaGroup, schemaName, schemaType, schemaString) - .block(HTTP_REQUEST_TIMEOUT); - } catch (HttpResponseException e) { - throw logger.logExceptionAsError( - new SchemaRegistryClientException("Register operation failed, unexpected service response.", e)); - } - - if (response == null) { - throw logger.logExceptionAsError(new SchemaRegistryClientException("Client returned null response")); - } - - if (response.getStatusCode() == 400) { - throw logger.logExceptionAsError( - new SchemaRegistryClientException("Invalid schema registration attempted")); - } - - SchemaId schemaId = response.getValue(); - - SchemaRegistryObject registered = new SchemaRegistryObject(schemaId.getId(), - schemaType, - schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), - getParseFunc(schemaType)); - - resetIfNeeded(); - schemaStringCache.putIfAbsent(schemaString, registered); - logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); - return registered; - } - - @Override - public SchemaRegistryObject getSchemaByGuid(String schemaId) { - Objects.requireNonNull(schemaId, "'schemaId' should not be null"); - - if (idCache.containsKey(schemaId)) { - logger.verbose("Cache hit for schema id '{}'", schemaId); - return idCache.get(schemaId); - } - - GetSchemaByIdResponse response; - try { - response = this.restService.getSchemaByIdWithResponseAsync(schemaId).block(HTTP_REQUEST_TIMEOUT); - } catch (HttpResponseException e) { - throw logger.logExceptionAsError( - new SchemaRegistryClientException("Fetching schema failed, unexpected service response.", e)); - } - - if (response == null) { - throw logger.logExceptionAsError(new SchemaRegistryClientException("Client returned null response")); - } - - if (response.getStatusCode() == 404) { - throw logger.logExceptionAsError( - new SchemaRegistryClientException(String.format("Schema does not exist, id %s", schemaId)) - ); - } - - String schemaType = response.getDeserializedHeaders().getXSchemaType(); - - SchemaRegistryObject schemaObject = new SchemaRegistryObject(schemaId, - schemaType, - response.getValue().getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), - getParseFunc(schemaType)); - - resetIfNeeded(); - idCache.putIfAbsent(schemaId, schemaObject); - logger.verbose("Cached schema object. Path: '{}'", schemaId); - return schemaObject; - } - - @Override - public String getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) { - if (schemaStringCache.containsKey(schemaString)) { - logger.verbose("Cache hit schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); - return schemaStringCache.get(schemaString).getSchemaId(); - } - - GetIdBySchemaContentResponse response; - try { - response = this.restService - .getIdBySchemaContentWithResponseAsync(schemaGroup, schemaName, schemaType, schemaString) - .block(HTTP_REQUEST_TIMEOUT); - } catch (HttpResponseException e) { - throw logger.logExceptionAsError(new SchemaRegistryClientException( - String.format( - "Failed to fetch ID for schema, unexpected service response. Group: '%s', name: '%s'", - schemaGroup, schemaName), - e)); - } - - if (response == null) { - throw logger.logExceptionAsError(new SchemaRegistryClientException("Client returned null response")); - } - - if (response.getStatusCode() == 404) { - throw logger.logExceptionAsError(new SchemaRegistryClientException("Existing matching schema not found.")); - } - - SchemaId schemaId = response.getValue(); - - resetIfNeeded(); - schemaStringCache.putIfAbsent( - schemaString, - new SchemaRegistryObject( - schemaId.getId(), - schemaType, - schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), - getParseFunc(schemaType))); - logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); - return schemaId.getId(); - } - - @Override - public String deleteSchemaVersion(String schemaGroup, String schemaName, int version) { - throw logger.logExceptionAsError(new UnsupportedOperationException()); - } - - @Override - public String deleteLatestSchemaVersion(String schemaGroup, String schemaName) { - throw logger.logExceptionAsError(new UnsupportedOperationException()); - } - - @Override - public List deleteSchema(String schemaGroup, String schemaName) { - throw logger.logExceptionAsError(new UnsupportedOperationException()); - } - - /** - * Explicit call to clear all caches. - */ - public void reset() { - idCache.clear(); - schemaStringCache.clear(); - typeParserMap.clear(); - } - - // TODO: max age for schema maps? or will schemas always be immutable? - /** - * Checks if caches should be reinitialized to satisfy initial configuration - */ - private void resetIfNeeded() { - // todo add verbose log - if (idCache.size() > this.maxSchemaMapSize) { - idCache.clear(); - logger.verbose("Cleared schema ID cache."); - } - if (schemaStringCache.size() > this.maxSchemaMapSize) { - schemaStringCache.clear(); - logger.verbose("Cleared schema string cache."); - } - } - - /** - * Return stored parse function for parsing schema payloads of specified schema type - * - * @param schemaType schema type of payload to be deserialized - * @return parse method for deserializing schema string - */ - private Function getParseFunc(String schemaType) { - Function parseFunc = typeParserMap.get(schemaType); - - if (parseFunc == null) { - throw logger.logExceptionAsError(new SchemaRegistryClientException( - String.format("Unexpected serialization type '%s' received. Currently loaded parsers: %s", - schemaType, - typeParserMap.keySet().toString()))); - } - return parseFunc; - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryClient.java deleted file mode 100644 index 5443ded211965..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryClient.java +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client; - -import com.azure.data.schemaregistry.Codec; - -import java.nio.charset.Charset; -import java.util.List; - -/** - * Interface that defines operation for registering and fetching schemas and schema information to and from a - * schema registry store. - */ -public interface SchemaRegistryClient { - - /** - * Encoding used by registry client implementation. - * @return encoding for registry client implementation - */ - Charset getEncoding(); - - /** - * Loads function for a given schema type that can parse the registry-stored schema string into - * usable schema object. - * - * Any com.azure.data.schemaregistry.ByteEncoder or com.azure.data.schemaregistry.ByteDecoder class will implement - * - schemaType(), which specifies schema type, and - * - parseSchemaString(), which parses schemas of the specified schema type from String to Object. - * - * @param codec Codec class implementation - */ - void addSchemaParser(Codec codec); - - /** - * Registers a schema against backing schema registry store. - * - * @param schemaGroup schema group name - * @param schemaName schema name - * @param schemaString string representation of schema - * @param schemaType string representation of schema type - * @return SchemaRegistryObject containing information regarding registered schema. - * @throws SchemaRegistryClientException if registration operation fails - */ - SchemaRegistryObject register(String schemaGroup, String schemaName, String schemaString, String schemaType); - - /** - * Fetches schema specified by the GUID. - *

- * GUID can be assumed to be unique within a schema registry store. - * - * @param schemaGuid GUID reference to specific schema within configured schema registry store. - * @return SchemaRegistryObject containing information regarding matching schema. - * @throws SchemaRegistryClientException if fetch operation fails - */ - SchemaRegistryObject getSchemaByGuid(String schemaGuid); - - /** - * Fetches schema GUID given schema group, name, string representation, and serialization type - * - * @param schemaGroup schema group name - * @param schemaName schema name - * @param schemaString String representation of schema - * @param schemaType String representation of schema type - * @return SchemaRegistryObject containing information regarding requested schema. - * @throws SchemaRegistryClientException if fetch operation fails - */ - String getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType); - - /** - * Not currently implemented. - * - * @param schemaGroup schema group name - * @param schemaName schema name - * @param version schema version - * @return GUID of delete schema - * @throws SchemaRegistryClientException deletion operation failed - */ - String deleteSchemaVersion(String schemaGroup, String schemaName, int version); - - /** - * Not currently implemented. - * - * @param schemaGroup schema group name - * @param schemaName schema name - * @return GUID of deleted schema - * @throws SchemaRegistryClientException deletion operation failed - */ - String deleteLatestSchemaVersion(String schemaGroup, String schemaName); - - /** - * Not currently implemented. - * - * @param schemaGroup schema group name - * @param schemaName schema name - * @return list of GUID references to deleted schemas - * @throws SchemaRegistryClientException deletion operation failed - */ - List deleteSchema(String schemaGroup, String schemaName); -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryClientException.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryClientException.java deleted file mode 100644 index 5d40f72d57012..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryClientException.java +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client; - -import com.azure.core.exception.AzureException; - -/** - * Runtime exception to be returned from SchemaRegistryClient implementations. - */ -public class SchemaRegistryClientException extends AzureException { - /** - * @param s error message returned from schema registry client - */ - SchemaRegistryClientException(String s) { - super(s); - } - - /** - * @param s error message returned from schema registry client - * @param cause Throwable cause of the exception - */ - SchemaRegistryClientException(String s, Throwable cause) { - super(s, cause); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryObject.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryObject.java deleted file mode 100644 index 2af1d810d07bc..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryObject.java +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client; - -import com.azure.core.util.logging.ClientLogger; -import java.util.function.Function; - -/** - * Stores all relevant information returned from SchemaRegistryClient layer. - */ -public class SchemaRegistryObject { - private final ClientLogger logger = new ClientLogger(SchemaRegistryObject.class); - - private final String schemaId; - private final String schemaType; - private final Function parseMethod; - private final byte[] schemaBytes; - - private Object deserialized; - - /** - * Initializes SchemaRegistryObject instance. - * - * @param schemaId schema ID - * @param schemaType type of schema, e.g. avro, json - * @param schemaByteArray byte payload representing schema, returned from Azure Schema Registry - * @param parseMethod method to deserialize schema payload into Object - */ - public SchemaRegistryObject( - String schemaId, - String schemaType, - byte[] schemaByteArray, - Function parseMethod) { - this.schemaId = schemaId; - this.schemaType = schemaType; - this.schemaBytes = schemaByteArray.clone(); - this.deserialized = null; - this.parseMethod = parseMethod; - } - - /** - * @return schema ID - */ - public String getSchemaId() { - return schemaId; - } - - /** - * @return schema type associated with the schema payload - */ - public String getSchemaType() { - return schemaType; - } - - /** - * Deserialize schema bytes returned from Schema Registry. If deserialization has happened once, the deserialized - * object is stored and returned. - * - * @return schema object, deserialized using stored schema parser method. - */ - public Object deserialize() { - if (this.deserialized == null) { - String schemaString = new String( - this.schemaBytes, CachedSchemaRegistryClient.SCHEMA_REGISTRY_SERVICE_ENCODING); - - logger.verbose("Deserializing schema, id: '{}', schema string '{}'", this.schemaId, schemaString); - - try { - this.deserialized = parseMethod.apply(schemaString); - } catch (Exception e) { - logger.logExceptionAsError(new SchemaRegistryClientException("Failed to deserialize schema", e)); - } - - } - return deserialized; - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/AzureSchemaRegistryRestService.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/AzureSchemaRegistryRestService.java deleted file mode 100644 index f44e765505afe..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/AzureSchemaRegistryRestService.java +++ /dev/null @@ -1,1922 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.Delete; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.Get; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.PathParam; -import com.azure.core.annotation.Post; -import com.azure.core.annotation.Put; -import com.azure.core.annotation.ReturnType; -import com.azure.core.annotation.ServiceInterface; -import com.azure.core.annotation.ServiceMethod; -import com.azure.core.annotation.UnexpectedResponseExceptionType; -import com.azure.core.exception.HttpResponseException; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.CookiePolicy; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; -import com.azure.core.http.rest.Response; -import com.azure.core.http.rest.RestProxy; -import com.azure.core.util.Context; -import com.azure.core.util.FluxUtil; -import com.azure.data.schemaregistry.client.implementation.models.CreateGroupResponse; -import com.azure.data.schemaregistry.client.implementation.models.CreateSchemaResponse; -import com.azure.data.schemaregistry.client.implementation.models.GetIdBySchemaContentResponse; -import com.azure.data.schemaregistry.client.implementation.models.GetLatestSchemaResponse; -import com.azure.data.schemaregistry.client.implementation.models.GetSchemaByIdResponse; -import com.azure.data.schemaregistry.client.implementation.models.GetSchemaVersionResponse; -import com.azure.data.schemaregistry.client.implementation.models.GetSchemaVersionsResponse; -import com.azure.data.schemaregistry.client.implementation.models.GetSchemasByGroupResponse; -import com.azure.data.schemaregistry.client.implementation.models.SchemaGroup; -import com.azure.data.schemaregistry.client.implementation.models.SchemaId; -import java.util.List; -import reactor.core.publisher.Mono; - -/** Initializes a new instance of the AzureSchemaRegistryRestService type. */ -public final class AzureSchemaRegistryRestService { - /** The proxy service used to perform REST calls. */ - private final AzureSchemaRegistryRestServiceService service; - - /** server parameter. */ - private String host; - - /** - * Gets server parameter. - * - * @return the host value. - */ - public String getHost() { - return this.host; - } - - /** - * Sets server parameter. - * - * @param host the host value. - * @return the service client itself. - */ - AzureSchemaRegistryRestService setHost(String host) { - this.host = host; - return this; - } - - /** The HTTP pipeline to send requests through. */ - private final HttpPipeline httpPipeline; - - /** - * Gets The HTTP pipeline to send requests through. - * - * @return the httpPipeline value. - */ - public HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** Initializes an instance of AzureSchemaRegistryRestService client. */ - AzureSchemaRegistryRestService() { - this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()).build()); - } - - /** - * Initializes an instance of AzureSchemaRegistryRestService client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - */ - AzureSchemaRegistryRestService(HttpPipeline httpPipeline) { - this.httpPipeline = httpPipeline; - this.service = RestProxy.create(AzureSchemaRegistryRestServiceService.class, this.httpPipeline); - } - - /** - * The interface defining all the services for AzureSchemaRegistryRestService to be used by the proxy service to - * perform REST calls. - */ - @Host("{$host}") - @ServiceInterface(name = "AzureSchemaRegistryR") - private interface AzureSchemaRegistryRestServiceService { - @Get("/$schemagroups") - @ExpectedResponses({200}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono>> getGroups(@HostParam("$host") String host, Context context); - - @Get("/$schemagroups/getSchemaById/{schema-id}") - @ExpectedResponses({200, 404}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono getSchemaById( - @HostParam("$host") String host, @PathParam("schema-id") String schemaId, Context context); - - @Get("/$schemagroups/{group-name}") - @ExpectedResponses({200, 404}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> getGroup( - @HostParam("$host") String host, @PathParam("group-name") String groupName, Context context); - - @Put("/$schemagroups/{group-name}") - @ExpectedResponses({201, 409}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono createGroup( - @HostParam("$host") String host, - @PathParam("group-name") String groupName, - @BodyParam("application/json") SchemaGroup body, - Context context); - - @Delete("/$schemagroups/{group-name}") - @ExpectedResponses({204, 404}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> deleteGroup( - @HostParam("$host") String host, @PathParam("group-name") String groupName, Context context); - - @Get("/$schemagroups/{group-name}/schemas") - @ExpectedResponses({200, 404}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono getSchemasByGroup( - @HostParam("$host") String host, @PathParam("group-name") String groupName, Context context); - - @Delete("/$schemagroups/{group-name}/schemas") - @ExpectedResponses({204, 404}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> deleteSchemasByGroup( - @HostParam("$host") String host, @PathParam("group-name") String groupName, Context context); - - @Post("/$schemagroups/{group-name}/schemas/{schema-name}") - @ExpectedResponses({200, 404}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono getIdBySchemaContent( - @HostParam("$host") String host, - @PathParam("group-name") String groupName, - @PathParam("schema-name") String schemaName, - @HeaderParam("X-Schema-Type") String xSchemaType, - @BodyParam("application/json") String body, - Context context); - - @Put("/$schemagroups/{group-name}/schemas/{schema-name}") - @ExpectedResponses({200, 400}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono createSchema( - @HostParam("$host") String host, - @PathParam("group-name") String groupName, - @PathParam("schema-name") String schemaName, - @HeaderParam("X-Schema-Type") String xSchemaType, - @BodyParam("application/json") String body, - Context context); - - @Get("/$schemagroups/{group-name}/schemas/{schema-name}") - @ExpectedResponses({200}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono getLatestSchema( - @HostParam("$host") String host, - @PathParam("group-name") String groupName, - @PathParam("schema-name") String schemaName, - Context context); - - @Delete("/$schemagroups/{group-name}/schemas/{schema-name}") - @ExpectedResponses({204, 404}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> deleteSchema( - @HostParam("$host") String host, - @PathParam("group-name") String groupName, - @PathParam("schema-name") String schemaName, - Context context); - - @Get("/$schemagroups/{group-name}/schemas/{schema-name}/versions") - @ExpectedResponses({200}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono getSchemaVersions( - @HostParam("$host") String host, - @PathParam("group-name") String groupName, - @PathParam("schema-name") String schemaName, - Context context); - - @Get("/$schemagroups/{group-name}/schemas/{schema-name}/versions/{version-number}") - @ExpectedResponses({200, 404}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono getSchemaVersion( - @HostParam("$host") String host, - @PathParam("group-name") String groupName, - @PathParam("schema-name") String schemaName, - @PathParam("version-number") int versionNumber, - Context context); - - @Delete("/$schemagroups/{group-name}/schemas/{schema-name}/versions/{version-number}") - @ExpectedResponses({204}) - @UnexpectedResponseExceptionType(HttpResponseException.class) - Mono> deleteSchemaVersion( - @HostParam("$host") String host, - @PathParam("group-name") String groupName, - @PathParam("schema-name") String schemaName, - @PathParam("version-number") int versionNumber, - Context context); - } - - /** - * Get all schema groups in namespace. - * - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all schema groups in namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono>> getGroupsWithResponseAsync() { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - return FluxUtil.withContext(context -> service.getGroups(this.getHost(), context)); - } - - /** - * Get all schema groups in namespace. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all schema groups in namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono>> getGroupsWithResponseAsync(Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - return service.getGroups(this.getHost(), context); - } - - /** - * Get all schema groups in namespace. - * - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all schema groups in namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getGroupsAsync() { - return getGroupsWithResponseAsync() - .flatMap( - (Response> res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get all schema groups in namespace. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all schema groups in namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getGroupsAsync(Context context) { - return getGroupsWithResponseAsync(context) - .flatMap( - (Response> res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get all schema groups in namespace. - * - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all schema groups in namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public List getGroups() { - return getGroupsAsync().block(); - } - - /** - * Get all schema groups in namespace. - * - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return all schema groups in namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public List getGroups(Context context) { - return getGroupsAsync(context).block(); - } - - /** - * Get schema by schema ID. - * - * @param schemaId schema ID referencing specific schema in registry namespace. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema by schema ID. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaByIdWithResponseAsync(String schemaId) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (schemaId == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); - } - return FluxUtil.withContext(context -> service.getSchemaById(this.getHost(), schemaId, context)); - } - - /** - * Get schema by schema ID. - * - * @param schemaId schema ID referencing specific schema in registry namespace. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema by schema ID. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaByIdWithResponseAsync(String schemaId, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (schemaId == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); - } - return service.getSchemaById(this.getHost(), schemaId, context); - } - - /** - * Get schema by schema ID. - * - * @param schemaId schema ID referencing specific schema in registry namespace. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema by schema ID. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaByIdAsync(String schemaId) { - return getSchemaByIdWithResponseAsync(schemaId) - .flatMap( - (GetSchemaByIdResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get schema by schema ID. - * - * @param schemaId schema ID referencing specific schema in registry namespace. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema by schema ID. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaByIdAsync(String schemaId, Context context) { - return getSchemaByIdWithResponseAsync(schemaId, context) - .flatMap( - (GetSchemaByIdResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get schema by schema ID. - * - * @param schemaId schema ID referencing specific schema in registry namespace. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema by schema ID. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public String getSchemaById(String schemaId) { - return getSchemaByIdAsync(schemaId).block(); - } - - /** - * Get schema by schema ID. - * - * @param schemaId schema ID referencing specific schema in registry namespace. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema by schema ID. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public String getSchemaById(String schemaId, Context context) { - return getSchemaByIdAsync(schemaId, context).block(); - } - - /** - * Get schema group description in registry namespace. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema group description in registry namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getGroupWithResponseAsync(String groupName) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - return FluxUtil.withContext(context -> service.getGroup(this.getHost(), groupName, context)); - } - - /** - * Get schema group description in registry namespace. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema group description in registry namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getGroupWithResponseAsync(String groupName, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - return service.getGroup(this.getHost(), groupName, context); - } - - /** - * Get schema group description in registry namespace. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema group description in registry namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getGroupAsync(String groupName) { - return getGroupWithResponseAsync(groupName) - .flatMap( - (Response res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get schema group description in registry namespace. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema group description in registry namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getGroupAsync(String groupName, Context context) { - return getGroupWithResponseAsync(groupName, context) - .flatMap( - (Response res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get schema group description in registry namespace. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema group description in registry namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaGroup getGroup(String groupName) { - return getGroupAsync(groupName).block(); - } - - /** - * Get schema group description in registry namespace. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return schema group description in registry namespace. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaGroup getGroup(String groupName, Context context) { - return getGroupAsync(groupName, context).block(); - } - - /** - * Create schema group with specified schema type in registry namespace. - * - * @param groupName schema group. - * @param body schema group description. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createGroupWithResponseAsync(String groupName, SchemaGroup body) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (body == null) { - return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); - } else { - body.validate(); - } - return FluxUtil.withContext(context -> service.createGroup(this.getHost(), groupName, body, context)); - } - - /** - * Create schema group with specified schema type in registry namespace. - * - * @param groupName schema group. - * @param body schema group description. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createGroupWithResponseAsync(String groupName, SchemaGroup body, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (body == null) { - return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); - } else { - body.validate(); - } - return service.createGroup(this.getHost(), groupName, body, context); - } - - /** - * Create schema group with specified schema type in registry namespace. - * - * @param groupName schema group. - * @param body schema group description. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createGroupAsync(String groupName, SchemaGroup body) { - return createGroupWithResponseAsync(groupName, body).flatMap((CreateGroupResponse res) -> Mono.empty()); - } - - /** - * Create schema group with specified schema type in registry namespace. - * - * @param groupName schema group. - * @param body schema group description. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createGroupAsync(String groupName, SchemaGroup body, Context context) { - return createGroupWithResponseAsync(groupName, body, context) - .flatMap((CreateGroupResponse res) -> Mono.empty()); - } - - /** - * Create schema group with specified schema type in registry namespace. - * - * @param groupName schema group. - * @param body schema group description. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void createGroup(String groupName, SchemaGroup body) { - createGroupAsync(groupName, body).block(); - } - - /** - * Create schema group with specified schema type in registry namespace. - * - * @param groupName schema group. - * @param body schema group description. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void createGroup(String groupName, SchemaGroup body, Context context) { - createGroupAsync(groupName, body, context).block(); - } - - /** - * Delete schema group in schema registry namespace. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteGroupWithResponseAsync(String groupName) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - return FluxUtil.withContext(context -> service.deleteGroup(this.getHost(), groupName, context)); - } - - /** - * Delete schema group in schema registry namespace. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteGroupWithResponseAsync(String groupName, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - return service.deleteGroup(this.getHost(), groupName, context); - } - - /** - * Delete schema group in schema registry namespace. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteGroupAsync(String groupName) { - return deleteGroupWithResponseAsync(groupName).flatMap((Response res) -> Mono.empty()); - } - - /** - * Delete schema group in schema registry namespace. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteGroupAsync(String groupName, Context context) { - return deleteGroupWithResponseAsync(groupName, context).flatMap((Response res) -> Mono.empty()); - } - - /** - * Delete schema group in schema registry namespace. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteGroup(String groupName) { - deleteGroupAsync(groupName).block(); - } - - /** - * Delete schema group in schema registry namespace. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteGroup(String groupName, Context context) { - deleteGroupAsync(groupName, context).block(); - } - - /** - * Returns schema by group name. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return array of String. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemasByGroupWithResponseAsync(String groupName) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - return FluxUtil.withContext(context -> service.getSchemasByGroup(this.getHost(), groupName, context)); - } - - /** - * Returns schema by group name. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return array of String. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemasByGroupWithResponseAsync(String groupName, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - return service.getSchemasByGroup(this.getHost(), groupName, context); - } - - /** - * Returns schema by group name. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return array of String. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSchemasByGroupAsync(String groupName) { - return getSchemasByGroupWithResponseAsync(groupName) - .flatMap( - (GetSchemasByGroupResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Returns schema by group name. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return array of String. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSchemasByGroupAsync(String groupName, Context context) { - return getSchemasByGroupWithResponseAsync(groupName, context) - .flatMap( - (GetSchemasByGroupResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Returns schema by group name. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return array of String. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public List getSchemasByGroup(String groupName) { - return getSchemasByGroupAsync(groupName).block(); - } - - /** - * Returns schema by group name. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return array of String. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public List getSchemasByGroup(String groupName, Context context) { - return getSchemasByGroupAsync(groupName, context).block(); - } - - /** - * Deletes all schemas under specified group name. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSchemasByGroupWithResponseAsync(String groupName) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - return FluxUtil.withContext(context -> service.deleteSchemasByGroup(this.getHost(), groupName, context)); - } - - /** - * Deletes all schemas under specified group name. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSchemasByGroupWithResponseAsync(String groupName, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - return service.deleteSchemasByGroup(this.getHost(), groupName, context); - } - - /** - * Deletes all schemas under specified group name. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSchemasByGroupAsync(String groupName) { - return deleteSchemasByGroupWithResponseAsync(groupName).flatMap((Response res) -> Mono.empty()); - } - - /** - * Deletes all schemas under specified group name. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSchemasByGroupAsync(String groupName, Context context) { - return deleteSchemasByGroupWithResponseAsync(groupName, context).flatMap((Response res) -> Mono.empty()); - } - - /** - * Deletes all schemas under specified group name. - * - * @param groupName schema group. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteSchemasByGroup(String groupName) { - deleteSchemasByGroupAsync(groupName).block(); - } - - /** - * Deletes all schemas under specified group name. - * - * @param groupName schema group. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteSchemasByGroup(String groupName, Context context) { - deleteSchemasByGroupAsync(groupName, context).block(); - } - - /** - * Get ID for schema with matching byte content and schema type. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return iD for schema with matching byte content and schema type. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getIdBySchemaContentWithResponseAsync( - String groupName, String schemaName, String xSchemaType, String body) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (xSchemaType == null) { - return Mono.error(new IllegalArgumentException("Parameter xSchemaType is required and cannot be null.")); - } - if (body == null) { - return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); - } - return FluxUtil.withContext( - context -> - service.getIdBySchemaContent( - this.getHost(), groupName, schemaName, xSchemaType, body, context)); - } - - /** - * Get ID for schema with matching byte content and schema type. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return iD for schema with matching byte content and schema type. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getIdBySchemaContentWithResponseAsync( - String groupName, String schemaName, String xSchemaType, String body, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (xSchemaType == null) { - return Mono.error(new IllegalArgumentException("Parameter xSchemaType is required and cannot be null.")); - } - if (body == null) { - return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); - } - return service.getIdBySchemaContent(this.getHost(), groupName, schemaName, xSchemaType, body, context); - } - - /** - * Get ID for schema with matching byte content and schema type. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return iD for schema with matching byte content and schema type. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getIdBySchemaContentAsync( - String groupName, String schemaName, String xSchemaType, String body) { - return getIdBySchemaContentWithResponseAsync(groupName, schemaName, xSchemaType, body) - .flatMap( - (GetIdBySchemaContentResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get ID for schema with matching byte content and schema type. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return iD for schema with matching byte content and schema type. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getIdBySchemaContentAsync( - String groupName, String schemaName, String xSchemaType, String body, Context context) { - return getIdBySchemaContentWithResponseAsync(groupName, schemaName, xSchemaType, body, context) - .flatMap( - (GetIdBySchemaContentResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get ID for schema with matching byte content and schema type. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return iD for schema with matching byte content and schema type. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaId getIdBySchemaContent(String groupName, String schemaName, String xSchemaType, String body) { - return getIdBySchemaContentAsync(groupName, schemaName, xSchemaType, body).block(); - } - - /** - * Get ID for schema with matching byte content and schema type. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return iD for schema with matching byte content and schema type. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaId getIdBySchemaContent( - String groupName, String schemaName, String xSchemaType, String body, Context context) { - return getIdBySchemaContentAsync(groupName, schemaName, xSchemaType, body, context).block(); - } - - /** - * Register schema. If schema of specified name does not exist in specified group, schema is created at version 1. - * If schema of specified name exists already in specified group, schema is created at latest version + 1. If schema - * with identical content already exists, existing schema's ID is returned. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createSchemaWithResponseAsync( - String groupName, String schemaName, String xSchemaType, String body) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (xSchemaType == null) { - return Mono.error(new IllegalArgumentException("Parameter xSchemaType is required and cannot be null.")); - } - if (body == null) { - return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); - } - return FluxUtil.withContext( - context -> service.createSchema(this.getHost(), groupName, schemaName, xSchemaType, body, context)); - } - - /** - * Register schema. If schema of specified name does not exist in specified group, schema is created at version 1. - * If schema of specified name exists already in specified group, schema is created at latest version + 1. If schema - * with identical content already exists, existing schema's ID is returned. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createSchemaWithResponseAsync( - String groupName, String schemaName, String xSchemaType, String body, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - if (xSchemaType == null) { - return Mono.error(new IllegalArgumentException("Parameter xSchemaType is required and cannot be null.")); - } - if (body == null) { - return Mono.error(new IllegalArgumentException("Parameter body is required and cannot be null.")); - } - return service.createSchema(this.getHost(), groupName, schemaName, xSchemaType, body, context); - } - - /** - * Register schema. If schema of specified name does not exist in specified group, schema is created at version 1. - * If schema of specified name exists already in specified group, schema is created at latest version + 1. If schema - * with identical content already exists, existing schema's ID is returned. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createSchemaAsync(String groupName, String schemaName, String xSchemaType, String body) { - return createSchemaWithResponseAsync(groupName, schemaName, xSchemaType, body) - .flatMap( - (CreateSchemaResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Register schema. If schema of specified name does not exist in specified group, schema is created at version 1. - * If schema of specified name exists already in specified group, schema is created at latest version + 1. If schema - * with identical content already exists, existing schema's ID is returned. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createSchemaAsync( - String groupName, String schemaName, String xSchemaType, String body, Context context) { - return createSchemaWithResponseAsync(groupName, schemaName, xSchemaType, body, context) - .flatMap( - (CreateSchemaResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Register schema. If schema of specified name does not exist in specified group, schema is created at version 1. - * If schema of specified name exists already in specified group, schema is created at latest version + 1. If schema - * with identical content already exists, existing schema's ID is returned. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaId createSchema(String groupName, String schemaName, String xSchemaType, String body) { - return createSchemaAsync(groupName, schemaName, xSchemaType, body).block(); - } - - /** - * Register schema. If schema of specified name does not exist in specified group, schema is created at version 1. - * If schema of specified name exists already in specified group, schema is created at latest version + 1. If schema - * with identical content already exists, existing schema's ID is returned. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param xSchemaType The xSchemaType parameter. - * @param body schema content. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaId createSchema( - String groupName, String schemaName, String xSchemaType, String body, Context context) { - return createSchemaAsync(groupName, schemaName, xSchemaType, body, context).block(); - } - - /** - * Get latest version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return latest version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getLatestSchemaWithResponseAsync(String groupName, String schemaName) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - return FluxUtil.withContext(context -> service.getLatestSchema(this.getHost(), groupName, schemaName, context)); - } - - /** - * Get latest version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return latest version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getLatestSchemaWithResponseAsync( - String groupName, String schemaName, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - return service.getLatestSchema(this.getHost(), groupName, schemaName, context); - } - - /** - * Get latest version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return latest version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getLatestSchemaAsync(String groupName, String schemaName) { - return getLatestSchemaWithResponseAsync(groupName, schemaName) - .flatMap( - (GetLatestSchemaResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get latest version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return latest version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getLatestSchemaAsync(String groupName, String schemaName, Context context) { - return getLatestSchemaWithResponseAsync(groupName, schemaName, context) - .flatMap( - (GetLatestSchemaResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get latest version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return latest version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public String getLatestSchema(String groupName, String schemaName) { - return getLatestSchemaAsync(groupName, schemaName).block(); - } - - /** - * Get latest version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return latest version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public String getLatestSchema(String groupName, String schemaName, Context context) { - return getLatestSchemaAsync(groupName, schemaName, context).block(); - } - - /** - * Delete schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSchemaWithResponseAsync(String groupName, String schemaName) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - return FluxUtil.withContext(context -> service.deleteSchema(this.getHost(), groupName, schemaName, context)); - } - - /** - * Delete schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSchemaWithResponseAsync(String groupName, String schemaName, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - return service.deleteSchema(this.getHost(), groupName, schemaName, context); - } - - /** - * Delete schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSchemaAsync(String groupName, String schemaName) { - return deleteSchemaWithResponseAsync(groupName, schemaName).flatMap((Response res) -> Mono.empty()); - } - - /** - * Delete schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSchemaAsync(String groupName, String schemaName, Context context) { - return deleteSchemaWithResponseAsync(groupName, schemaName, context) - .flatMap((Response res) -> Mono.empty()); - } - - /** - * Delete schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteSchema(String groupName, String schemaName) { - deleteSchemaAsync(groupName, schemaName).block(); - } - - /** - * Delete schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteSchema(String groupName, String schemaName, Context context) { - deleteSchemaAsync(groupName, schemaName, context).block(); - } - - /** - * Get list of versions for specified schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of versions for specified schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaVersionsWithResponseAsync(String groupName, String schemaName) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - return FluxUtil.withContext( - context -> service.getSchemaVersions(this.getHost(), groupName, schemaName, context)); - } - - /** - * Get list of versions for specified schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of versions for specified schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaVersionsWithResponseAsync( - String groupName, String schemaName, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - return service.getSchemaVersions(this.getHost(), groupName, schemaName, context); - } - - /** - * Get list of versions for specified schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of versions for specified schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSchemaVersionsAsync(String groupName, String schemaName) { - return getSchemaVersionsWithResponseAsync(groupName, schemaName) - .flatMap( - (GetSchemaVersionsResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get list of versions for specified schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of versions for specified schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSchemaVersionsAsync(String groupName, String schemaName, Context context) { - return getSchemaVersionsWithResponseAsync(groupName, schemaName, context) - .flatMap( - (GetSchemaVersionsResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get list of versions for specified schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of versions for specified schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public List getSchemaVersions(String groupName, String schemaName) { - return getSchemaVersionsAsync(groupName, schemaName).block(); - } - - /** - * Get list of versions for specified schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return list of versions for specified schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public List getSchemaVersions(String groupName, String schemaName, Context context) { - return getSchemaVersionsAsync(groupName, schemaName, context).block(); - } - - /** - * Get specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return specified version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaVersionWithResponseAsync( - String groupName, String schemaName, int versionNumber) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - return FluxUtil.withContext( - context -> service.getSchemaVersion(this.getHost(), groupName, schemaName, versionNumber, context)); - } - - /** - * Get specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return specified version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaVersionWithResponseAsync( - String groupName, String schemaName, int versionNumber, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - return service.getSchemaVersion(this.getHost(), groupName, schemaName, versionNumber, context); - } - - /** - * Get specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return specified version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaVersionAsync(String groupName, String schemaName, int versionNumber) { - return getSchemaVersionWithResponseAsync(groupName, schemaName, versionNumber) - .flatMap( - (GetSchemaVersionResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return specified version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaVersionAsync(String groupName, String schemaName, int versionNumber, Context context) { - return getSchemaVersionWithResponseAsync(groupName, schemaName, versionNumber, context) - .flatMap( - (GetSchemaVersionResponse res) -> { - if (res.getValue() != null) { - return Mono.just(res.getValue()); - } else { - return Mono.empty(); - } - }); - } - - /** - * Get specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return specified version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public String getSchemaVersion(String groupName, String schemaName, int versionNumber) { - return getSchemaVersionAsync(groupName, schemaName, versionNumber).block(); - } - - /** - * Get specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return specified version of schema. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public String getSchemaVersion(String groupName, String schemaName, int versionNumber, Context context) { - return getSchemaVersionAsync(groupName, schemaName, versionNumber, context).block(); - } - - /** - * Delete specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSchemaVersionWithResponseAsync( - String groupName, String schemaName, int versionNumber) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - return FluxUtil.withContext( - context -> service.deleteSchemaVersion(this.getHost(), groupName, schemaName, versionNumber, context)); - } - - /** - * Delete specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSchemaVersionWithResponseAsync( - String groupName, String schemaName, int versionNumber, Context context) { - if (this.getHost() == null) { - return Mono.error(new IllegalArgumentException("Parameter this.getHost() is required and cannot be null.")); - } - if (groupName == null) { - return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); - } - if (schemaName == null) { - return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); - } - return service.deleteSchemaVersion(this.getHost(), groupName, schemaName, versionNumber, context); - } - - /** - * Delete specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSchemaVersionAsync(String groupName, String schemaName, int versionNumber) { - return deleteSchemaVersionWithResponseAsync(groupName, schemaName, versionNumber) - .flatMap((Response res) -> Mono.empty()); - } - - /** - * Delete specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - * @return the completion. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteSchemaVersionAsync( - String groupName, String schemaName, int versionNumber, Context context) { - return deleteSchemaVersionWithResponseAsync(groupName, schemaName, versionNumber, context) - .flatMap((Response res) -> Mono.empty()); - } - - /** - * Delete specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteSchemaVersion(String groupName, String schemaName, int versionNumber) { - deleteSchemaVersionAsync(groupName, schemaName, versionNumber).block(); - } - - /** - * Delete specified version of schema. - * - * @param groupName schema group. - * @param schemaName schema name. - * @param versionNumber version number. - * @param context The context to associate with this operation. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws HttpResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteSchemaVersion(String groupName, String schemaName, int versionNumber, Context context) { - deleteSchemaVersionAsync(groupName, schemaName, versionNumber, context).block(); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/AzureSchemaRegistryRestServiceClientBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/AzureSchemaRegistryRestServiceClientBuilder.java deleted file mode 100644 index 4dbf94d09ca5d..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/AzureSchemaRegistryRestServiceClientBuilder.java +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation; - -import com.azure.core.annotation.ServiceClientBuilder; -import com.azure.core.http.HttpPipeline; -import com.azure.core.http.HttpPipelineBuilder; -import com.azure.core.http.policy.CookiePolicy; -import com.azure.core.http.policy.RetryPolicy; -import com.azure.core.http.policy.UserAgentPolicy; - -/** A builder for creating a new instance of the AzureSchemaRegistryRestService type. */ -@ServiceClientBuilder(serviceClients = {AzureSchemaRegistryRestService.class}) -public final class AzureSchemaRegistryRestServiceClientBuilder { - /* - * server parameter - */ - private String host; - - /** - * Sets server parameter. - * - * @param host the host value. - * @return the AzureSchemaRegistryRestServiceClientBuilder. - */ - public AzureSchemaRegistryRestServiceClientBuilder host(String host) { - this.host = host; - return this; - } - - /* - * The HTTP pipeline to send requests through - */ - private HttpPipeline pipeline; - - /** - * Sets The HTTP pipeline to send requests through. - * - * @param pipeline the pipeline value. - * @return the AzureSchemaRegistryRestServiceClientBuilder. - */ - public AzureSchemaRegistryRestServiceClientBuilder pipeline(HttpPipeline pipeline) { - this.pipeline = pipeline; - return this; - } - - /** - * Builds an instance of AzureSchemaRegistryRestService with the provided parameters. - * - * @return an instance of AzureSchemaRegistryRestService. - */ - public AzureSchemaRegistryRestService buildClient() { - if (host == null) { - this.host = ""; - } - if (pipeline == null) { - this.pipeline = - new HttpPipelineBuilder() - .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) - .build(); - } - AzureSchemaRegistryRestService client = new AzureSchemaRegistryRestService(pipeline); - client.setHost(this.host); - return client; - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateGroupHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateGroupHeaders.java deleted file mode 100644 index ba373f71b19d1..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateGroupHeaders.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** The CreateGroupHeaders model. */ -@Fluent -public final class CreateGroupHeaders { - /* - * The Location property. - */ - @JsonProperty(value = "Location") - private String location; - - /** - * Get the location property: The Location property. - * - * @return the location value. - */ - public String getLocation() { - return this.location; - } - - /** - * Set the location property: The Location property. - * - * @param location the location value to set. - * @return the CreateGroupHeaders object itself. - */ - public CreateGroupHeaders setLocation(String location) { - this.location = location; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateGroupResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateGroupResponse.java deleted file mode 100644 index 7f6b958bbd68a..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateGroupResponse.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.rest.ResponseBase; - -/** Contains all response data for the createGroup operation. */ -public final class CreateGroupResponse extends ResponseBase { - /** - * Creates an instance of CreateGroupResponse. - * - * @param request the request which resulted in this CreateGroupResponse. - * @param statusCode the status code of the HTTP response. - * @param rawHeaders the raw headers of the HTTP response. - * @param value the deserialized value of the HTTP response. - * @param headers the deserialized headers of the HTTP response. - */ - public CreateGroupResponse( - HttpRequest request, int statusCode, HttpHeaders rawHeaders, Void value, CreateGroupHeaders headers) { - super(request, statusCode, rawHeaders, value, headers); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateSchemaResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateSchemaResponse.java deleted file mode 100644 index 5612686cb87f8..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateSchemaResponse.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.rest.ResponseBase; - -/** Contains all response data for the createSchema operation. */ -public final class CreateSchemaResponse extends ResponseBase { - /** - * Creates an instance of CreateSchemaResponse. - * - * @param request the request which resulted in this CreateSchemaResponse. - * @param statusCode the status code of the HTTP response. - * @param rawHeaders the raw headers of the HTTP response. - * @param value the deserialized value of the HTTP response. - * @param headers the deserialized headers of the HTTP response. - */ - public CreateSchemaResponse( - HttpRequest request, int statusCode, HttpHeaders rawHeaders, SchemaId value, CreateSchemaHeaders headers) { - super(request, statusCode, rawHeaders, value, headers); - } - - /** @return the deserialized response body. */ - @Override - public SchemaId getValue() { - return super.getValue(); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetIdBySchemaContentHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetIdBySchemaContentHeaders.java deleted file mode 100644 index 45e63cd1e4a11..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetIdBySchemaContentHeaders.java +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.fasterxml.jackson.annotation.JsonProperty; -import java.net.URL; - -/** The GetIdBySchemaContentHeaders model. */ -@Fluent -public final class GetIdBySchemaContentHeaders { - /* - * The X-Schema-Version property. - */ - @JsonProperty(value = "X-Schema-Version") - private Integer xSchemaVersion; - - /* - * The X-Schema-Type property. - */ - @JsonProperty(value = "X-Schema-Type") - private String xSchemaType; - - /* - * The X-Schema-Id property. - */ - @JsonProperty(value = "X-Schema-Id") - private String xSchemaId; - - /* - * The X-Schema-Id-Location property. - */ - @JsonProperty(value = "X-Schema-Id-Location") - private URL xSchemaIdLocation; - - /* - * The Location property. - */ - @JsonProperty(value = "Location") - private String location; - - /** - * Get the xSchemaVersion property: The X-Schema-Version property. - * - * @return the xSchemaVersion value. - */ - public Integer getXSchemaVersion() { - return this.xSchemaVersion; - } - - /** - * Set the xSchemaVersion property: The X-Schema-Version property. - * - * @param xSchemaVersion the xSchemaVersion value to set. - * @return the GetIdBySchemaContentHeaders object itself. - */ - public GetIdBySchemaContentHeaders setXSchemaVersion(Integer xSchemaVersion) { - this.xSchemaVersion = xSchemaVersion; - return this; - } - - /** - * Get the xSchemaType property: The X-Schema-Type property. - * - * @return the xSchemaType value. - */ - public String getXSchemaType() { - return this.xSchemaType; - } - - /** - * Set the xSchemaType property: The X-Schema-Type property. - * - * @param xSchemaType the xSchemaType value to set. - * @return the GetIdBySchemaContentHeaders object itself. - */ - public GetIdBySchemaContentHeaders setXSchemaType(String xSchemaType) { - this.xSchemaType = xSchemaType; - return this; - } - - /** - * Get the xSchemaId property: The X-Schema-Id property. - * - * @return the xSchemaId value. - */ - public String getXSchemaId() { - return this.xSchemaId; - } - - /** - * Set the xSchemaId property: The X-Schema-Id property. - * - * @param xSchemaId the xSchemaId value to set. - * @return the GetIdBySchemaContentHeaders object itself. - */ - public GetIdBySchemaContentHeaders setXSchemaId(String xSchemaId) { - this.xSchemaId = xSchemaId; - return this; - } - - /** - * Get the xSchemaIdLocation property: The X-Schema-Id-Location property. - * - * @return the xSchemaIdLocation value. - */ - public URL getXSchemaIdLocation() { - return this.xSchemaIdLocation; - } - - /** - * Set the xSchemaIdLocation property: The X-Schema-Id-Location property. - * - * @param xSchemaIdLocation the xSchemaIdLocation value to set. - * @return the GetIdBySchemaContentHeaders object itself. - */ - public GetIdBySchemaContentHeaders setXSchemaIdLocation(URL xSchemaIdLocation) { - this.xSchemaIdLocation = xSchemaIdLocation; - return this; - } - - /** - * Get the location property: The Location property. - * - * @return the location value. - */ - public String getLocation() { - return this.location; - } - - /** - * Set the location property: The Location property. - * - * @param location the location value to set. - * @return the GetIdBySchemaContentHeaders object itself. - */ - public GetIdBySchemaContentHeaders setLocation(String location) { - this.location = location; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetLatestSchemaResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetLatestSchemaResponse.java deleted file mode 100644 index b1aec099e8682..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetLatestSchemaResponse.java +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.rest.ResponseBase; - -/** Contains all response data for the getLatestSchema operation. */ -public final class GetLatestSchemaResponse extends ResponseBase { - /** - * Creates an instance of GetLatestSchemaResponse. - * - * @param request the request which resulted in this GetLatestSchemaResponse. - * @param statusCode the status code of the HTTP response. - * @param rawHeaders the raw headers of the HTTP response. - * @param value the deserialized value of the HTTP response. - * @param headers the deserialized headers of the HTTP response. - */ - public GetLatestSchemaResponse( - HttpRequest request, int statusCode, HttpHeaders rawHeaders, String value, GetLatestSchemaHeaders headers) { - super(request, statusCode, rawHeaders, value, headers); - } - - /** @return the deserialized response body. */ - @Override - public String getValue() { - return super.getValue(); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionHeaders.java deleted file mode 100644 index 6210361d7a1cc..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionHeaders.java +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.fasterxml.jackson.annotation.JsonProperty; -import java.net.URL; - -/** The GetSchemaVersionHeaders model. */ -@Fluent -public final class GetSchemaVersionHeaders { - /* - * The X-Schema-Version property. - */ - @JsonProperty(value = "X-Schema-Version") - private Integer xSchemaVersion; - - /* - * The X-Schema-Type property. - */ - @JsonProperty(value = "X-Schema-Type") - private String xSchemaType; - - /* - * The X-Schema-Id property. - */ - @JsonProperty(value = "X-Schema-Id") - private String xSchemaId; - - /* - * The X-Schema-Id-Location property. - */ - @JsonProperty(value = "X-Schema-Id-Location") - private URL xSchemaIdLocation; - - /* - * The Location property. - */ - @JsonProperty(value = "Location") - private String location; - - /** - * Get the xSchemaVersion property: The X-Schema-Version property. - * - * @return the xSchemaVersion value. - */ - public Integer getXSchemaVersion() { - return this.xSchemaVersion; - } - - /** - * Set the xSchemaVersion property: The X-Schema-Version property. - * - * @param xSchemaVersion the xSchemaVersion value to set. - * @return the GetSchemaVersionHeaders object itself. - */ - public GetSchemaVersionHeaders setXSchemaVersion(Integer xSchemaVersion) { - this.xSchemaVersion = xSchemaVersion; - return this; - } - - /** - * Get the xSchemaType property: The X-Schema-Type property. - * - * @return the xSchemaType value. - */ - public String getXSchemaType() { - return this.xSchemaType; - } - - /** - * Set the xSchemaType property: The X-Schema-Type property. - * - * @param xSchemaType the xSchemaType value to set. - * @return the GetSchemaVersionHeaders object itself. - */ - public GetSchemaVersionHeaders setXSchemaType(String xSchemaType) { - this.xSchemaType = xSchemaType; - return this; - } - - /** - * Get the xSchemaId property: The X-Schema-Id property. - * - * @return the xSchemaId value. - */ - public String getXSchemaId() { - return this.xSchemaId; - } - - /** - * Set the xSchemaId property: The X-Schema-Id property. - * - * @param xSchemaId the xSchemaId value to set. - * @return the GetSchemaVersionHeaders object itself. - */ - public GetSchemaVersionHeaders setXSchemaId(String xSchemaId) { - this.xSchemaId = xSchemaId; - return this; - } - - /** - * Get the xSchemaIdLocation property: The X-Schema-Id-Location property. - * - * @return the xSchemaIdLocation value. - */ - public URL getXSchemaIdLocation() { - return this.xSchemaIdLocation; - } - - /** - * Set the xSchemaIdLocation property: The X-Schema-Id-Location property. - * - * @param xSchemaIdLocation the xSchemaIdLocation value to set. - * @return the GetSchemaVersionHeaders object itself. - */ - public GetSchemaVersionHeaders setXSchemaIdLocation(URL xSchemaIdLocation) { - this.xSchemaIdLocation = xSchemaIdLocation; - return this; - } - - /** - * Get the location property: The Location property. - * - * @return the location value. - */ - public String getLocation() { - return this.location; - } - - /** - * Set the location property: The Location property. - * - * @param location the location value to set. - * @return the GetSchemaVersionHeaders object itself. - */ - public GetSchemaVersionHeaders setLocation(String location) { - this.location = location; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionsHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionsHeaders.java deleted file mode 100644 index db011b690a669..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionsHeaders.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** The GetSchemaVersionsHeaders model. */ -@Fluent -public final class GetSchemaVersionsHeaders { - /* - * The X-Schema-Type property. - */ - @JsonProperty(value = "X-Schema-Type") - private String xSchemaType; - - /** - * Get the xSchemaType property: The X-Schema-Type property. - * - * @return the xSchemaType value. - */ - public String getXSchemaType() { - return this.xSchemaType; - } - - /** - * Set the xSchemaType property: The X-Schema-Type property. - * - * @param xSchemaType the xSchemaType value to set. - * @return the GetSchemaVersionsHeaders object itself. - */ - public GetSchemaVersionsHeaders setXSchemaType(String xSchemaType) { - this.xSchemaType = xSchemaType; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionsResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionsResponse.java deleted file mode 100644 index 67afbfed471b0..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionsResponse.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.rest.ResponseBase; -import java.util.List; - -/** Contains all response data for the getSchemaVersions operation. */ -public final class GetSchemaVersionsResponse extends ResponseBase> { - /** - * Creates an instance of GetSchemaVersionsResponse. - * - * @param request the request which resulted in this GetSchemaVersionsResponse. - * @param statusCode the status code of the HTTP response. - * @param rawHeaders the raw headers of the HTTP response. - * @param value the deserialized value of the HTTP response. - * @param headers the deserialized headers of the HTTP response. - */ - public GetSchemaVersionsResponse( - HttpRequest request, - int statusCode, - HttpHeaders rawHeaders, - List value, - GetSchemaVersionsHeaders headers) { - super(request, statusCode, rawHeaders, value, headers); - } - - /** @return the deserialized response body. */ - @Override - public List getValue() { - return super.getValue(); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemasByGroupHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemasByGroupHeaders.java deleted file mode 100644 index a8162e0af75ac..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemasByGroupHeaders.java +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** The GetSchemasByGroupHeaders model. */ -@Fluent -public final class GetSchemasByGroupHeaders { - /* - * The X-Schema-Type property. - */ - @JsonProperty(value = "X-Schema-Type") - private String xSchemaType; - - /** - * Get the xSchemaType property: The X-Schema-Type property. - * - * @return the xSchemaType value. - */ - public String getXSchemaType() { - return this.xSchemaType; - } - - /** - * Set the xSchemaType property: The X-Schema-Type property. - * - * @param xSchemaType the xSchemaType value to set. - * @return the GetSchemasByGroupHeaders object itself. - */ - public GetSchemasByGroupHeaders setXSchemaType(String xSchemaType) { - this.xSchemaType = xSchemaType; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemasByGroupResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemasByGroupResponse.java deleted file mode 100644 index 796219fe422d2..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemasByGroupResponse.java +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.http.HttpHeaders; -import com.azure.core.http.HttpRequest; -import com.azure.core.http.rest.ResponseBase; -import java.util.List; - -/** Contains all response data for the getSchemasByGroup operation. */ -public final class GetSchemasByGroupResponse extends ResponseBase> { - /** - * Creates an instance of GetSchemasByGroupResponse. - * - * @param request the request which resulted in this GetSchemasByGroupResponse. - * @param statusCode the status code of the HTTP response. - * @param rawHeaders the raw headers of the HTTP response. - * @param value the deserialized value of the HTTP response. - * @param headers the deserialized headers of the HTTP response. - */ - public GetSchemasByGroupResponse( - HttpRequest request, - int statusCode, - HttpHeaders rawHeaders, - List value, - GetSchemasByGroupHeaders headers) { - super(request, statusCode, rawHeaders, value, headers); - } - - /** @return the deserialized response body. */ - @Override - public List getValue() { - return super.getValue(); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/SchemaGroup.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/SchemaGroup.java deleted file mode 100644 index 98d2e8e3ca719..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/SchemaGroup.java +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.fasterxml.jackson.annotation.JsonProperty; -import java.time.OffsetDateTime; -import java.util.Map; - -/** The SchemaGroup model. */ -@Fluent -public final class SchemaGroup { - /* - * The name property. - */ - @JsonProperty(value = "name") - private String name; - - /* - * The createdTimeUtc property. - */ - @JsonProperty(value = "createdTimeUtc") - private OffsetDateTime createdTimeUtc; - - /* - * The updatedTimeUtc property. - */ - @JsonProperty(value = "updatedTimeUtc") - private OffsetDateTime updatedTimeUtc; - - /* - * The schemaType property. - */ - @JsonProperty(value = "schemaType") - private String schemaType; - - /* - * schema compatibility mode enum, defined by supported schema type - */ - @JsonProperty(value = "schemaCompatibility") - private Integer schemaCompatibility; - - /* - * Dictionary of - */ - @JsonProperty(value = "groupProperties") - private Map groupProperties; - - /** - * Get the name property: The name property. - * - * @return the name value. - */ - public String getName() { - return this.name; - } - - /** - * Set the name property: The name property. - * - * @param name the name value to set. - * @return the SchemaGroup object itself. - */ - public SchemaGroup setName(String name) { - this.name = name; - return this; - } - - /** - * Get the createdTimeUtc property: The createdTimeUtc property. - * - * @return the createdTimeUtc value. - */ - public OffsetDateTime getCreatedTimeUtc() { - return this.createdTimeUtc; - } - - /** - * Set the createdTimeUtc property: The createdTimeUtc property. - * - * @param createdTimeUtc the createdTimeUtc value to set. - * @return the SchemaGroup object itself. - */ - public SchemaGroup setCreatedTimeUtc(OffsetDateTime createdTimeUtc) { - this.createdTimeUtc = createdTimeUtc; - return this; - } - - /** - * Get the updatedTimeUtc property: The updatedTimeUtc property. - * - * @return the updatedTimeUtc value. - */ - public OffsetDateTime getUpdatedTimeUtc() { - return this.updatedTimeUtc; - } - - /** - * Set the updatedTimeUtc property: The updatedTimeUtc property. - * - * @param updatedTimeUtc the updatedTimeUtc value to set. - * @return the SchemaGroup object itself. - */ - public SchemaGroup setUpdatedTimeUtc(OffsetDateTime updatedTimeUtc) { - this.updatedTimeUtc = updatedTimeUtc; - return this; - } - - /** - * Get the schemaType property: The schemaType property. - * - * @return the schemaType value. - */ - public String getSchemaType() { - return this.schemaType; - } - - /** - * Set the schemaType property: The schemaType property. - * - * @param schemaType the schemaType value to set. - * @return the SchemaGroup object itself. - */ - public SchemaGroup setSchemaType(String schemaType) { - this.schemaType = schemaType; - return this; - } - - /** - * Get the schemaCompatibility property: schema compatibility mode enum, defined by supported schema type. - * - * @return the schemaCompatibility value. - */ - public Integer getSchemaCompatibility() { - return this.schemaCompatibility; - } - - /** - * Set the schemaCompatibility property: schema compatibility mode enum, defined by supported schema type. - * - * @param schemaCompatibility the schemaCompatibility value to set. - * @return the SchemaGroup object itself. - */ - public SchemaGroup setSchemaCompatibility(Integer schemaCompatibility) { - this.schemaCompatibility = schemaCompatibility; - return this; - } - - /** - * Get the groupProperties property: Dictionary of <string>. - * - * @return the groupProperties value. - */ - public Map getGroupProperties() { - return this.groupProperties; - } - - /** - * Set the groupProperties property: Dictionary of <string>. - * - * @param groupProperties the groupProperties value to set. - * @return the SchemaGroup object itself. - */ - public SchemaGroup setGroupProperties(Map groupProperties) { - this.groupProperties = groupProperties; - return this; - } - - /** - * Validates the instance. - * - * @throws IllegalArgumentException thrown if the instance is not valid. - */ - public void validate() { } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/package-info.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/package-info.java deleted file mode 100644 index cdb3fcbbeaf8d..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/package-info.java +++ /dev/null @@ -1,2 +0,0 @@ -/** Package containing the data models for AzureSchemaRegistryRestService. null. */ -package com.azure.data.schemaregistry.client.implementation.models; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/package-info.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/package-info.java deleted file mode 100644 index b9afd3e65bc9c..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/package-info.java +++ /dev/null @@ -1,2 +0,0 @@ -/** Package containing the classes for AzureSchemaRegistryRestService. null. */ -package com.azure.data.schemaregistry.client.implementation; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/package-info.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/package-info.java deleted file mode 100644 index f6da76235f3a0..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Package containing the classes for - * - SchemaRegistryClient interface - * - CachedSchemaRegistryClient - * - AzureSchemaRegistryRestService. - */ -package com.azure.data.schemaregistry.client; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistry.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistry.java new file mode 100644 index 0000000000000..ecb3e24092e3f --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistry.java @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.implementation; + +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.CookiePolicy; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.core.util.serializer.SerializerAdapter; + +/** Initializes a new instance of the AzureSchemaRegistry type. */ +public final class AzureSchemaRegistry { + /** The Schema Registry service endpoint, for example my-namespace.servicebus.windows.net. */ + private final String endpoint; + + /** + * Gets The Schema Registry service endpoint, for example my-namespace.servicebus.windows.net. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** Api Version. */ + private final String apiVersion; + + /** + * Gets Api Version. + * + * @return the apiVersion value. + */ + public String getApiVersion() { + return this.apiVersion; + } + + /** The HTTP pipeline to send requests through. */ + private final HttpPipeline httpPipeline; + + /** + * Gets The HTTP pipeline to send requests through. + * + * @return the httpPipeline value. + */ + public HttpPipeline getHttpPipeline() { + return this.httpPipeline; + } + + /** The serializer to serialize an object into a string. */ + private final SerializerAdapter serializerAdapter; + + /** + * Gets The serializer to serialize an object into a string. + * + * @return the serializerAdapter value. + */ + public SerializerAdapter getSerializerAdapter() { + return this.serializerAdapter; + } + + /** The Schemas object to access its operations. */ + private final Schemas schemas; + + /** + * Gets the Schemas object to access its operations. + * + * @return the Schemas object. + */ + public Schemas getSchemas() { + return this.schemas; + } + + /** Initializes an instance of AzureSchemaRegistry client. */ + AzureSchemaRegistry(String endpoint) { + this( + new HttpPipelineBuilder() + .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) + .build(), + JacksonAdapter.createDefaultSerializerAdapter(), + endpoint); + } + + /** + * Initializes an instance of AzureSchemaRegistry client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + */ + AzureSchemaRegistry(HttpPipeline httpPipeline, String endpoint) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint); + } + + /** + * Initializes an instance of AzureSchemaRegistry client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param serializerAdapter The serializer to serialize an object into a string. + */ + AzureSchemaRegistry(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.endpoint = endpoint; + this.apiVersion = "2020-09-01-preview"; + this.schemas = new Schemas(this); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistryBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistryBuilder.java new file mode 100644 index 0000000000000..c9c90cc074dc1 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistryBuilder.java @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.implementation; + +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.CookiePolicy; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.HttpLoggingPolicy; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.core.http.policy.HttpPolicyProviders; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.util.Configuration; +import com.azure.core.util.ServiceVersion; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.core.util.serializer.SerializerAdapter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** A builder for creating a new instance of the AzureSchemaRegistry type. */ +@ServiceClientBuilder(serviceClients = {AzureSchemaRegistry.class}) +public final class AzureSchemaRegistryBuilder { + private static final String SDK_NAME = "name"; + + private static final String SDK_VERSION = "version"; + + private final Map properties = new HashMap<>(); + + public AzureSchemaRegistryBuilder() { + this.pipelinePolicies = new ArrayList<>(); + } + + /* + * The Schema Registry service endpoint, for example + * my-namespace.servicebus.windows.net. + */ + private String endpoint; + + /** + * Sets The Schema Registry service endpoint, for example my-namespace.servicebus.windows.net. + * + * @param endpoint the endpoint value. + * @return the AzureSchemaRegistryBuilder. + */ + public AzureSchemaRegistryBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /* + * The HTTP pipeline to send requests through + */ + private HttpPipeline pipeline; + + /** + * Sets The HTTP pipeline to send requests through. + * + * @param pipeline the pipeline value. + * @return the AzureSchemaRegistryBuilder. + */ + public AzureSchemaRegistryBuilder pipeline(HttpPipeline pipeline) { + this.pipeline = pipeline; + return this; + } + + /* + * The serializer to serialize an object into a string + */ + private SerializerAdapter serializerAdapter; + + /** + * Sets The serializer to serialize an object into a string. + * + * @param serializerAdapter the serializerAdapter value. + * @return the AzureSchemaRegistryBuilder. + */ + public AzureSchemaRegistryBuilder serializerAdapter(SerializerAdapter serializerAdapter) { + this.serializerAdapter = serializerAdapter; + return this; + } + + /* + * The HTTP client used to send the request. + */ + private HttpClient httpClient; + + /** + * Sets The HTTP client used to send the request. + * + * @param httpClient the httpClient value. + * @return the AzureSchemaRegistryBuilder. + */ + public AzureSchemaRegistryBuilder httpClient(HttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /* + * The configuration store that is used during construction of the service + * client. + */ + private Configuration configuration; + + /** + * Sets The configuration store that is used during construction of the service client. + * + * @param configuration the configuration value. + * @return the AzureSchemaRegistryBuilder. + */ + public AzureSchemaRegistryBuilder configuration(Configuration configuration) { + this.configuration = configuration; + return this; + } + + /* + * The logging configuration for HTTP requests and responses. + */ + private HttpLogOptions httpLogOptions; + + /** + * Sets The logging configuration for HTTP requests and responses. + * + * @param httpLogOptions the httpLogOptions value. + * @return the AzureSchemaRegistryBuilder. + */ + public AzureSchemaRegistryBuilder httpLogOptions(HttpLogOptions httpLogOptions) { + this.httpLogOptions = httpLogOptions; + return this; + } + + /* + * The retry policy that will attempt to retry failed requests, if + * applicable. + */ + private RetryPolicy retryPolicy; + + /** + * Sets The retry policy that will attempt to retry failed requests, if applicable. + * + * @param retryPolicy the retryPolicy value. + * @return the AzureSchemaRegistryBuilder. + */ + public AzureSchemaRegistryBuilder retryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; + return this; + } + + /* + * The list of Http pipeline policies to add. + */ + private List pipelinePolicies; + + /** + * Adds a custom Http pipeline policy. + * + * @param customPolicy The custom Http pipeline policy to add. + * @return the AzureSchemaRegistryBuilder. + */ + public AzureSchemaRegistryBuilder addPolicy(HttpPipelinePolicy customPolicy) { + pipelinePolicies.add(customPolicy); + return this; + } + + /** + * Builds an instance of AzureSchemaRegistry with the provided parameters. + * + * @return an instance of AzureSchemaRegistry. + */ + public AzureSchemaRegistry buildClient() { + if (pipeline == null) { + this.pipeline = createHttpPipeline(); + } + if (serializerAdapter == null) { + this.serializerAdapter = JacksonAdapter.createDefaultSerializerAdapter(); + } + AzureSchemaRegistry client = new AzureSchemaRegistry(pipeline, serializerAdapter, endpoint); + return client; + } + + private HttpPipeline createHttpPipeline() { + Configuration buildConfiguration = + (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; + if (httpLogOptions == null) { + httpLogOptions = new HttpLogOptions(); + } + List policies = new ArrayList<>(); + String clientName = properties.getOrDefault(SDK_NAME, "UnknownName"); + String clientVersion = properties.getOrDefault(SDK_VERSION, "UnknownVersion"); + policies.add( + new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); + HttpPolicyProviders.addBeforeRetryPolicies(policies); + policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); + policies.add(new CookiePolicy()); + policies.addAll(this.pipelinePolicies); + HttpPolicyProviders.addAfterRetryPolicies(policies); + policies.add(new HttpLoggingPolicy(httpLogOptions)); + HttpPipeline httpPipeline = + new HttpPipelineBuilder() + .policies(policies.toArray(new HttpPipelinePolicy[0])) + .httpClient(httpClient) + .build(); + return httpPipeline; + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/Schemas.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/Schemas.java new file mode 100644 index 0000000000000..03242e7385163 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/Schemas.java @@ -0,0 +1,338 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.HeaderParam; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.Put; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.data.schemaregistry.implementation.models.SchemaId; +import com.azure.data.schemaregistry.implementation.models.SchemasQueryIdByContentResponse; +import com.azure.data.schemaregistry.implementation.models.SchemasGetByIdResponse; +import com.azure.data.schemaregistry.implementation.models.SchemasRegisterResponse; +import com.azure.data.schemaregistry.implementation.models.SerializationType; +import com.azure.data.schemaregistry.implementation.models.ServiceErrorResponseException; +import reactor.core.publisher.Mono; + +/** An instance of this class provides access to all the operations defined in Schemas. */ +public final class Schemas { + /** The proxy service used to perform REST calls. */ + private final SchemasService service; + + /** The service client containing this operation class. */ + private final AzureSchemaRegistry client; + + /** + * Initializes an instance of Schemas. + * + * @param client the instance of the service client containing this operation class. + */ + Schemas(AzureSchemaRegistry client) { + this.service = RestProxy.create(SchemasService.class, client.getHttpPipeline(), client.getSerializerAdapter()); + this.client = client; + } + + /** + * The interface defining all the services for AzureSchemaRegistrySchemas to be used by the proxy service to perform + * REST calls. + */ + @Host("https://{endpoint}") + @ServiceInterface(name = "AzureSchemaRegistryS") + private interface SchemasService { + @Get("/$schemagroups/getSchemaById/{schema-id}") + @ExpectedResponses({200}) + @UnexpectedResponseExceptionType(ServiceErrorResponseException.class) + Mono getById( + @HostParam("endpoint") String endpoint, + @PathParam("schema-id") String schemaId, + @QueryParam("api-version") String apiVersion, + Context context); + + @Post("/$schemagroups/{group-name}/schemas/{schema-name}") + @ExpectedResponses({200}) + @UnexpectedResponseExceptionType(ServiceErrorResponseException.class) + Mono queryIdByContent( + @HostParam("endpoint") String endpoint, + @PathParam("group-name") String groupName, + @PathParam("schema-name") String schemaName, + @HeaderParam("Serialization-Type") SerializationType xSchemaType, + @QueryParam("api-version") String apiVersion, + @BodyParam("application/json") String schemaContent, + Context context); + + @Put("/$schemagroups/{group-name}/schemas/{schema-name}") + @ExpectedResponses({200}) + @UnexpectedResponseExceptionType(ServiceErrorResponseException.class) + Mono register( + @HostParam("endpoint") String endpoint, + @PathParam("group-name") String groupName, + @PathParam("schema-name") String schemaName, + @HeaderParam("Serialization-Type") SerializationType xSchemaType, + @QueryParam("api-version") String apiVersion, + @BodyParam("application/json") String schemaContent, + Context context); + } + + /** + * Gets a registered schema by its unique ID. Azure Schema Registry guarantees that ID is unique within a namespace. + * + * @param schemaId References specific schema in registry namespace. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ServiceErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a registered schema by its unique ID. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getByIdWithResponseAsync(String schemaId) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException( + "Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (schemaId == null) { + return Mono.error(new IllegalArgumentException("Parameter schemaId is required and cannot be null.")); + } + return FluxUtil.withContext( + context -> service.getById(this.client.getEndpoint(), schemaId, this.client.getApiVersion(), context)); + } + + /** + * Gets a registered schema by its unique ID. Azure Schema Registry guarantees that ID is unique within a namespace. + * + * @param schemaId References specific schema in registry namespace. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ServiceErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a registered schema by its unique ID. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getByIdAsync(String schemaId) { + return getByIdWithResponseAsync(schemaId) + .flatMap( + (SchemasGetByIdResponse res) -> { + if (res.getValue() != null) { + return Mono.just(res.getValue()); + } else { + return Mono.empty(); + } + }); + } + + /** + * Gets a registered schema by its unique ID. Azure Schema Registry guarantees that ID is unique within a namespace. + * + * @param schemaId References specific schema in registry namespace. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ServiceErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return a registered schema by its unique ID. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public String getById(String schemaId) { + return getByIdAsync(schemaId).block(); + } + + /** + * Gets the ID referencing an existing schema within the specified schema group, as matched by schema content + * comparison. + * + * @param groupName Schema group under which schema is registered. Group's serialization type should match the + * serialization type specified in the request. + * @param schemaName Name of the registered schema. + * @param xSchemaType Serialization type for the schema being registered. + * @param schemaContent String representation of the registered schema. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ServiceErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the ID referencing an existing schema within the specified schema group, as matched by schema content + * comparison. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono queryIdByContentWithResponseAsync( + String groupName, String schemaName, SerializationType xSchemaType, String schemaContent) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException( + "Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (schemaName == null) { + return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); + } + if (xSchemaType == null) { + return Mono.error(new IllegalArgumentException("Parameter xSchemaType is required and cannot be null.")); + } + if (schemaContent == null) { + return Mono.error(new IllegalArgumentException("Parameter schemaContent is required and cannot be null.")); + } + return FluxUtil.withContext( + context -> + service.queryIdByContent( + this.client.getEndpoint(), + groupName, + schemaName, + xSchemaType, + this.client.getApiVersion(), + schemaContent, + context)); + } + + /** + * Gets the ID referencing an existing schema within the specified schema group, as matched by schema content + * comparison. + * + * @param groupName Schema group under which schema is registered. Group's serialization type should match the + * serialization type specified in the request. + * @param schemaName Name of the registered schema. + * @param xSchemaType Serialization type for the schema being registered. + * @param schemaContent String representation of the registered schema. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ServiceErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the ID referencing an existing schema within the specified schema group, as matched by schema content + * comparison. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono queryIdByContentAsync( + String groupName, String schemaName, SerializationType xSchemaType, String schemaContent) { + return queryIdByContentWithResponseAsync(groupName, schemaName, xSchemaType, schemaContent) + .flatMap( + (SchemasQueryIdByContentResponse res) -> { + if (res.getValue() != null) { + return Mono.just(res.getValue()); + } else { + return Mono.empty(); + } + }); + } + + /** + * Gets the ID referencing an existing schema within the specified schema group, as matched by schema content + * comparison. + * + * @param groupName Schema group under which schema is registered. Group's serialization type should match the + * serialization type specified in the request. + * @param schemaName Name of the registered schema. + * @param xSchemaType Serialization type for the schema being registered. + * @param schemaContent String representation of the registered schema. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ServiceErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return the ID referencing an existing schema within the specified schema group, as matched by schema content + * comparison. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SchemaId queryIdByContent( + String groupName, String schemaName, SerializationType xSchemaType, String schemaContent) { + return queryIdByContentAsync(groupName, schemaName, xSchemaType, schemaContent).block(); + } + + /** + * Register new schema. If schema of specified name does not exist in specified group, schema is created at version + * 1. If schema of specified name exists already in specified group, schema is created at latest version + 1. + * + * @param groupName Schema group under which schema should be registered. Group's serialization type should match + * the serialization type specified in the request. + * @param schemaName Name of schema being registered. + * @param xSchemaType Serialization type for the schema being registered. + * @param schemaContent String representation of the schema being registered. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ServiceErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return jSON Object received from the registry containing schema identifiers. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono registerWithResponseAsync( + String groupName, String schemaName, SerializationType xSchemaType, String schemaContent) { + if (this.client.getEndpoint() == null) { + return Mono.error( + new IllegalArgumentException( + "Parameter this.client.getEndpoint() is required and cannot be null.")); + } + if (groupName == null) { + return Mono.error(new IllegalArgumentException("Parameter groupName is required and cannot be null.")); + } + if (schemaName == null) { + return Mono.error(new IllegalArgumentException("Parameter schemaName is required and cannot be null.")); + } + if (xSchemaType == null) { + return Mono.error(new IllegalArgumentException("Parameter xSchemaType is required and cannot be null.")); + } + if (schemaContent == null) { + return Mono.error(new IllegalArgumentException("Parameter schemaContent is required and cannot be null.")); + } + return FluxUtil.withContext( + context -> + service.register( + this.client.getEndpoint(), + groupName, + schemaName, + xSchemaType, + this.client.getApiVersion(), + schemaContent, + context)); + } + + /** + * Register new schema. If schema of specified name does not exist in specified group, schema is created at version + * 1. If schema of specified name exists already in specified group, schema is created at latest version + 1. + * + * @param groupName Schema group under which schema should be registered. Group's serialization type should match + * the serialization type specified in the request. + * @param schemaName Name of schema being registered. + * @param xSchemaType Serialization type for the schema being registered. + * @param schemaContent String representation of the schema being registered. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ServiceErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return jSON Object received from the registry containing schema identifiers. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono registerAsync( + String groupName, String schemaName, SerializationType xSchemaType, String schemaContent) { + return registerWithResponseAsync(groupName, schemaName, xSchemaType, schemaContent) + .flatMap( + (SchemasRegisterResponse res) -> { + if (res.getValue() != null) { + return Mono.just(res.getValue()); + } else { + return Mono.empty(); + } + }); + } + + /** + * Register new schema. If schema of specified name does not exist in specified group, schema is created at version + * 1. If schema of specified name exists already in specified group, schema is created at latest version + 1. + * + * @param groupName Schema group under which schema should be registered. Group's serialization type should match + * the serialization type specified in the request. + * @param schemaName Name of schema being registered. + * @param xSchemaType Serialization type for the schema being registered. + * @param schemaContent String representation of the schema being registered. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @throws ServiceErrorResponseException thrown if the request is rejected by server. + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + * @return jSON Object received from the registry containing schema identifiers. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SchemaId register(String groupName, String schemaName, SerializationType xSchemaType, String schemaContent) { + return registerAsync(groupName, schemaName, xSchemaType, schemaContent).block(); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/SchemaId.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemaId.java similarity index 67% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/SchemaId.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemaId.java index 6fa7927c4cc49..992882faa2808 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/SchemaId.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemaId.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client.implementation.models; +package com.azure.data.schemaregistry.implementation.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; @@ -10,13 +10,13 @@ @Fluent public final class SchemaId { /* - * The id property. + * Schema ID that uniquely identifies a schema in the registry namespace. */ @JsonProperty(value = "id") private String id; /** - * Get the id property: The id property. + * Get the id property: Schema ID that uniquely identifies a schema in the registry namespace. * * @return the id value. */ @@ -25,7 +25,7 @@ public String getId() { } /** - * Set the id property: The id property. + * Set the id property: Schema ID that uniquely identifies a schema in the registry namespace. * * @param id the id value to set. * @return the SchemaId object itself. @@ -40,5 +40,5 @@ public SchemaId setId(String id) { * * @throws IllegalArgumentException thrown if the instance is not valid. */ - public void validate() { } + public void validate() {} } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateSchemaHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdHeaders.java similarity index 77% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateSchemaHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdHeaders.java index fcdac46e5b9f0..6dc170e592835 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateSchemaHeaders.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdHeaders.java @@ -1,15 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client.implementation.models; +package com.azure.data.schemaregistry.implementation.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; -import java.net.URL; -/** The CreateSchemaHeaders model. */ +/** The SchemasGetByIdHeaders model. */ @Fluent -public final class CreateSchemaHeaders { +public final class SchemasGetByIdHeaders { /* * The X-Schema-Version property. */ @@ -32,7 +31,7 @@ public final class CreateSchemaHeaders { * The X-Schema-Id-Location property. */ @JsonProperty(value = "X-Schema-Id-Location") - private URL xSchemaIdLocation; + private String xSchemaIdLocation; /* * The Location property. @@ -53,9 +52,9 @@ public Integer getXSchemaVersion() { * Set the xSchemaVersion property: The X-Schema-Version property. * * @param xSchemaVersion the xSchemaVersion value to set. - * @return the CreateSchemaHeaders object itself. + * @return the SchemasGetByIdHeaders object itself. */ - public CreateSchemaHeaders setXSchemaVersion(Integer xSchemaVersion) { + public SchemasGetByIdHeaders setXSchemaVersion(Integer xSchemaVersion) { this.xSchemaVersion = xSchemaVersion; return this; } @@ -73,9 +72,9 @@ public String getXSchemaType() { * Set the xSchemaType property: The X-Schema-Type property. * * @param xSchemaType the xSchemaType value to set. - * @return the CreateSchemaHeaders object itself. + * @return the SchemasGetByIdHeaders object itself. */ - public CreateSchemaHeaders setXSchemaType(String xSchemaType) { + public SchemasGetByIdHeaders setXSchemaType(String xSchemaType) { this.xSchemaType = xSchemaType; return this; } @@ -93,9 +92,9 @@ public String getXSchemaId() { * Set the xSchemaId property: The X-Schema-Id property. * * @param xSchemaId the xSchemaId value to set. - * @return the CreateSchemaHeaders object itself. + * @return the SchemasGetByIdHeaders object itself. */ - public CreateSchemaHeaders setXSchemaId(String xSchemaId) { + public SchemasGetByIdHeaders setXSchemaId(String xSchemaId) { this.xSchemaId = xSchemaId; return this; } @@ -105,7 +104,7 @@ public CreateSchemaHeaders setXSchemaId(String xSchemaId) { * * @return the xSchemaIdLocation value. */ - public URL getXSchemaIdLocation() { + public String getXSchemaIdLocation() { return this.xSchemaIdLocation; } @@ -113,9 +112,9 @@ public URL getXSchemaIdLocation() { * Set the xSchemaIdLocation property: The X-Schema-Id-Location property. * * @param xSchemaIdLocation the xSchemaIdLocation value to set. - * @return the CreateSchemaHeaders object itself. + * @return the SchemasGetByIdHeaders object itself. */ - public CreateSchemaHeaders setXSchemaIdLocation(URL xSchemaIdLocation) { + public SchemasGetByIdHeaders setXSchemaIdLocation(String xSchemaIdLocation) { this.xSchemaIdLocation = xSchemaIdLocation; return this; } @@ -133,9 +132,9 @@ public String getLocation() { * Set the location property: The Location property. * * @param location the location value to set. - * @return the CreateSchemaHeaders object itself. + * @return the SchemasGetByIdHeaders object itself. */ - public CreateSchemaHeaders setLocation(String location) { + public SchemasGetByIdHeaders setLocation(String location) { this.location = location; return this; } @@ -145,5 +144,5 @@ public CreateSchemaHeaders setLocation(String location) { * * @throws IllegalArgumentException thrown if the instance is not valid. */ - public void validate() { } + public void validate() {} } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaByIdResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdResponse.java similarity index 63% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaByIdResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdResponse.java index 9f5f8392a987c..548619675165d 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaByIdResponse.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdResponse.java @@ -1,25 +1,25 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client.implementation.models; +package com.azure.data.schemaregistry.implementation.models; import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpRequest; import com.azure.core.http.rest.ResponseBase; -/** Contains all response data for the getSchemaById operation. */ -public final class GetSchemaByIdResponse extends ResponseBase { +/** Contains all response data for the getById operation. */ +public final class SchemasGetByIdResponse extends ResponseBase { /** - * Creates an instance of GetSchemaByIdResponse. + * Creates an instance of SchemasGetByIdResponse. * - * @param request the request which resulted in this GetSchemaByIdResponse. + * @param request the request which resulted in this SchemasGetByIdResponse. * @param statusCode the status code of the HTTP response. * @param rawHeaders the raw headers of the HTTP response. * @param value the deserialized value of the HTTP response. * @param headers the deserialized headers of the HTTP response. */ - public GetSchemaByIdResponse( - HttpRequest request, int statusCode, HttpHeaders rawHeaders, String value, GetSchemaByIdHeaders headers) { + public SchemasGetByIdResponse( + HttpRequest request, int statusCode, HttpHeaders rawHeaders, String value, SchemasGetByIdHeaders headers) { super(request, statusCode, rawHeaders, value, headers); } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaByIdHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentHeaders.java similarity index 75% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaByIdHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentHeaders.java index cb6e7f5df9478..1ea51172bc5bd 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaByIdHeaders.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentHeaders.java @@ -1,15 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client.implementation.models; +package com.azure.data.schemaregistry.implementation.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; -import java.net.URL; -/** The GetSchemaByIdHeaders model. */ +/** The SchemasQueryIdByContentHeaders model. */ @Fluent -public final class GetSchemaByIdHeaders { +public final class SchemasQueryIdByContentHeaders { /* * The X-Schema-Version property. */ @@ -32,7 +31,7 @@ public final class GetSchemaByIdHeaders { * The X-Schema-Id-Location property. */ @JsonProperty(value = "X-Schema-Id-Location") - private URL xSchemaIdLocation; + private String xSchemaIdLocation; /* * The Location property. @@ -53,9 +52,9 @@ public Integer getXSchemaVersion() { * Set the xSchemaVersion property: The X-Schema-Version property. * * @param xSchemaVersion the xSchemaVersion value to set. - * @return the GetSchemaByIdHeaders object itself. + * @return the SchemasQueryIdByContentHeaders object itself. */ - public GetSchemaByIdHeaders setXSchemaVersion(Integer xSchemaVersion) { + public SchemasQueryIdByContentHeaders setXSchemaVersion(Integer xSchemaVersion) { this.xSchemaVersion = xSchemaVersion; return this; } @@ -73,9 +72,9 @@ public String getXSchemaType() { * Set the xSchemaType property: The X-Schema-Type property. * * @param xSchemaType the xSchemaType value to set. - * @return the GetSchemaByIdHeaders object itself. + * @return the SchemasQueryIdByContentHeaders object itself. */ - public GetSchemaByIdHeaders setXSchemaType(String xSchemaType) { + public SchemasQueryIdByContentHeaders setXSchemaType(String xSchemaType) { this.xSchemaType = xSchemaType; return this; } @@ -93,9 +92,9 @@ public String getXSchemaId() { * Set the xSchemaId property: The X-Schema-Id property. * * @param xSchemaId the xSchemaId value to set. - * @return the GetSchemaByIdHeaders object itself. + * @return the SchemasQueryIdByContentHeaders object itself. */ - public GetSchemaByIdHeaders setXSchemaId(String xSchemaId) { + public SchemasQueryIdByContentHeaders setXSchemaId(String xSchemaId) { this.xSchemaId = xSchemaId; return this; } @@ -105,7 +104,7 @@ public GetSchemaByIdHeaders setXSchemaId(String xSchemaId) { * * @return the xSchemaIdLocation value. */ - public URL getXSchemaIdLocation() { + public String getXSchemaIdLocation() { return this.xSchemaIdLocation; } @@ -113,9 +112,9 @@ public URL getXSchemaIdLocation() { * Set the xSchemaIdLocation property: The X-Schema-Id-Location property. * * @param xSchemaIdLocation the xSchemaIdLocation value to set. - * @return the GetSchemaByIdHeaders object itself. + * @return the SchemasQueryIdByContentHeaders object itself. */ - public GetSchemaByIdHeaders setXSchemaIdLocation(URL xSchemaIdLocation) { + public SchemasQueryIdByContentHeaders setXSchemaIdLocation(String xSchemaIdLocation) { this.xSchemaIdLocation = xSchemaIdLocation; return this; } @@ -133,9 +132,9 @@ public String getLocation() { * Set the location property: The Location property. * * @param location the location value to set. - * @return the GetSchemaByIdHeaders object itself. + * @return the SchemasQueryIdByContentHeaders object itself. */ - public GetSchemaByIdHeaders setLocation(String location) { + public SchemasQueryIdByContentHeaders setLocation(String location) { this.location = location; return this; } @@ -145,5 +144,5 @@ public GetSchemaByIdHeaders setLocation(String location) { * * @throws IllegalArgumentException thrown if the instance is not valid. */ - public void validate() { } + public void validate() {} } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentResponse.java similarity index 58% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentResponse.java index 4b4f3bfbc24c1..84351f4b293f1 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionResponse.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentResponse.java @@ -1,35 +1,35 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client.implementation.models; +package com.azure.data.schemaregistry.implementation.models; import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpRequest; import com.azure.core.http.rest.ResponseBase; -/** Contains all response data for the getSchemaVersion operation. */ -public final class GetSchemaVersionResponse extends ResponseBase { +/** Contains all response data for the queryIdByContent operation. */ +public final class SchemasQueryIdByContentResponse extends ResponseBase { /** - * Creates an instance of GetSchemaVersionResponse. + * Creates an instance of SchemasQueryIdByContentResponse. * - * @param request the request which resulted in this GetSchemaVersionResponse. + * @param request the request which resulted in this SchemasQueryIdByContentResponse. * @param statusCode the status code of the HTTP response. * @param rawHeaders the raw headers of the HTTP response. * @param value the deserialized value of the HTTP response. * @param headers the deserialized headers of the HTTP response. */ - public GetSchemaVersionResponse( + public SchemasQueryIdByContentResponse( HttpRequest request, int statusCode, HttpHeaders rawHeaders, - String value, - GetSchemaVersionHeaders headers) { + SchemaId value, + SchemasQueryIdByContentHeaders headers) { super(request, statusCode, rawHeaders, value, headers); } /** @return the deserialized response body. */ @Override - public String getValue() { + public SchemaId getValue() { return super.getValue(); } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetLatestSchemaHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterHeaders.java similarity index 77% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetLatestSchemaHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterHeaders.java index 6fc62f9ad8093..7acb1bffe084a 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetLatestSchemaHeaders.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterHeaders.java @@ -1,15 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client.implementation.models; +package com.azure.data.schemaregistry.implementation.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; -import java.net.URL; -/** The GetLatestSchemaHeaders model. */ +/** The SchemasRegisterHeaders model. */ @Fluent -public final class GetLatestSchemaHeaders { +public final class SchemasRegisterHeaders { /* * The X-Schema-Version property. */ @@ -32,7 +31,7 @@ public final class GetLatestSchemaHeaders { * The X-Schema-Id-Location property. */ @JsonProperty(value = "X-Schema-Id-Location") - private URL xSchemaIdLocation; + private String xSchemaIdLocation; /* * The Location property. @@ -53,9 +52,9 @@ public Integer getXSchemaVersion() { * Set the xSchemaVersion property: The X-Schema-Version property. * * @param xSchemaVersion the xSchemaVersion value to set. - * @return the GetLatestSchemaHeaders object itself. + * @return the SchemasRegisterHeaders object itself. */ - public GetLatestSchemaHeaders setXSchemaVersion(Integer xSchemaVersion) { + public SchemasRegisterHeaders setXSchemaVersion(Integer xSchemaVersion) { this.xSchemaVersion = xSchemaVersion; return this; } @@ -73,9 +72,9 @@ public String getXSchemaType() { * Set the xSchemaType property: The X-Schema-Type property. * * @param xSchemaType the xSchemaType value to set. - * @return the GetLatestSchemaHeaders object itself. + * @return the SchemasRegisterHeaders object itself. */ - public GetLatestSchemaHeaders setXSchemaType(String xSchemaType) { + public SchemasRegisterHeaders setXSchemaType(String xSchemaType) { this.xSchemaType = xSchemaType; return this; } @@ -93,9 +92,9 @@ public String getXSchemaId() { * Set the xSchemaId property: The X-Schema-Id property. * * @param xSchemaId the xSchemaId value to set. - * @return the GetLatestSchemaHeaders object itself. + * @return the SchemasRegisterHeaders object itself. */ - public GetLatestSchemaHeaders setXSchemaId(String xSchemaId) { + public SchemasRegisterHeaders setXSchemaId(String xSchemaId) { this.xSchemaId = xSchemaId; return this; } @@ -105,7 +104,7 @@ public GetLatestSchemaHeaders setXSchemaId(String xSchemaId) { * * @return the xSchemaIdLocation value. */ - public URL getXSchemaIdLocation() { + public String getXSchemaIdLocation() { return this.xSchemaIdLocation; } @@ -113,9 +112,9 @@ public URL getXSchemaIdLocation() { * Set the xSchemaIdLocation property: The X-Schema-Id-Location property. * * @param xSchemaIdLocation the xSchemaIdLocation value to set. - * @return the GetLatestSchemaHeaders object itself. + * @return the SchemasRegisterHeaders object itself. */ - public GetLatestSchemaHeaders setXSchemaIdLocation(URL xSchemaIdLocation) { + public SchemasRegisterHeaders setXSchemaIdLocation(String xSchemaIdLocation) { this.xSchemaIdLocation = xSchemaIdLocation; return this; } @@ -133,9 +132,9 @@ public String getLocation() { * Set the location property: The Location property. * * @param location the location value to set. - * @return the GetLatestSchemaHeaders object itself. + * @return the SchemasRegisterHeaders object itself. */ - public GetLatestSchemaHeaders setLocation(String location) { + public SchemasRegisterHeaders setLocation(String location) { this.location = location; return this; } @@ -145,5 +144,5 @@ public GetLatestSchemaHeaders setLocation(String location) { * * @throws IllegalArgumentException thrown if the instance is not valid. */ - public void validate() { } + public void validate() {} } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetIdBySchemaContentResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterResponse.java similarity index 63% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetIdBySchemaContentResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterResponse.java index 4061fd93f9370..08dde0ba56c74 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetIdBySchemaContentResponse.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterResponse.java @@ -1,29 +1,29 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client.implementation.models; +package com.azure.data.schemaregistry.implementation.models; import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpRequest; import com.azure.core.http.rest.ResponseBase; -/** Contains all response data for the getIdBySchemaContent operation. */ -public final class GetIdBySchemaContentResponse extends ResponseBase { +/** Contains all response data for the register operation. */ +public final class SchemasRegisterResponse extends ResponseBase { /** - * Creates an instance of GetIdBySchemaContentResponse. + * Creates an instance of SchemasRegisterResponse. * - * @param request the request which resulted in this GetIdBySchemaContentResponse. + * @param request the request which resulted in this SchemasRegisterResponse. * @param statusCode the status code of the HTTP response. * @param rawHeaders the raw headers of the HTTP response. * @param value the deserialized value of the HTTP response. * @param headers the deserialized headers of the HTTP response. */ - public GetIdBySchemaContentResponse( + public SchemasRegisterResponse( HttpRequest request, int statusCode, HttpHeaders rawHeaders, SchemaId value, - GetIdBySchemaContentHeaders headers) { + SchemasRegisterHeaders headers) { super(request, statusCode, rawHeaders, value, headers); } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SerializationType.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SerializationType.java new file mode 100644 index 0000000000000..ec9f2b902fd58 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SerializationType.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.implementation.models; + +import com.azure.core.util.ExpandableStringEnum; +import com.fasterxml.jackson.annotation.JsonCreator; +import java.util.Collection; + +/** Defines values for SerializationType. */ +public final class SerializationType extends ExpandableStringEnum { + /** Static value avro for SerializationType. */ + public static final SerializationType AVRO = fromString("avro"); + + /** + * Creates or finds a SerializationType from its string representation. + * + * @param name a name to look for. + * @return the corresponding SerializationType. + */ + @JsonCreator + public static SerializationType fromString(String name) { + return fromString(name, SerializationType.class); + } + + /** @return known SerializationType values. */ + public static Collection values() { + return values(SerializationType.class); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/ServiceErrorResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/ServiceErrorResponse.java new file mode 100644 index 0000000000000..f5a4167e78abc --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/ServiceErrorResponse.java @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** The ServiceErrorResponse model. */ +@Fluent +public final class ServiceErrorResponse { + /* + * The error message + */ + @JsonProperty(value = "message") + private String message; + + /** + * Get the message property: The error message. + * + * @return the message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Set the message property: The error message. + * + * @param message the message value to set. + * @return the ServiceErrorResponse object itself. + */ + public ServiceErrorResponse setMessage(String message) { + this.message = message; + return this; + } + + /** + * Validates the instance. + * + * @throws IllegalArgumentException thrown if the instance is not valid. + */ + public void validate() {} +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/ServiceErrorResponseException.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/ServiceErrorResponseException.java new file mode 100644 index 0000000000000..6bafbfcdf5d57 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/ServiceErrorResponseException.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.implementation.models; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.HttpResponse; + +/** Exception thrown for an invalid response with ServiceErrorResponse information. */ +public final class ServiceErrorResponseException extends HttpResponseException { + /** + * Initializes a new instance of the ServiceErrorResponseException class. + * + * @param message the exception message or the response content if a message is not available. + * @param response the HTTP response. + */ + public ServiceErrorResponseException(String message, HttpResponse response) { + super(message, response); + } + + /** + * Initializes a new instance of the ServiceErrorResponseException class. + * + * @param message the exception message or the response content if a message is not available. + * @param response the HTTP response. + * @param value the deserialized response value. + */ + public ServiceErrorResponseException(String message, HttpResponse response, ServiceErrorResponse value) { + super(message, response, value); + } + + @Override + public ServiceErrorResponse getValue() { + return (ServiceErrorResponse) super.getValue(); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/package-info.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/package-info.java new file mode 100644 index 0000000000000..69bc98649c18c --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the data models for AzureSchemaRegistry. Azure Schema Registry is as a central schema repository + * for enterprise-level data infrastructure, complete with support for versioning and management. + */ +package com.azure.data.schemaregistry.implementation.models; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/package-info.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/package-info.java new file mode 100644 index 0000000000000..b5b3b659b0932 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the classes for AzureSchemaRegistry. Azure Schema Registry is as a central schema repository for + * enterprise-level data infrastructure, complete with support for versioning and management. + */ +package com.azure.data.schemaregistry.implementation; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaProperties.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaProperties.java new file mode 100644 index 0000000000000..9e9dbffcf86fe --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaProperties.java @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.models; + +import com.azure.data.schemaregistry.SchemaRegistryAsyncClient; +import com.azure.data.schemaregistry.SchemaRegistryClient; + +import java.util.Arrays; + +/** + * Stores all relevant information returned from {@link SchemaRegistryClient}/{@link SchemaRegistryAsyncClient} layer. + */ +public final class SchemaProperties { + + private final String schemaId; + private final SerializationType serializationType; + private final byte[] schemaBytes; + private final String schemaName; + + /** + * Initializes SchemaRegistryObject instance. + * + * @param schemaId the schema id + * @param serializationType type of schema, e.g. avro, json + * @param schemaName name of the schema. + * @param schemaByteArray byte payload representing schema, returned from Azure Schema Registry + */ + public SchemaProperties( + String schemaId, + SerializationType serializationType, + String schemaName, + byte[] schemaByteArray) { + this.schemaId = schemaId; + this.serializationType = serializationType; + this.schemaBytes = schemaByteArray.clone(); + this.schemaName = schemaName; + } + + /** + * Returns the unique identifier for this schema. + * + * @return the unique identifier for this schema. + */ + public String getSchemaId() { + return schemaId; + } + + /** + * The serialization type of this schema. + * @return schema type associated with the schema payload + */ + public SerializationType getSerializationType() { + return serializationType; + } + + + /** + * The name of the schema. + * @return the schema name. + */ + public String getSchemaName() { + return this.schemaName; + } + + /** + * Schema bytes returned from Schema Registry. + * + * @return The byte content of this schema. + */ + public byte[] getSchema() { + if (schemaBytes == null) { + return new byte[0]; + } + return Arrays.copyOf(this.schemaBytes, this.schemaBytes.length); + } + +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SerializationType.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SerializationType.java new file mode 100644 index 0000000000000..c3d3193208a56 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SerializationType.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.models; + +import com.azure.core.util.ExpandableStringEnum; + +/** + * The list of all serialization types. + */ +public class SerializationType extends ExpandableStringEnum { + public static final SerializationType AVRO = fromString("avro"); + + /** + * Returns the {@link SerializationType} associated with the name. + * @param name The name of the serialization type. + * @return The {@link SerializationType} associated with this name. + */ + public static SerializationType fromString(String name) { + return fromString(name, SerializationType.class); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/package-info.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/package-info.java new file mode 100644 index 0000000000000..3e1fe45c92d83 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the model classes for schema registry. + */ +package com.azure.data.schemaregistry.models; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/package-info.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/package-info.java index f04c2e22d1ed5..8b909b678f5c0 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/package-info.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/package-info.java @@ -1,4 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + /** - * Package containing core serialization and deserialization implementations for Azure Schema Registry SDK. + * Package containing clients for Azure Schema Registry service. */ package com.azure.data.schemaregistry; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/module-info.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/module-info.java index 1858b02d6f172..d14d3288f09e5 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/module-info.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/module-info.java @@ -5,7 +5,7 @@ requires transitive com.azure.core; exports com.azure.data.schemaregistry; - exports com.azure.data.schemaregistry.client; + exports com.azure.data.schemaregistry.models; opens com.azure.data.schemaregistry to com.fasterxml.jackson.databind, com.azure.core; } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/samples/README.md b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/README.md new file mode 100644 index 0000000000000..a6687a9f91728 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/README.md @@ -0,0 +1,47 @@ +--- +page_type: sample +languages: + - java +products: + - azure + - azure-data-schemaregistry +urlFragment: schemaregistry-samples +--- + +# Azure Schema Registry library samples for Java + +Azure Schema Registry samples are a set of self-contained Java programs that demonstrate using the client library to +register schemas with Azure Schema Registry service and read from it. Each sample focuses on a specific scenario and +can be executed independently. + +## Key concepts +Key concepts are explained in detail [here][sdk_readme_key_concepts]. + +## Getting started +Please refer to the [Getting Started][sdk_readme_getting_started] section. + +## Examples + +- [Serialize an object into avro schema bytes][sample_avro_serialization] +- [Deserialize avro serialized bytes into a strongly-typed object][sample_avro_deserialization] + +## Troubleshooting +See [Troubleshooting][sdk_readme_troubleshooting]. + +## Next steps +See [Next steps][sdk_readme_next_steps]. + +## Contributing +This project welcomes contributions and suggestions. See [Contributing][sdk_readme_contributing] for guidelines. + + +[sdk_readme_key_concepts]: ../../README.md#key-concepts +[sdk_readme_getting_started]: ../../README.md#getting-started +[sdk_readme_troubleshooting]: ../../README.md#troubleshooting +[sdk_readme_next_steps]: ../../README.md#next-steps +[sdk_readme_contributing]: ../../README.md#contributing +[sample_register_schema]: ./java/com/azure/data/schemaregistry/RegisterSchemaSample.java +[sample_get_schema]: ./java/com/azure/data/schemaregistry/GetSchemaSample.java +[sample_get_schema_id]: ./java/com/azure/data/schemaregistry/GetSchemaIdSample.java + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%schemaregistry%2Fazure-data-schemaregistry%2Fsrc%2Fsamples%2README.png) diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaIdSample.java b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaIdSample.java new file mode 100644 index 0000000000000..5186a261d5c4c --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaIdSample.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry; + +import com.azure.core.credential.TokenCredential; +import com.azure.data.schemaregistry.models.SerializationType; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.util.concurrent.CountDownLatch; + +/** + * Sample to demonstrate retrieving the schema id of a schema from Schema Registry. + */ +public class GetSchemaIdSample { + + /** + * The main method to run this program. + * @param args Ignored args. + */ + public static void main(String[] args) throws InterruptedException { + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + SchemaRegistryAsyncClient schemaRegistryAsyncClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildAsyncClient(); + + CountDownLatch countDownLatch = new CountDownLatch(1); + // Register a schema + schemaRegistryAsyncClient + .getSchemaId("{group-name}", "{schema-name}", "{schema-string}", SerializationType.AVRO) + .subscribe(schemaId -> { + System.out.println("Successfully retrieved the schema id: " + schemaId); + countDownLatch.countDown(); + }); + + // wait for the async task to complete + countDownLatch.await(); + + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaSample.java b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaSample.java new file mode 100644 index 0000000000000..1481c9f9b8164 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaSample.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry; + +import com.azure.core.credential.TokenCredential; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.util.concurrent.CountDownLatch; + +/** + * Sample to demonstrate retrieving a schema from Schema Registry. + */ +public class GetSchemaSample { + /** + * The main method to run this program. + * @param args Ignored args. + */ + public static void main(String[] args) throws InterruptedException { + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + SchemaRegistryAsyncClient schemaRegistryAsyncClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildAsyncClient(); + + CountDownLatch countDownLatch = new CountDownLatch(1); + // Register a schema + schemaRegistryAsyncClient + .getSchema("{schema-id}") + .subscribe(schemaProperties -> { + System.out.println("Successfully retrieved the schema " + schemaProperties.getSchemaName()); + countDownLatch.countDown(); + }); + + // wait for the async task to complete + countDownLatch.await(); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/ReadmeSamples.java b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/ReadmeSamples.java new file mode 100644 index 0000000000000..4297467826507 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/ReadmeSamples.java @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry; + +import com.azure.core.credential.TokenCredential; +import com.azure.data.schemaregistry.models.SchemaProperties; +import com.azure.data.schemaregistry.models.SerializationType; +import com.azure.identity.DefaultAzureCredentialBuilder; + +/** + * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS + * ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING + * LINE NUMBERS OF EXISTING CODE SAMPLES. + * + * Code samples for the README.md + */ +public class ReadmeSamples { + + /** + * Sample for creating async client. + */ + public void createAsyncClient() { + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + SchemaRegistryAsyncClient schemaRegistryAsyncClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildAsyncClient(); + } + + /** + * Sample for creating sync client. + */ + public void createSyncClient() { + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + SchemaRegistryClient schemaRegistryClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildClient(); + } + + /** + * Sample for registering a schema. + */ + public void registerSchema() { + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + SchemaRegistryClient schemaRegistryClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildClient(); + + String schemaContent = "{\n" + + " \"type\" : \"record\", \n" + + " \"namespace\" : \"SampleSchemaNameSpace\", \n" + + " \"name\" : \"Person\", \n" + + " \"fields\" : [\n" + + " { \n" + + " \"name\" : \"FirstName\" , \"type\" : \"string\" \n" + + " }, \n" + + " { \n" + + " \"name\" : \"LastName\", \"type\" : \"string\" \n" + + " }\n" + + " ]\n" + + "}"; + SchemaProperties schemaProperties = schemaRegistryClient.registerSchema("{schema-group}", "{schema-name}", + schemaContent, SerializationType.AVRO); + System.out.println("Registered schema: " + schemaProperties.getSchemaId()); + } + + /** + * Sample for getting the schema from a schema id. + */ + public void getSchema() { + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + SchemaRegistryClient schemaRegistryClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildClient(); + + SchemaProperties schemaProperties = schemaRegistryClient.getSchema("{schema-id}"); + System.out.println("Retrieved schema: " + schemaProperties.getSchemaName()); + } + + /** + * Sample for getting the schema id of a registered schema. + */ + public void getSchemaId() { + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + SchemaRegistryClient schemaRegistryClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildClient(); + + String schemaContent = "{\n" + + " \"type\" : \"record\", \n" + + " \"namespace\" : \"SampleSchemaNameSpace\", \n" + + " \"name\" : \"Person\", \n" + + " \"fields\" : [\n" + + " { \n" + + " \"name\" : \"FirstName\" , \"type\" : \"string\" \n" + + " }, \n" + + " { \n" + + " \"name\" : \"LastName\", \"type\" : \"string\" \n" + + " }\n" + + " ]\n" + + "}"; + String schemaId = schemaRegistryClient.getSchemaId("{schema-group}", "{schema-name}", + schemaContent, SerializationType.AVRO); + System.out.println("Retreived schema id: " + schemaId); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/RegisterSchemaSample.java b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/RegisterSchemaSample.java new file mode 100644 index 0000000000000..47fbd8316b80a --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/RegisterSchemaSample.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry; + +import com.azure.core.credential.TokenCredential; +import com.azure.data.schemaregistry.models.SerializationType; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.util.concurrent.CountDownLatch; + +/** + * Sample to demonstrate registering a schema with Schema Registry. + */ +public class RegisterSchemaSample { + /** + * The main method to run this program. + * @param args Ignored args. + */ + public static void main(String[] args) throws InterruptedException { + TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + + SchemaRegistryAsyncClient schemaRegistryAsyncClient = new SchemaRegistryClientBuilder() + .endpoint("{schema-registry-endpoint") + .credential(tokenCredential) + .buildAsyncClient(); + + CountDownLatch countDownLatch = new CountDownLatch(1); + // Register a schema + schemaRegistryAsyncClient + .registerSchema("{group-name}", "{schema-name}", "{schema-string}", SerializationType.AVRO) + .subscribe(schemaProperties -> { + System.out.println("Successfully registered a schema with id " + schemaProperties.getSchemaId()); + countDownLatch.countDown(); + }); + + // wait for the async task to complete + countDownLatch.await(); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/AbstractDataDeserializerTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/AbstractDataDeserializerTest.java deleted file mode 100644 index 310d3abe00399..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/AbstractDataDeserializerTest.java +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.data.schemaregistry.client.SchemaRegistryObject; -import com.azure.data.schemaregistry.client.SchemaRegistryClientException; -import org.apache.avro.Schema; -import org.apache.avro.generic.GenericData; -import org.apache.avro.generic.GenericDatumWriter; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.io.BinaryEncoder; -import org.apache.avro.io.EncoderFactory; -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; - -import static org.junit.jupiter.api.Assertions.*; - -public class AbstractDataDeserializerTest { - private static final String MOCK_GUID = new String(new char[AbstractDataSerDe.SCHEMA_ID_SIZE]).replace("\0", "a"); - private static final String MOCK_AVRO_SCHEMA_STRING = "{\"namespace\":\"example2.avro\",\"type\":\"record\",\"name\":\"User\",\"fields\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"favorite_number\",\"type\": [\"int\", \"null\"]}]}"; - - private final EncoderFactory encoderFactory = EncoderFactory.get(); - private static final Schema MOCK_AVRO_SCHEMA = (new Schema.Parser()).parse(MOCK_AVRO_SCHEMA_STRING); - - @Test - public void testLoadDecoder() throws IOException, SchemaRegistryClientException, SerializationException { - // add standard avro decoder class and test that it is used for decoding payload - SampleByteDecoder decoder = new SampleByteDecoder(); - - // manually add SchemaRegistryObject to cache - SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, - decoder.schemaType(), - MOCK_AVRO_SCHEMA_STRING.getBytes(), - decoder::parseSchemaString); - - assertTrue(registered.deserialize() != null); - - MockSchemaRegistryClient mockRegistryClient = new MockSchemaRegistryClient(); - mockRegistryClient.getGuidCache().put(MOCK_GUID, registered); - TestDummyDeserializer deserializer = new TestDummyDeserializer(mockRegistryClient); // contains byte decoder - - assertEquals(MOCK_GUID, deserializer.schemaRegistryClient.getSchemaByGuid(MOCK_GUID).getSchemaId()); - assertEquals(SampleByteDecoder.CONSTANT_PAYLOAD, deserializer.deserialize(getPayload())); - } - - @Test - public void testNullPayload() throws IOException, SchemaRegistryClientException, SerializationException { - TestDummyDeserializer deserializer = new TestDummyDeserializer(new MockSchemaRegistryClient()); - assertEquals(null, deserializer.deserialize(null)); - } - - @Test - public void testIfTooShortPayloadThrow() { - TestDummyDeserializer deserializer = new TestDummyDeserializer(new MockSchemaRegistryClient()); - - try { - deserializer.deserialize("bad payload".getBytes()); - fail("Too short payload did not throw SerializationException"); - } catch (SerializationException e) { - assertTrue(true); - } - } - - // TODO: add for non-existing guid - - @Test - public void testIfRegistryClientNullOnBuildThrow() { - try { - TestDummyDeserializer deserializer = new TestDummyDeserializer(null); - fail("should not get here."); - } catch (IllegalArgumentException e) { - // good - } - } - - private byte[] getPayload() throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(ByteBuffer.allocate(AbstractDataSerDe.SCHEMA_ID_SIZE) - .put(MOCK_GUID.getBytes(Charset.forName("UTF-8"))) - .array()); - GenericRecord record = getAvroRecord(); - BinaryEncoder encoder = encoderFactory.directBinaryEncoder(out, null); - GenericDatumWriter writer = new GenericDatumWriter<>(MOCK_AVRO_SCHEMA); - writer.write(record, encoder); - encoder.flush(); - byte[] bytes = out.toByteArray(); - return bytes; - } - - - private GenericRecord getAvroRecord() { - GenericRecord avroRecord = new GenericData.Record(MOCK_AVRO_SCHEMA); - avroRecord.put("name", "arthur"); - avroRecord.put("favorite_number", 23); - return avroRecord; - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/AbstractDataSerializerTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/AbstractDataSerializerTest.java deleted file mode 100644 index ec8494935b94a..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/AbstractDataSerializerTest.java +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.data.schemaregistry.client.SchemaRegistryObject; -import org.junit.jupiter.api.Test; - -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; -import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.*; - -public class AbstractDataSerializerTest { - private static final String MOCK_GUID = new String(new char[AbstractDataSerDe.SCHEMA_ID_SIZE]).replace("\0", "a"); - - @Test - public void testRegistryGuidPrefixedToPayload() { - // manually add SchemaRegistryObject into mock registry client cache - SampleByteEncoder encoder = new SampleByteEncoder(); - SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, - encoder.schemaType(), - encoder.getSchemaString(null).getBytes(), // always returns same schema string - encoder::parseSchemaString); - - assertEquals(encoder.getSchemaString(null), registered.deserialize()); - - MockSchemaRegistryClient mockRegistryClient = new MockSchemaRegistryClient(); - mockRegistryClient.getSchemaStringCache().put(encoder.getSchemaString(null), registered); - - TestDummySerializer serializer = new TestDummySerializer( - mockRegistryClient, true, false); - - try { - byte[] payload = serializer.serializeImpl(1); - ByteBuffer buffer = ByteBuffer.wrap(payload); - byte[] schemaGuidByteArray = new byte[AbstractDataSerDe.SCHEMA_ID_SIZE]; - try { - buffer.get(schemaGuidByteArray); - } catch (BufferUnderflowException e) { - throw new SerializationException("Payload too short, no readable guid.", e); - } - - // guid should match preloaded SchemaRegistryObject guid - assertEquals(MOCK_GUID, new String(schemaGuidByteArray)); - - int start = buffer.position() + buffer.arrayOffset(); - int length = buffer.limit() - AbstractDataSerDe.SCHEMA_ID_SIZE; - byte[] encodedBytes = Arrays.copyOfRange(buffer.array(), start, start + length); - assertTrue(Arrays.equals(encoder.encode(null).toByteArray(), encodedBytes)); - } catch (SerializationException e) { - e.printStackTrace(); - fail(); - } - } - - @Test - public void testNullPayloadThrowsSerializationException() { - TestDummySerializer serializer = new TestDummySerializer( - new MockSchemaRegistryClient(), - true, - false); - - try { - serializer.serializeImpl(null); - fail("Serializing null payload failed to throw SerializationException"); - } catch (SerializationException e) { - assertTrue(true); - } - } - - @Test - public void testSerializeWithNullByteEncoderThrows() { - // don't set byte encoder on constructor - TestDummySerializer serializer = new TestDummySerializer( - new MockSchemaRegistryClient(), false, false); - - try { - serializer.serializeImpl(1); - } catch (SerializationException e) { - assert (true); - } - } - - @Test - public void testIfRegistryNullThenThrow() { - try { - TestDummySerializer serializer = new TestDummySerializer( - null, true, false); - fail("Building serializer instance with null registry client failed to throw"); - } catch (IllegalArgumentException e) { - assertTrue(true); - } catch (Exception e) { - fail("Building serializer instance with null registry client should throw illegal argument exception"); - } - } - - @Test - public void testDefaultAutoRegister() { - TestDummySerializer serializer = new TestDummySerializer(new MockSchemaRegistryClient(), true); - assertEquals(false, (boolean) serializer.autoRegisterSchemas); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/MockSchemaRegistryClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/MockSchemaRegistryClient.java deleted file mode 100644 index 54fb22667bbad..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/MockSchemaRegistryClient.java +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.data.schemaregistry.client.SchemaRegistryClient; -import com.azure.data.schemaregistry.client.SchemaRegistryClientException; -import com.azure.data.schemaregistry.client.SchemaRegistryObject; - -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.function.Function; - -public class MockSchemaRegistryClient implements SchemaRegistryClient { - private final HashMap> typeParserDictionary; - private final HashMap guidCache; - private final HashMap schemaStringCache; - - public MockSchemaRegistryClient() { - this.guidCache = new HashMap(); - this.schemaStringCache = new HashMap(); - this.typeParserDictionary = new HashMap>(); - } - - @Override - public Charset getEncoding() { - return StandardCharsets.UTF_8; - } - - public void addSchemaParser(Codec codec) { } - - @Override - public SchemaRegistryObject register(String schemaGroup, String schemaName, String schemaString, String schemaType) - throws SchemaRegistryClientException { - if (schemaStringCache.containsKey(schemaString)) { - return schemaStringCache.get(schemaString); - } - - return null; - } - - @Override - public SchemaRegistryObject getSchemaByGuid(String schemaGuid) - throws SchemaRegistryClientException { - if (guidCache.containsKey(schemaGuid)) { - return guidCache.get(schemaGuid); - } - return null; - } - - @Override - public String getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) - throws SchemaRegistryClientException { - if (schemaStringCache.containsKey(schemaString)) { - return schemaStringCache.get(schemaString).getSchemaId(); - } - - return null; - } - - @Override - public String deleteSchemaVersion(String schemaGroup, String schemaName, int version) - throws SchemaRegistryClientException { - return null; - } - - @Override - public String deleteLatestSchemaVersion(String schemaGroup, String schemaName) - throws SchemaRegistryClientException { - return null; - } - - @Override - public List deleteSchema(String schemaGroup, String schemaName) - throws SchemaRegistryClientException { - return new ArrayList(); - } - - public HashMap> getTypeParserDictionary() { - return typeParserDictionary; - } - - public HashMap getGuidCache() { - return guidCache; - } - - public HashMap getSchemaStringCache() { - return schemaStringCache; - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleByteDecoder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleByteDecoder.java deleted file mode 100644 index 8b4cba7c82152..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleByteDecoder.java +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import org.apache.avro.Schema; - -public class SampleByteDecoder implements ByteDecoder { - public SampleByteDecoder() { } - - @Override - public String schemaType() { - return "sample"; - } - - public static final String CONSTANT_PAYLOAD = "sample payload!"; - - @Override - public Object decodeBytes(byte[] bytes, Object o) throws SerializationException { - return CONSTANT_PAYLOAD; - } - - @Override - public Schema parseSchemaString(String s) { - return new Schema.Parser().parse(s); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleByteEncoder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleByteEncoder.java deleted file mode 100644 index 768f7fbac496d..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleByteEncoder.java +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -public class SampleByteEncoder implements ByteEncoder { - - public SampleByteEncoder() { } - - @Override - public String getSchemaName(Object object) throws SerializationException { - return null; - } - - @Override - public String getSchemaString(Object object) { - return "string representation of schema"; - } - - @Override - public ByteArrayOutputStream encode(Object object) throws SerializationException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try { - outputStream.write("sample payload".getBytes()); - outputStream.flush(); - outputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - throw new SerializationException("this should never happen", e); - } - return outputStream; - } - - @Override - public String schemaType() { - return "test"; - } - - @Override - public String parseSchemaString(String s) { - return s; - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClientTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClientTest.java new file mode 100644 index 0000000000000..53c8cc292ca92 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClientTest.java @@ -0,0 +1,272 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry; + +import com.azure.data.schemaregistry.implementation.AzureSchemaRegistry; +import com.azure.data.schemaregistry.implementation.Schemas; +import com.azure.data.schemaregistry.implementation.models.SchemaId; +import com.azure.data.schemaregistry.implementation.models.SchemasGetByIdHeaders; +import com.azure.data.schemaregistry.implementation.models.SchemasGetByIdResponse; +import com.azure.data.schemaregistry.implementation.models.SchemasQueryIdByContentResponse; +import com.azure.data.schemaregistry.implementation.models.SchemasRegisterResponse; +import com.azure.data.schemaregistry.implementation.models.SerializationType; +import com.azure.data.schemaregistry.models.SchemaProperties; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Mono; + +import java.util.HashMap; +import java.util.concurrent.ConcurrentSkipListMap; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.validateMockitoUsage; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class SchemaRegistryAsyncClientTest { + + private static final com.azure.data.schemaregistry.models.SerializationType MOCK_SERIALIZATION = + com.azure.data.schemaregistry.models.SerializationType.fromString("mock_serialization_type"); + private static final String MOCK_ID = "mock_guid"; + private static final SchemaId MOCK_SCHEMA_ID = new SchemaId(); + private static final String MOCK_GROUP = "mockgroup"; + private static final String MOCK_SCHEMA_NAME = "mockname"; + private static final String MOCK_AVRO_SCHEMA = "{\"namespace\":\"example2.avro\",\"type\":\"record\",\"name\":\"User\",\"fields\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"favorite_number\",\"type\": [\"int\", \"null\"]}]}"; + + private SchemaRegistryAsyncClient client; + private AzureSchemaRegistry restService; + private HashMap guidCache; + private HashMap schemaStringCache; + private ConcurrentSkipListMap> typeParserDictionary; + private Schemas schemas; + + @BeforeEach + protected void setUp() { + this.guidCache = new HashMap(); + this.schemaStringCache = new HashMap(); + + this.typeParserDictionary = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); + this.typeParserDictionary.put(MOCK_SERIALIZATION.toString(), (s) -> s); + + this.restService = mock(AzureSchemaRegistry.class); + this.client = new SchemaRegistryAsyncClient( + this.restService, + this.guidCache, + this.schemaStringCache, + this.typeParserDictionary); + this.schemas = mock(Schemas.class); + } + + @AfterEach + protected void tearDown() { + validateMockitoUsage(); + } + + @Test + public void testRegisterThenSchemaCacheHit() throws Exception { + MOCK_SCHEMA_ID.setId(MOCK_ID); + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.registerWithResponseAsync(anyString(), anyString(), + any(com.azure.data.schemaregistry.implementation.models.SerializationType.class), + anyString())) + .thenReturn( + Mono.just( + new SchemasRegisterResponse( + null, + 200, + null, + MOCK_SCHEMA_ID, + null))); + + assertEquals( + MOCK_ID, + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION) + .block().getSchemaId()); + assertEquals( + MOCK_ID, + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION) + .block().getSchemaId()); + + verify(schemas, times(1)) + .registerWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, SerializationType.AVRO, MOCK_AVRO_SCHEMA); + } + + @Test + public void testGetGuidThenSchemaCacheHit() throws Exception { + MOCK_SCHEMA_ID.setId(MOCK_ID); + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.queryIdByContentWithResponseAsync(anyString(), anyString(), + any(SerializationType.class), anyString())) + .thenReturn( + Mono.just( + new SchemasQueryIdByContentResponse( + null, + 200, + null, + MOCK_SCHEMA_ID, + null))); + + assertEquals(MOCK_ID, + client.getSchemaId(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block()); + assertEquals(MOCK_ID, + client.getSchemaId(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block()); + + verify(schemas, times(1)) + .queryIdByContentWithResponseAsync(anyString(), anyString(), any(SerializationType.class), anyString()); + } + + @Test + public void testGetSchemaThenGuidCacheHit() throws Exception { + String mockId = "mock-id---"; + SchemasGetByIdHeaders mockHeaders = new SchemasGetByIdHeaders(); + mockHeaders.setXSchemaType(MOCK_SERIALIZATION.toString()); + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.getByIdWithResponseAsync(mockId)) + .thenReturn( + Mono.just(new SchemasGetByIdResponse( + null, + 200, + null, + MOCK_AVRO_SCHEMA, + mockHeaders))); + + SchemaProperties first = client.getSchema(mockId.toString()).block(); + SchemaProperties second = client.getSchema(mockId.toString()).block(); + + assertTrue(first.equals(second)); + assertEquals(mockId.toString(), first.getSchemaId()); + + verify(schemas, times(1)).getByIdWithResponseAsync(mockId); + } + + @Test + public void testClientReset() throws Exception { + MOCK_SCHEMA_ID.setId(MOCK_ID); + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.registerWithResponseAsync(anyString(), anyString(), any(SerializationType.class), + anyString())) + .thenReturn( + Mono.just( + new SchemasRegisterResponse( + null, + 200, + null, + MOCK_SCHEMA_ID, + null))); + + assertEquals( + MOCK_ID, + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION) + .block().getSchemaId()); + + client.clearCache(); + + assertEquals(0, guidCache.size()); + assertEquals(0, schemaStringCache.size()); + assertEquals(0, this.typeParserDictionary.size()); + + this.typeParserDictionary.put(MOCK_SERIALIZATION.toString(), (s) -> s); + + assertEquals( + MOCK_ID, + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION) + .block().getSchemaId()); + + verify(schemas, times(2)) + .registerWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, SerializationType.AVRO, MOCK_AVRO_SCHEMA); + } + + @Test + public void testBadRegisterRequestThenThrows() { + MOCK_SCHEMA_ID.setId(MOCK_ID); + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.registerWithResponseAsync(anyString(), anyString(), any(SerializationType.class), + anyString())) + .thenReturn( + Mono.just( + new SchemasRegisterResponse( + null, + 400, + null, + null, + null))); + try { + client.registerSchema( + "doesn't matter", + "doesn't matter", + "doesn't matter", + MOCK_SERIALIZATION).block(); + fail("Should throw on 400 status code"); + } catch (IllegalStateException e) { + assert true; + } + + verify(schemas, times(1)) + .registerWithResponseAsync(anyString(), anyString(), any(SerializationType.class), anyString()); + } + + @Test + public void testGetIdBySchemaContentNotFoundThenThrows() { + MOCK_SCHEMA_ID.setId(MOCK_ID); + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.queryIdByContentWithResponseAsync(anyString(), anyString(), + any(SerializationType.class), anyString())) + .thenReturn( + Mono.just( + new SchemasQueryIdByContentResponse( + null, + 404, + null, + null, + null))); + + try { + client.getSchemaId( + "doesn't matter", + "doesn't matter", + "doesn't matter", + MOCK_SERIALIZATION).block(); + fail("Should throw on 404 status code"); + } catch (IllegalStateException e) { + assert true; + } + + verify(schemas, times(1)) + .queryIdByContentWithResponseAsync(anyString(), anyString(), any(SerializationType.class), anyString()); + } + + @Test + public void testGetSchemaByIdNotFoundThenThrows() { + String mockId = "mock-id---"; + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.getByIdWithResponseAsync(mockId)) + .thenReturn( + Mono.just(new SchemasGetByIdResponse( + null, + 404, + null, + null, + null))); + + try { + client.getSchema(mockId).block(); + fail("Should have thrown on 404 status code"); + } catch (IllegalStateException e) { + assert true; + } catch (Exception e) { + assert false; + } + + verify(schemas, times(1)) + .getByIdWithResponseAsync(mockId); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummyDeserializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummyDeserializer.java deleted file mode 100644 index 591ffd95f172c..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummyDeserializer.java +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.data.schemaregistry.client.SchemaRegistryClient; - -public class TestDummyDeserializer extends AbstractDataDeserializer { - TestDummyDeserializer(SchemaRegistryClient mockClient) { - super(mockClient); - ByteDecoder sampleDecoder = new SampleByteDecoder(); - this.loadByteDecoder(sampleDecoder); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummySerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummySerializer.java deleted file mode 100644 index 9844b9caaaad0..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummySerializer.java +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.data.schemaregistry.client.SchemaRegistryClient; - -public class TestDummySerializer extends AbstractDataSerializer { - TestDummySerializer( - SchemaRegistryClient mockClient, - boolean byteEncoder, - boolean autoRegisterSchemas) { - super(mockClient); - - // allows simulating improperly written serializer constructor that does not initialize byte encoder - if (byteEncoder) { - setByteEncoder(new SampleByteEncoder()); - } - - this.autoRegisterSchemas = autoRegisterSchemas; - } - - TestDummySerializer( - SchemaRegistryClient mockClient, - boolean byteEncoder) { - super(mockClient); - - // allows simulating improperly written serializer constructor that does not initialize byte encoder - if (byteEncoder) { - setByteEncoder(new SampleByteEncoder()); - } - - // default auto register - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClientTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClientTest.java deleted file mode 100644 index 144d3c5d2b6df..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClientTest.java +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.client; - -import com.azure.data.schemaregistry.client.implementation.AzureSchemaRegistryRestService; -import com.azure.data.schemaregistry.client.implementation.models.*; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import reactor.core.publisher.Mono; - -import java.util.HashMap; -import java.util.concurrent.ConcurrentSkipListMap; -import java.util.function.Function; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -public class CachedSchemaRegistryClientTest { - private static final String MOCK_SERIALIZATION = "mock_serialization_type"; - private static final String MOCK_ID = "mock_guid"; - private static final SchemaId MOCK_SCHEMA_ID = new SchemaId(); - private static final String MOCK_GROUP = "mockgroup"; - private static final String MOCK_SCHEMA_NAME = "mockname"; - private static final String MOCK_AVRO_SCHEMA = "{\"namespace\":\"example2.avro\",\"type\":\"record\",\"name\":\"User\",\"fields\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"favorite_number\",\"type\": [\"int\", \"null\"]}]}"; - - private CachedSchemaRegistryClient client; - private AzureSchemaRegistryRestService restService; - private HashMap guidCache; - private HashMap schemaStringCache; - private ConcurrentSkipListMap> typeParserDictionary; - - @BeforeEach - protected void setUp() { - this.guidCache = new HashMap(); - this.schemaStringCache = new HashMap(); - - this.typeParserDictionary = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); - this.typeParserDictionary.put(MOCK_SERIALIZATION, (s) -> s); - - this.restService = mock(AzureSchemaRegistryRestService.class); - this.client = new CachedSchemaRegistryClient( - this.restService, - this.guidCache, - this.schemaStringCache, - this.typeParserDictionary); - } - - @AfterEach - protected void tearDown() { - validateMockitoUsage(); - } - - @Test - public void testRegisterThenSchemaCacheHit() throws Exception { - MOCK_SCHEMA_ID.setId(MOCK_ID); - when(restService.createSchemaWithResponseAsync(anyString(), anyString(), anyString(), anyString())) - .thenReturn( - Mono.just( - new CreateSchemaResponse( - null, - 200, - null, - MOCK_SCHEMA_ID, - null))); - - assertEquals( - MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).getSchemaId()); - assertEquals( - MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).getSchemaId()); - - verify(restService, times(1)) - .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION, MOCK_AVRO_SCHEMA); - } - - @Test - public void testGetGuidThenSchemaCacheHit() throws Exception { - MOCK_SCHEMA_ID.setId(MOCK_ID); - when(restService.getIdBySchemaContentWithResponseAsync(anyString(), anyString(), anyString(), anyString())) - .thenReturn( - Mono.just( - new GetIdBySchemaContentResponse( - null, - 200, - null, - MOCK_SCHEMA_ID, - null))); - - assertEquals(MOCK_ID, client.getSchemaId(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION)); - assertEquals(MOCK_ID, client.getSchemaId(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION)); - - verify(restService, times(1)) - .getIdBySchemaContentWithResponseAsync(anyString(), anyString(), anyString(), anyString()); - } - - @Test - public void testGetSchemaThenGuidCacheHit() throws Exception { - String mockId = "mock-id---"; - GetSchemaByIdHeaders mockHeaders = new GetSchemaByIdHeaders(); - mockHeaders.setXSchemaType(MOCK_SERIALIZATION); - when(restService.getSchemaByIdWithResponseAsync(mockId)) - .thenReturn( - Mono.just(new GetSchemaByIdResponse( - null, - 200, - null, - MOCK_AVRO_SCHEMA, - mockHeaders))); - - SchemaRegistryObject first = client.getSchemaByGuid(mockId.toString()); - SchemaRegistryObject second = client.getSchemaByGuid(mockId.toString()); - - assertTrue(first.equals(second)); - assertEquals(mockId.toString(), first.getSchemaId()); - - verify(restService, times(1)).getSchemaByIdWithResponseAsync(mockId); - } - - @Test - public void testClientReset() throws Exception { - MOCK_SCHEMA_ID.setId(MOCK_ID); - when(restService.createSchemaWithResponseAsync(anyString(), anyString(), anyString(), anyString())) - .thenReturn( - Mono.just( - new CreateSchemaResponse( - null, - 200, - null, - MOCK_SCHEMA_ID, - null))); - - assertEquals( - MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).getSchemaId()); - - client.reset(); - - assertEquals(0, guidCache.size()); - assertEquals(0, schemaStringCache.size()); - assertEquals(0, this.typeParserDictionary.size()); - - this.typeParserDictionary.put(MOCK_SERIALIZATION, (s) -> s); - - assertEquals( - MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).getSchemaId()); - - verify(restService, times(2)) - .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION, MOCK_AVRO_SCHEMA); - } - - @Test - public void testBadRegisterRequestThenThrows() { - MOCK_SCHEMA_ID.setId(MOCK_ID); - when(restService.createSchemaWithResponseAsync(anyString(), anyString(), anyString(), anyString())) - .thenReturn( - Mono.just( - new CreateSchemaResponse( - null, - 400, - null, - null, - null))); - try { - client.register( - "doesn't matter", - "doesn't matter", - "doesn't matter", - "doesn't matter"); - fail("Should throw on 400 status code"); - } catch (SchemaRegistryClientException e) { - assert true; - } - - verify(restService, times(1)) - .createSchemaWithResponseAsync(anyString(), anyString(), anyString(), anyString()); - } - - @Test - public void testGetIdBySchemaContentNotFoundThenThrows() { - MOCK_SCHEMA_ID.setId(MOCK_ID); - when(restService.getIdBySchemaContentWithResponseAsync(anyString(), anyString(), anyString(), anyString())) - .thenReturn( - Mono.just( - new GetIdBySchemaContentResponse( - null, - 404, - null, - null, - null))); - - try { - client.getSchemaId( - "doesn't matter", - "doesn't matter", - "doesn't matter", - "doesn't matter"); - fail("Should throw on 404 status code"); - } catch (SchemaRegistryClientException e) { - assert true; - } - - verify(restService, times(1)) - .getIdBySchemaContentWithResponseAsync(anyString(), anyString(), anyString(), anyString()); - } - - @Test - public void testGetSchemaByIdNotFoundThenThrows() { - String mockId = "mock-id---"; - when(restService.getSchemaByIdWithResponseAsync(mockId)) - .thenReturn( - Mono.just(new GetSchemaByIdResponse( - null, - 404, - null, - null, - null))); - - try { - client.getSchemaByGuid(mockId); - fail("Should have thrown on 404 status code"); - } catch (SchemaRegistryClientException e) { - assert true; - } - - verify(restService, times(1)) - .getSchemaByIdWithResponseAsync(mockId); - } -}