From a69684acceebefba0e819074b3226b970ca12b26 Mon Sep 17 00:00:00 2001 From: Arthur Erlendsson <30675661+arerlend@users.noreply.github.com> Date: Thu, 30 Jul 2020 14:23:04 -0700 Subject: [PATCH 01/17] [WIP] Schema Registry serializers implement ObjectSerializer experimental interface (#13152) * ObjectSerializer refactor - init, does not build * stash fix * condense serde into ser * empty or 0 length payload * add sync SR client * AbstractDataSerializer -> AbstractSchemaRegistrySerializer --- .../azure-data-schemaregistry-avro/pom.xml | 5 + .../schemaregistry/avro/AvroByteDecoder.java | 86 ------ .../schemaregistry/avro/AvroByteEncoder.java | 82 ----- .../data/schemaregistry/avro/AvroCodec.java | 137 ++++++++- .../SchemaRegistryAvroAsyncDeserializer.java | 43 --- .../SchemaRegistryAvroAsyncSerializer.java | 64 ++-- .../avro/SchemaRegistryAvroDeserializer.java | 39 --- ...SchemaRegistryAvroDeserializerBuilder.java | 112 ------- .../avro/SchemaRegistryAvroSerializer.java | 45 ++- .../SchemaRegistryAvroSerializerBuilder.java | 45 ++- .../avro/AvroByteDecoderTest.java | 15 - .../avro/AvroByteEncoderTest.java | 22 -- .../AbstractDataDeserializer.java | 126 -------- .../schemaregistry/AbstractDataSerDe.java | 39 --- .../AbstractDataSerializer.java | 130 -------- .../AbstractSchemaRegistrySerializer.java | 285 ++++++++++++++++++ .../data/schemaregistry/ByteDecoder.java | 18 -- .../data/schemaregistry/ByteEncoder.java | 40 --- .../com/azure/data/schemaregistry/Codec.java | 42 ++- .../SerializationException.java | 6 +- .../CachedSchemaRegistryAsyncClient.java | 251 +++++++++++++++ .../client/CachedSchemaRegistryClient.java | 282 +---------------- .../CachedSchemaRegistryClientBuilder.java | 48 +-- .../client/SchemaRegistryClient.java | 100 ------ .../client/SchemaRegistryClientException.java | 2 +- .../client/SchemaRegistryObject.java | 4 +- .../schemaregistry/client/package-info.java | 2 +- .../AbstractDataDeserializerTest.java | 102 ------- .../AbstractDataSerializerTest.java | 136 ++++++++- .../MockSchemaRegistryClient.java | 93 ------ .../schemaregistry/SampleByteDecoder.java | 27 -- ...ampleByteEncoder.java => SampleCodec.java} | 15 +- .../schemaregistry/TestDummyDeserializer.java | 14 - .../schemaregistry/TestDummySerializer.java | 23 +- ... CachedSchemaRegistryAsyncClientTest.java} | 32 +- 35 files changed, 1017 insertions(+), 1495 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/SchemaRegistryAvroAsyncDeserializer.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 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 create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractSchemaRegistrySerializer.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 create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClient.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/test/java/com/azure/data/schemaregistry/AbstractDataDeserializerTest.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 rename sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/{SampleByteEncoder.java => SampleCodec.java} (75%) delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummyDeserializer.java rename sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/{CachedSchemaRegistryClientTest.java => CachedSchemaRegistryAsyncClientTest.java} (88%) diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml index ff9d8f470bf97..e9fcfd9db703c 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml @@ -48,6 +48,11 @@ azure-data-schemaregistry 1.0.0-beta.3 + + com.azure + azure-core-experimental + 1.0.0-beta.1 + org.apache.avro avro 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 index bbf70f18342c4..4b25995594527 100644 --- 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 @@ -3,15 +3,40 @@ package com.azure.data.schemaregistry.avro; +import com.azure.core.util.logging.ClientLogger; import com.azure.data.schemaregistry.Codec; +import com.azure.data.schemaregistry.SerializationException; import org.apache.avro.Schema; +import org.apache.avro.generic.GenericDatumReader; +import org.apache.avro.generic.GenericDatumWriter; +import org.apache.avro.io.*; +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.util.Objects; /** * Base Codec class for Avro encoder and decoder implementations */ -abstract class AvroCodec implements Codec { +public class AvroCodec implements Codec { + private final ClientLogger logger = new ClientLogger(AvroCodec.class); + private static final EncoderFactory ENCODER_FACTORY = EncoderFactory.get(); + private static final DecoderFactory DECODER_FACTORY = DecoderFactory.get(); + private final boolean avroSpecificReader; + + /** + * Instantiates AvroCodec instance + * @param avroSpecificReader flag indicating if decoder should decode records as SpecificRecords + */ + public AvroCodec(boolean avroSpecificReader) { + this.avroSpecificReader = avroSpecificReader; + } + @Override - public String schemaType() { + public String getSchemaType() { return "avro"; } @@ -23,4 +48,112 @@ public String schemaType() { public 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 + */ + @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)); + } + } + + + /** + * @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/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 index 7d8edfb020bac..6e2cf03202c85 100644 --- 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 @@ -3,46 +3,58 @@ package com.azure.data.schemaregistry.avro; -import com.azure.data.schemaregistry.AbstractDataSerializer; +import com.azure.core.experimental.serializer.ObjectSerializer; +import com.azure.core.util.logging.ClientLogger; +import com.azure.data.schemaregistry.AbstractSchemaRegistrySerializer; import com.azure.data.schemaregistry.SerializationException; +import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; import reactor.core.publisher.Mono; -import reactor.core.scheduler.Scheduler; -import reactor.core.scheduler.Schedulers; - -import java.util.concurrent.Executors; +import java.io.InputStream; +import java.io.OutputStream; /** * 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; +public class SchemaRegistryAvroAsyncSerializer extends AbstractSchemaRegistrySerializer implements ObjectSerializer { + private final ClientLogger logger = new ClientLogger(SchemaRegistryAvroAsyncSerializer.class); /** - * @param serializer synchronous Avro serializer implementation + * + * @param registryClient + * @param codec + * @param schemaGroup + * @param autoRegisterSchemas */ - SchemaRegistryAvroAsyncSerializer(SchemaRegistryAvroSerializer serializer) { - this.serializer = serializer; - this.scheduler = Schedulers.fromExecutor(Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE)); + SchemaRegistryAvroAsyncSerializer(CachedSchemaRegistryAsyncClient registryClient, AvroCodec codec, + String schemaGroup, boolean autoRegisterSchemas) { + super(registryClient); + + setSerializerCodec(codec); + addDeserializerCodec(codec); + + // send configurations only + this.autoRegisterSchemas = autoRegisterSchemas; + this.schemaGroup = schemaGroup; } - /** - * 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) { + @Override + public Mono serialize(S s, Object o) { + if (o == null) { return Mono.empty(); } - return Mono - .fromCallable(() -> this.serializer.serialize(object)) - .subscribeOn(scheduler); + return this.serializeImpl(s, o); + } + + @Override + public Mono deserialize(InputStream stream, Class clazz) { + return this.deserializeImpl(stream) + .map(o -> { + if (clazz.isInstance(o)) { + return clazz.cast(o); + } + throw logger.logExceptionAsError(new SerializationException("Deserialized object not of class %s")); + }); } } 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..942b36eb9fa32 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,9 +3,11 @@ package com.azure.data.schemaregistry.avro; -import com.azure.data.schemaregistry.AbstractDataSerializer; +import com.azure.data.schemaregistry.AbstractSchemaRegistrySerializer; import com.azure.data.schemaregistry.SerializationException; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryClient; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; /** * A serializer implementation capable of serializing objects and automatedly storing serialization schemas @@ -15,31 +17,44 @@ * * Pluggable with the core Azure SDK Serializer interface. * - * @see AbstractDataSerializer See AbstractDataSerializer for internal serialization implementation + * @see AbstractSchemaRegistrySerializer See AbstractSchemaRegistrySerializer for internal serialization implementation */ -public class SchemaRegistryAvroSerializer extends AbstractDataSerializer { - SchemaRegistryAvroSerializer(CachedSchemaRegistryClient registryClient, - String schemaGroup, - boolean autoRegisterSchemas) { - super(registryClient); - - setByteEncoder(new AvroByteEncoder()); - - this.autoRegisterSchemas = autoRegisterSchemas; - this.schemaGroup = schemaGroup; +public class SchemaRegistryAvroSerializer { + private final SchemaRegistryAvroAsyncSerializer serializer; + SchemaRegistryAvroSerializer(SchemaRegistryAvroAsyncSerializer serializer) { + this.serializer = serializer; } /** * 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 + * @return byte array containing unique ID reference to schema, then the object serialized into bytes * @throws SerializationException Throws on serialization failure. */ public byte[] serialize(Object object) throws SerializationException { if (object == null) { return null; } - return serializeImpl(object); + + ByteArrayOutputStream s = serializer.serialize(new ByteArrayOutputStream(), object).block(); + if (s != null){ + s.toByteArray(); + } + + throw new SerializationException("Serialization failed, null output stream returned."); + } + + /** + * 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 serializer.deserialize(new ByteArrayInputStream(data), Object.class); } } 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..83136b90893bb 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 @@ -4,8 +4,8 @@ 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.AbstractSchemaRegistrySerializer; +import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; import com.azure.data.schemaregistry.client.CachedSchemaRegistryClientBuilder; import java.util.Objects; @@ -19,6 +19,7 @@ public final class SchemaRegistryAvroSerializerBuilder { private boolean autoRegisterSchemas; private String schemaGroup; private Integer maxSchemaMapSize; + private boolean avroSpecificReader; /** * Instantiates instance of Builder class. @@ -27,9 +28,10 @@ public final class SchemaRegistryAvroSerializerBuilder { public SchemaRegistryAvroSerializerBuilder() { this.registryUrl = null; this.credential = null; - this.autoRegisterSchemas = AbstractDataSerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; - this.schemaGroup = AbstractDataSerializer.SCHEMA_GROUP_DEFAULT; + this.autoRegisterSchemas = AbstractSchemaRegistrySerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; + this.schemaGroup = AbstractSchemaRegistrySerializer.SCHEMA_GROUP_DEFAULT; this.maxSchemaMapSize = null; + this.avroSpecificReader = false; } /** @@ -87,7 +89,17 @@ public SchemaRegistryAvroSerializerBuilder autoRegisterSchema(boolean autoRegist } /** - * Specifies maximum schema object cache size for underlying CachedSchemaRegistryClient. If specified 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 avroSpecificReader(boolean avroSpecificReader) { + this.avroSpecificReader = avroSpecificReader; + return this; + } + + /** + * Specifies maximum schema object cache size for underlying CachedSchemaRegistryAsyncClient. If specified cache * size is exceeded, all caches are recycled. * * @param maxSchemaMapSize maximum number of schemas per cache @@ -99,24 +111,24 @@ public SchemaRegistryAvroSerializerBuilder maxSchemaMapSize(int maxSchemaMapSize } /** - * Instantiates SchemaRegistry - * @return {@link SchemaRegistryAvroAsyncSerializer} instance + * Instantiates {@link SchemaRegistryAvroSerializer} + * @return {@link SchemaRegistryAvroSerializer} instance * * @throws NullPointerException if parameters are incorrectly set. * @throws IllegalArgumentException if credential is not set. */ - public SchemaRegistryAvroAsyncSerializer buildAsyncClient() { - return new SchemaRegistryAvroAsyncSerializer(this.buildSyncClient()); + public SchemaRegistryAvroSerializer buildClient() { + return new SchemaRegistryAvroSerializer(this.buildAsyncClient()); } /** - * Instantiates {@link SchemaRegistryAvroSerializer} - * @return {@link SchemaRegistryAvroSerializer} instance + * Instantiates SchemaRegistry + * @return {@link SchemaRegistryAvroAsyncSerializer} instance * * @throws NullPointerException if parameters are incorrectly set. * @throws IllegalArgumentException if credential is not set. */ - public SchemaRegistryAvroSerializer buildSyncClient() { + public SchemaRegistryAvroAsyncSerializer buildAsyncClient() { CachedSchemaRegistryClientBuilder builder = new CachedSchemaRegistryClientBuilder() .endpoint(registryUrl) .credential(credential); @@ -125,8 +137,13 @@ public SchemaRegistryAvroSerializer buildSyncClient() { builder.maxSchemaMapSize(maxSchemaMapSize); } - CachedSchemaRegistryClient client = builder.buildClient(); + AvroCodec codec = new AvroCodec(this.avroSpecificReader); + + CachedSchemaRegistryAsyncClient client = builder + .addSchemaParser(codec) + .buildAsyncClient(); - return new SchemaRegistryAvroSerializer(client, this.schemaGroup, this.autoRegisterSchemas); + return new SchemaRegistryAvroAsyncSerializer(client, codec, this.schemaGroup, + this.autoRegisterSchemas); } } 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/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/AbstractSchemaRegistrySerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractSchemaRegistrySerializer.java new file mode 100644 index 0000000000000..dcf9abf2d9306 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractSchemaRegistrySerializer.java @@ -0,0 +1,285 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.util.logging.ClientLogger; +import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; +import com.azure.data.schemaregistry.client.SchemaRegistryClientException; +import com.azure.data.schemaregistry.client.SchemaRegistryObject; +import reactor.core.publisher.Mono; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.BufferUnderflowException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; +import java.util.concurrent.ConcurrentSkipListMap; + +import static com.azure.core.util.FluxUtil.monoError; + +/** + * Common implementation for all registry-based serializers. + */ +public abstract class AbstractSchemaRegistrySerializer { + private final ClientLogger logger = new ClientLogger(AbstractSchemaRegistrySerializer.class); + + public static final Boolean AUTO_REGISTER_SCHEMAS_DEFAULT = false; + public static final String SCHEMA_GROUP_DEFAULT = "$default"; + public static final int SCHEMA_ID_SIZE = 32; + + protected CachedSchemaRegistryAsyncClient schemaRegistryClient; + + protected Codec serializerCodec = null; + private final Map deserializerCodecMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); + protected String schemaType; + protected Boolean autoRegisterSchemas = AbstractSchemaRegistrySerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; + protected String schemaGroup = AbstractSchemaRegistrySerializer.SCHEMA_GROUP_DEFAULT; + + /** + * @param schemaRegistryClient registry client to be used for storing schemas. Not null. + */ + public AbstractSchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, + Codec serializerCodec, Map deserializerCodecMap) { + if (schemaRegistryClient == null) { + throw logger.logExceptionAsError( + new IllegalArgumentException("Schema registry client must be initialized and passed into builder.")); + } + this.schemaRegistryClient = schemaRegistryClient; + this.serializerCodec = serializerCodec; + this.deserializerCodecMap.putAll(deserializerCodecMap); + } + + /** + * Set Codec class to be used for serialized objects into bytes + * + * @param codec Codec instance + */ + protected void setSerializerCodec(Codec codec) { + if (this.serializerCodec != null) { + throw logger.logExceptionAsError( + new IllegalArgumentException("Setting multiple encoders on serializer not permitted")); + } + this.serializerCodec = codec; + this.schemaType = codec.getSchemaType(); + } + + /** + * 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 s Output stream destination for encoded bytes + * @param object object to be serialized + * @param Type of the output stream parameter. + * @return byte array containing encoded bytes with prefixed schema ID + * @throws SerializationException if serialization operation fails during runtime. + */ + protected Mono serializeImpl(T s, Object object) { + if (object == null) { + return monoError(logger, new SerializationException( + "Null object, behavior should be defined in concrete serializer implementation.")); + } + + if (serializerCodec == null) { + return monoError(logger, new SerializationException( + "Byte encoder null, serializer must be initialized with a byte encoder.")); + } + + if (schemaType == null) { + schemaType = serializerCodec.getSchemaType(); + } + + String schemaString = serializerCodec.getSchemaString(object); + String schemaName = serializerCodec.getSchemaName(object); + + return this.maybeRegisterSchema(this.schemaGroup, schemaName, schemaString, this.schemaType) + .onErrorMap(e -> { + if (e instanceof SchemaRegistryClientException) { + StringBuilder builder = new StringBuilder(); + if (this.autoRegisterSchemas) { + builder.append(String.format("Error registering Avro schema. Group: %s, name: %s. ", + schemaGroup, schemaName)); + } else { + builder.append(String.format("Error retrieving Avro schema. Group: %s, name: %s. ", + schemaGroup, schemaName)); + } + + if (e.getCause() instanceof HttpResponseException) { + HttpResponseException httpException = (HttpResponseException) e.getCause(); + builder.append("HTTP ") + .append(httpException.getResponse().getStatusCode()) + .append(" ") + .append(httpException.getResponse().getBodyAsString()); + } else { + builder.append(e.getCause().getMessage()); + } + + return logger.logExceptionAsError(new SerializationException(builder.toString(), e)); + } else { + return logger.logExceptionAsError(new SerializationException(e.getMessage(), e)); + } + }) + .handle((id, sink) -> { + ByteBuffer idBuffer = ByteBuffer.allocate(AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE) + .put(id.getBytes(StandardCharsets.UTF_8)); + try { + s.write(idBuffer.array()); + serializerCodec.encode(object).writeTo(s); + } catch (IOException e) { + sink.error(new SerializationException(e.getMessage(), e)); + } + sink.next(s); + }); + } + + + /** + * Core implementation for registry-based deserialization. + * Fetches schema referenced by prefixed ID and deserializes the subsequent payload into Java object. + * + * @param s InputStream containing bytes encoded by an Azure Schema Registry producer + * @return object, deserialized with the prefixed schema + * @throws SerializationException if deserialization of registry schema or message payload fails. + */ + protected Mono deserializeImpl(InputStream s) throws SerializationException { + if (s == null) { + return Mono.empty(); + } + + return Mono.fromCallable(() -> { + byte[] payload = new byte[s.available()]; + while (s.read(payload) != -1) {} + return payload; + }) + .flatMap(payload -> { + if (payload == null || payload.length == 0) { + return Mono.empty(); + } + + ByteBuffer buffer = ByteBuffer.wrap(payload); + String schemaId = getSchemaIdFromPayload(buffer); + System.out.println(schemaId); + + SchemaRegistryObject block = this.schemaRegistryClient.getSchemaById(schemaId).block(); + System.out.println(block); + return this.schemaRegistryClient.getSchemaById(schemaId) + .onErrorMap(IOException.class, + e -> logger.logExceptionAsError(new SerializationException(e.getMessage(), e))) + .handle((registryObject, sink) -> { + Object payloadSchema = registryObject.deserialize(); + + if (payloadSchema == null) { + sink.error(logger.logExceptionAsError( + new SerializationException( + String.format("Payload schema returned as null. Schema type: %s, Schema ID: %s", + registryObject.getSchemaType(), registryObject.getSchemaId())))); + return; + } + + int start = buffer.position() + buffer.arrayOffset(); + int length = buffer.limit() - AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE; + byte[] b = Arrays.copyOfRange(buffer.array(), start, start + length); + + Codec codec = getDeserializerCodec(registryObject); + sink.next(codec.decodeBytes(b, payloadSchema)); + }) + .onErrorMap(e -> { + if (e instanceof SchemaRegistryClientException) { + StringBuilder builder = new StringBuilder( + String.format("Failed to retrieve schema for id %s", schemaId)); + + if (e.getCause() instanceof HttpResponseException) { + HttpResponseException httpException = (HttpResponseException) e.getCause(); + builder.append("HTTP ") + .append(httpException.getResponse().getStatusCode()) + .append(" ") + .append(httpException.getResponse().getBodyAsString()); + } else { + builder.append(e.getCause().getMessage()); + } + + return logger.logExceptionAsError(new SerializationException(builder.toString(), e)); + } else { + return logger.logExceptionAsError(new SerializationException(e.getMessage(), e)); + } + }); + }); + } + + + /** + * Fetches the correct Codec based on schema type of the message. + * + * @param registryObject object returned from CachedSchemaRegistryAsyncClient, contains schema type + * @return Codec to be used to deserialize encoded payload bytes + * @throws SerializationException if decoder for the required schema type has not been loaded + */ + private Codec getDeserializerCodec(SchemaRegistryObject registryObject) throws SerializationException { + Codec codec = deserializerCodecMap.get(registryObject.getSchemaType()); + if (codec == null) { + throw logger.logExceptionAsError( + new SerializationException( + String.format("No deserializer codec class found for schema type '%s'.", + registryObject.getSchemaType()) + )); + } + return codec; + } + + /** + * @param buffer full payload bytes + * @return String representation of schema ID + * @throws SerializationException if schema ID could not be extracted from payload + */ + private String getSchemaIdFromPayload(ByteBuffer buffer) throws SerializationException { + byte[] schemaGuidByteArray = new byte[AbstractSchemaRegistrySerializer.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 Codec to be used for decoding message payloads of specified schema type. + * + * @param codec Codec class instance to be loaded + */ + protected void addDeserializerCodec(Codec codec) { + if (codec == null) { + throw logger.logExceptionAsError(new IllegalArgumentException("'codec' cannot be null")); + } + + this.deserializerCodecMap.put(codec.getSchemaType(), codec); + } + + /** + * 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 + * @param schemaType type of schema being stored, e.g. avro + * @return string representation of schema ID + * @throws SchemaRegistryClientException upon registry client operation failure + */ + private Mono maybeRegisterSchema( + String schemaGroup, String schemaName, String schemaString, String schemaType) { + if (this.autoRegisterSchemas) { + return this.schemaRegistryClient.register(schemaGroup, schemaName, schemaString, schemaType) + .map(SchemaRegistryObject::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 index cf99962f9ff6f..ca4ff37afedf1 100644 --- 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 @@ -3,8 +3,10 @@ package com.azure.data.schemaregistry; +import java.io.ByteArrayOutputStream; + /** - * Base interface for all ByteEncoder and ByteDecoder interfaces + * An interface defining operations required for registry-based serialization and deserialization. */ public interface Codec { /** @@ -13,7 +15,7 @@ public interface Codec { * Utilized by schema registry store and client as non-case-sensitive tags for * schemas of a specific type. */ - String schemaType(); + String getSchemaType(); /** * Parses string representation of schema into schema Object @@ -21,4 +23,40 @@ public interface Codec { * @return schema object to be used for decoding payloads */ Object parseSchemaString(String schemaString); + + /** + * 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); + + /** + * 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); + + /** + * 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); + + /** + * 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); } 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 index a4f6b5f6065e3..b526a8843721b 100644 --- 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 @@ -10,15 +10,15 @@ */ public class SerializationException extends AzureException { /** - * @param s error message explaining serde operation failure + * @param s error message explaining serialization/deserialization operation failure */ public SerializationException(String s) { super(s); } /** - * @param s error message explaining serde operation failure - * @param cause Throwable cause of serialization failure + * @param s error message explaining serialization/deserialization operation failure + * @param cause Throwable failure cause */ 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/CachedSchemaRegistryAsyncClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClient.java new file mode 100644 index 0000000000000..a244f03a896c3 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClient.java @@ -0,0 +1,251 @@ +// 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.logging.ClientLogger; +import com.azure.data.schemaregistry.client.implementation.AzureSchemaRegistryRestService; +import com.azure.data.schemaregistry.client.implementation.models.SchemaId; +import reactor.core.publisher.Mono; + +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; + +/** + * 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 CachedSchemaRegistryClientBuilder Follows builder pattern for object instantiation + */ +@ServiceClient( + builder = CachedSchemaRegistryClientBuilder.class, + serviceInterfaces = AzureSchemaRegistryRestService.class) +public final class CachedSchemaRegistryAsyncClient { + private final ClientLogger logger = new ClientLogger(CachedSchemaRegistryAsyncClient.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 final AzureSchemaRegistryRestService restService; + private final Integer maxSchemaMapSize; + private final ConcurrentSkipListMap> typeParserMap; + private final Map idCache; + private final Map schemaStringCache; + + CachedSchemaRegistryAsyncClient( + 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 + CachedSchemaRegistryAsyncClient( + 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 + */ + public Charset getEncoding() { + return CachedSchemaRegistryAsyncClient.SCHEMA_REGISTRY_SERVICE_ENCODING; + } + + public Mono register( + String schemaGroup, String schemaName, String schemaString, String schemaType) { + if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { + logger.verbose( + "Cache hit schema string. Group: '{}', name: '{}', schema type: '{}', payload: '{}'", + schemaGroup, schemaName, schemaType, schemaString); + return Mono.fromCallable( + () -> schemaStringCache.get(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))); + } + + logger.verbose( + "Registering schema. Group: '{}', name: '{}', serialization type: '{}', payload: '{}'", + schemaGroup, schemaName, schemaType, schemaString); + + return this.restService.createSchemaWithResponseAsync(schemaGroup, schemaName, schemaType, schemaString) + .onErrorMap(HttpResponseException.class, e -> logger.logExceptionAsError( + new SchemaRegistryClientException("Register operation failed, unexpected service response.", e))) + .handle((response, sink) -> { + if (response == null) { + sink.error(logger.logExceptionAsError( + new SchemaRegistryClientException("Client returned null response"))); + return; + } + + if (response.getStatusCode() == 400) { + sink.error(logger.logExceptionAsError( + new SchemaRegistryClientException("Invalid schema registration attempted"))); + return; + } + + SchemaId schemaId = response.getValue(); + + SchemaRegistryObject registered = new SchemaRegistryObject(schemaId.getId(), + schemaType, + schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), + getParseFunc(schemaType)); + + resetIfNeeded(); + schemaStringCache.putIfAbsent(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString), registered); + logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); + sink.next(registered); + }); + } + + public Mono getSchemaById(String schemaId) { + Objects.requireNonNull(schemaId, "'schemaId' should not be null"); + + if (idCache.containsKey(schemaId)) { + logger.verbose("Cache hit for schema id '{}'", schemaId); + return Mono.fromCallable(() -> idCache.get(schemaId)); + } + + return this.restService.getSchemaByIdWithResponseAsync(schemaId) + .onErrorMap(HttpResponseException.class, + e -> logger.logExceptionAsError( + new SchemaRegistryClientException("Fetching schema failed, unexpected service response.", e))) + .handle((response, sink) -> { + if (response == null) { + sink.error(logger.logExceptionAsError( + new SchemaRegistryClientException("Client returned null response"))); + return; + } + + if (response.getStatusCode() == 404) { + sink.error(logger.logExceptionAsError( + new SchemaRegistryClientException(String.format("Schema does not exist, id %s", schemaId)))); + return; + } + + 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); + sink.next(schemaObject); + }); + } + + public Mono getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) { + if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { + logger.verbose("Cache hit schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); + return Mono.fromCallable(() -> schemaStringCache.get(schemaString).getSchemaId()); + } + + return this.restService.getIdBySchemaContentWithResponseAsync(schemaGroup, schemaName, schemaType, schemaString) + .onErrorMap(HttpResponseException.class, e -> + logger.logExceptionAsError(new SchemaRegistryClientException(String.format( + "Failed to fetch ID for schema, unexpected service response. Group: '%s', name: '%s'", + schemaGroup, schemaName), e))) + .handle((response, sink) -> { + if (response == null) { + sink.error(logger.logExceptionAsError( + new SchemaRegistryClientException("Client returned null response"))); + return; + } + + if (response.getStatusCode() == 404) { + sink.error(logger.logExceptionAsError( + new SchemaRegistryClientException("Existing matching schema not found."))); + return; + } + + SchemaId schemaId = response.getValue(); + + resetIfNeeded(); + schemaStringCache.putIfAbsent( + getSchemaStringCacheKey(schemaGroup, schemaName, schemaString), + new SchemaRegistryObject( + schemaId.getId(), + schemaType, + schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), + getParseFunc(schemaType))); + logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); + sink.next(schemaId.getId()); + }); + } + + /** + * 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; + } + + 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/client/CachedSchemaRegistryClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClient.java index 07c2a53838bf3..bc075b74ded65 100644 --- 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 @@ -1,295 +1,35 @@ -// 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 reactor.core.publisher.Mono; 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<>(); - } +public final class CachedSchemaRegistryClient { + private final CachedSchemaRegistryAsyncClient asyncClient; - // 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; + CachedSchemaRegistryClient(CachedSchemaRegistryAsyncClient asyncClient) { + this.asyncClient = asyncClient; } - /** - * @return Azure Schema Registry service string encoding - */ - @Override public Charset getEncoding() { - return CachedSchemaRegistryClient.SCHEMA_REGISTRY_SERVICE_ENCODING; + return this.asyncClient.getEncoding(); } - /** - * @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)); + public SchemaRegistryObject register(String schemaGroup, String schemaName, String schemaString, String schemaType) { + return this.asyncClient.register(schemaGroup, schemaName, schemaString, schemaType).block(); } - @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; + public SchemaRegistryObject getSchemaById(String schemaId) { + return this.asyncClient.getSchemaById(schemaId).block(); } - @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; + return this.asyncClient.getSchemaId(schemaGroup, schemaName, schemaString, schemaType).block(); } } 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/client/CachedSchemaRegistryClientBuilder.java index 4dcbb71fa9253..f9cc105ff3eaa 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/client/CachedSchemaRegistryClientBuilder.java @@ -38,9 +38,9 @@ import java.util.function.Function; /** - * Builder implementation for {@link CachedSchemaRegistryClient}. + * Builder implementation for {@link CachedSchemaRegistryAsyncClient}. */ -@ServiceClientBuilder(serviceClients = CachedSchemaRegistryClient.class) +@ServiceClientBuilder(serviceClients = CachedSchemaRegistryAsyncClient.class) public class CachedSchemaRegistryClientBuilder { private final ClientLogger logger = new ClientLogger(CachedSchemaRegistryClientBuilder.class); @@ -115,15 +115,15 @@ 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} + * @param maxSchemaMapSize max size for internal schema caches in {@link CachedSchemaRegistryAsyncClient} * @return The updated {@link CachedSchemaRegistryClientBuilder} object. * @throws IllegalArgumentException on invalid maxSchemaMapSize value */ public CachedSchemaRegistryClientBuilder maxSchemaMapSize(int maxSchemaMapSize) { - if (maxSchemaMapSize < CachedSchemaRegistryClient.MAX_SCHEMA_MAP_SIZE_MINIMUM) { + if (maxSchemaMapSize < CachedSchemaRegistryAsyncClient.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))); + CachedSchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM))); } this.maxSchemaMapSize = maxSchemaMapSize; @@ -144,7 +144,7 @@ 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 CachedSchemaRegistryAsyncClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated {@link CachedSchemaRegistryClientBuilder} object. @@ -161,7 +161,7 @@ public CachedSchemaRegistryClientBuilder pipeline(HttpPipeline httpPipeline) { /** * Sets the {@link TokenCredential} to use when authenticating HTTP requests for this - * {@link CachedSchemaRegistryClient}. + * {@link CachedSchemaRegistryAsyncClient}. * * @param credential {@link TokenCredential} * @return The updated {@link CachedSchemaRegistryClientBuilder} object. @@ -188,7 +188,7 @@ 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 CachedSchemaRegistryAsyncClient} . * * @param retryPolicy user's retry policy applied to each request. * @return The updated {@link CachedSchemaRegistryClientBuilder} object. @@ -214,7 +214,7 @@ public CachedSchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) { * 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 + * Any com.azure.data.schemaregistry.Codec class will implement * - schemaType(), which specifies schema type, and * - parseSchemaString(), which parses schemas of the specified schema type from String to Object. * @@ -225,30 +225,30 @@ public CachedSchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) { */ public CachedSchemaRegistryClientBuilder addSchemaParser(Codec codec) { Objects.requireNonNull(codec, "'codec' cannot be null."); - if (CoreUtils.isNullOrEmpty(codec.schemaType())) { + if (CoreUtils.isNullOrEmpty(codec.getSchemaType())) { throw logger.logExceptionAsError( new IllegalArgumentException("Serialization type cannot be null or empty.")); } - if (this.typeParserMap.containsKey(codec.schemaType())) { + if (this.typeParserMap.containsKey(codec.getSchemaType())) { throw logger.logExceptionAsError( new IllegalArgumentException("Multiple parse methods for single serialization type may not be added.")); } - this.typeParserMap.put(codec.schemaType(), codec::parseSchemaString); + this.typeParserMap.put(codec.getSchemaType(), 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 CachedSchemaRegistryAsyncClient} based on options set in the builder. + * Every time {@code buildClient()} is called a new instance of {@link CachedSchemaRegistryAsyncClient} 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 CachedSchemaRegistryAsyncClient client}. * - * @return A {@link CachedSchemaRegistryClient} with the options set from the builder. + * @return A {@link CachedSchemaRegistryAsyncClient} 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 CachedSchemaRegistryAsyncClient buildAsyncClient() { // Authentications if (credential == null) { // Throw exception that credential and tokenCredential cannot be null @@ -292,8 +292,18 @@ public CachedSchemaRegistryClient buildClient() { this.maxSchemaMapSize = this.maxSchemaMapSize != null ? this.maxSchemaMapSize - : CachedSchemaRegistryClient.MAX_SCHEMA_MAP_SIZE_DEFAULT; + : CachedSchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_DEFAULT; - return new CachedSchemaRegistryClient(restService, maxSchemaMapSize, typeParserMap); + return new CachedSchemaRegistryAsyncClient(restService, maxSchemaMapSize, typeParserMap); } + + /** + * Creates synchronous {@link CachedSchemaRegistryClient} instance. + * See async builder method for options validation. + * + * @return {@link CachedSchemaRegistryClient} with the options set from the builder. + */ + public CachedSchemaRegistryClient buildClient() { + return new CachedSchemaRegistryClient(this.buildAsyncClient()); + } } 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 index 5d40f72d57012..92e302e422d53 100644 --- 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 @@ -6,7 +6,7 @@ import com.azure.core.exception.AzureException; /** - * Runtime exception to be returned from SchemaRegistryClient implementations. + * Runtime exception to be returned from CachedSchemaRegistryClient implementations. */ public class SchemaRegistryClientException extends AzureException { /** 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 index 2af1d810d07bc..e152c13f1819c 100644 --- 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 @@ -7,7 +7,7 @@ import java.util.function.Function; /** - * Stores all relevant information returned from SchemaRegistryClient layer. + * Stores all relevant information returned from CachedSchemaRegistryClient layer. */ public class SchemaRegistryObject { private final ClientLogger logger = new ClientLogger(SchemaRegistryObject.class); @@ -62,7 +62,7 @@ public String getSchemaType() { public Object deserialize() { if (this.deserialized == null) { String schemaString = new String( - this.schemaBytes, CachedSchemaRegistryClient.SCHEMA_REGISTRY_SERVICE_ENCODING); + this.schemaBytes, CachedSchemaRegistryAsyncClient.SCHEMA_REGISTRY_SERVICE_ENCODING); logger.verbose("Deserializing schema, id: '{}', schema string '{}'", this.schemaId, schemaString); 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 index f6da76235f3a0..037a0fecb1582 100644 --- 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 @@ -1,7 +1,7 @@ /** * Package containing the classes for - * - SchemaRegistryClient interface * - CachedSchemaRegistryClient + * - CachedSchemaRegistryAsyncClient * - AzureSchemaRegistryRestService. */ package com.azure.data.schemaregistry.client; 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 index ec8494935b94a..6ba39ea638dc7 100644 --- 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 @@ -3,39 +3,59 @@ package com.azure.data.schemaregistry; +import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; +import com.azure.data.schemaregistry.client.SchemaRegistryClientException; import com.azure.data.schemaregistry.client.SchemaRegistryObject; +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 org.mockito.Mockito; +import reactor.core.publisher.Mono; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; public class AbstractDataSerializerTest { - private static final String MOCK_GUID = new String(new char[AbstractDataSerDe.SCHEMA_ID_SIZE]).replace("\0", "a"); + private static final String MOCK_GUID = new String(new char[AbstractSchemaRegistrySerializer.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 testRegistryGuidPrefixedToPayload() { // manually add SchemaRegistryObject into mock registry client cache - SampleByteEncoder encoder = new SampleByteEncoder(); + SampleCodec encoder = new SampleCodec(); SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, - encoder.schemaType(), + encoder.getSchemaType(), 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); + CachedSchemaRegistryAsyncClient mockRegistryClient = getMockClient(); + Mockito.when(mockRegistryClient.getSchemaId(anyString(), anyString(), anyString(), anyString())) + .thenReturn(Mono.just(encoder.getSchemaString(null))); 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]; + ByteArrayOutputStream payload = serializer.serializeImpl(new ByteArrayOutputStream(), 1).block(); + ByteBuffer buffer = ByteBuffer.wrap(payload.toByteArray()); + byte[] schemaGuidByteArray = new byte[AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE]; try { buffer.get(schemaGuidByteArray); } catch (BufferUnderflowException e) { @@ -46,7 +66,7 @@ public void testRegistryGuidPrefixedToPayload() { assertEquals(MOCK_GUID, new String(schemaGuidByteArray)); int start = buffer.position() + buffer.arrayOffset(); - int length = buffer.limit() - AbstractDataSerDe.SCHEMA_ID_SIZE; + int length = buffer.limit() - AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE; byte[] encodedBytes = Arrays.copyOfRange(buffer.array(), start, start + length); assertTrue(Arrays.equals(encoder.encode(null).toByteArray(), encodedBytes)); } catch (SerializationException e) { @@ -58,12 +78,12 @@ public void testRegistryGuidPrefixedToPayload() { @Test public void testNullPayloadThrowsSerializationException() { TestDummySerializer serializer = new TestDummySerializer( - new MockSchemaRegistryClient(), + getMockClient(), true, false); try { - serializer.serializeImpl(null); + serializer.serializeImpl(new ByteArrayOutputStream(), null).block(); fail("Serializing null payload failed to throw SerializationException"); } catch (SerializationException e) { assertTrue(true); @@ -74,10 +94,10 @@ public void testNullPayloadThrowsSerializationException() { public void testSerializeWithNullByteEncoderThrows() { // don't set byte encoder on constructor TestDummySerializer serializer = new TestDummySerializer( - new MockSchemaRegistryClient(), false, false); + getMockClient(), false, false); try { - serializer.serializeImpl(1); + serializer.serializeImpl(new ByteArrayOutputStream(), null); } catch (SerializationException e) { assert (true); } @@ -97,8 +117,92 @@ public void testIfRegistryNullThenThrow() { } @Test - public void testDefaultAutoRegister() { - TestDummySerializer serializer = new TestDummySerializer(new MockSchemaRegistryClient(), true); - assertEquals(false, (boolean) serializer.autoRegisterSchemas); + public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientException, SerializationException { + // add sample codec impl and test that it is used for decoding payload + SampleCodec decoder = new SampleCodec(); + + // manually add SchemaRegistryObject to cache + SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, + decoder.getSchemaType(), + MOCK_AVRO_SCHEMA_STRING.getBytes(), + decoder::parseSchemaString); + + assertTrue(registered.deserialize() != null); + + CachedSchemaRegistryAsyncClient mockClient = getMockClient(); + Mockito.when(mockClient.getSchemaById(anyString())) + .thenReturn(Mono.just(registered)); + Mockito.when(mockClient.getEncoding()).thenReturn(StandardCharsets.UTF_8); + + // constructor loads deserializer codec + TestDummySerializer serializer = new TestDummySerializer(mockClient, true, true); + + assertEquals(MOCK_GUID, + serializer.schemaRegistryClient.getSchemaById(MOCK_GUID).block().getSchemaId()); + + serializer.deserializeImpl(new ByteArrayInputStream(getPayload())) + .subscribe(unused -> { + System.out.println(unused); + }, + ex -> System.out.println(ex)); + + assertEquals(SampleCodec.CONSTANT_PAYLOAD, + serializer.deserializeImpl(new ByteArrayInputStream(getPayload())).block()); + } + + @Test + public void testNullPayload() throws SchemaRegistryClientException, SerializationException { + TestDummySerializer deserializer = new TestDummySerializer( + getMockClient(), true, true); + assertNull(deserializer.deserializeImpl(null).block()); + } + + @Test + public void testIfTooShortPayloadThrow() { + TestDummySerializer serializer = new TestDummySerializer( + getMockClient(), true, true); + + try { + serializer.deserializeImpl(new ByteArrayInputStream("bad payload".getBytes())).block(); + fail("Too short payload did not throw SerializationException"); + } catch (SerializationException e) { + assertTrue(true); + } + } + + // TODO: add for non-existing guid + + @Test + public void testIfRegistryClientNullOnBuildThrow() { + try { + TestDummySerializer deserializer = new TestDummySerializer(null, true, true); + fail("should not get here."); + } catch (IllegalArgumentException e) { + // good + } + } + + private CachedSchemaRegistryAsyncClient getMockClient() { + return mock(CachedSchemaRegistryAsyncClient.class); + } + + private byte[] getPayload() throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(ByteBuffer.allocate(AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE) + .put(MOCK_GUID.getBytes(StandardCharsets.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(); + return out.toByteArray(); + } + + 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/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/SampleCodec.java similarity index 75% rename from sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleByteEncoder.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java index 768f7fbac496d..41882d67b189c 100644 --- 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/SampleCodec.java @@ -6,13 +6,13 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -public class SampleByteEncoder implements ByteEncoder { +public class SampleCodec implements Codec { - public SampleByteEncoder() { } + public SampleCodec() { } @Override public String getSchemaName(Object object) throws SerializationException { - return null; + return "schema name"; } @Override @@ -35,7 +35,7 @@ public ByteArrayOutputStream encode(Object object) throws SerializationException } @Override - public String schemaType() { + public String getSchemaType() { return "test"; } @@ -43,4 +43,11 @@ public String schemaType() { public String parseSchemaString(String s) { return s; } + + public static final String CONSTANT_PAYLOAD = "sample payload!"; + + @Override + public Object decodeBytes(byte[] bytes, Object o) throws SerializationException { + return CONSTANT_PAYLOAD; + } } 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 index 9844b9caaaad0..94d45bb54da9b 100644 --- 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 @@ -3,33 +3,22 @@ package com.azure.data.schemaregistry; -import com.azure.data.schemaregistry.client.SchemaRegistryClient; +import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; -public class TestDummySerializer extends AbstractDataSerializer { +public class TestDummySerializer extends AbstractSchemaRegistrySerializer { TestDummySerializer( - SchemaRegistryClient mockClient, + CachedSchemaRegistryAsyncClient mockClient, boolean byteEncoder, boolean autoRegisterSchemas) { super(mockClient); // allows simulating improperly written serializer constructor that does not initialize byte encoder if (byteEncoder) { - setByteEncoder(new SampleByteEncoder()); + setSerializerCodec(new SampleCodec()); } - this.autoRegisterSchemas = autoRegisterSchemas; - } - - TestDummySerializer( - SchemaRegistryClient mockClient, - boolean byteEncoder) { - super(mockClient); + this.addDeserializerCodec(new SampleCodec()); - // allows simulating improperly written serializer constructor that does not initialize byte encoder - if (byteEncoder) { - setByteEncoder(new SampleByteEncoder()); - } - - // default auto register + this.autoRegisterSchemas = autoRegisterSchemas; } } 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/CachedSchemaRegistryAsyncClientTest.java similarity index 88% rename from sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClientTest.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClientTest.java index 144d3c5d2b6df..c2b4792b5a00b 100644 --- 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/CachedSchemaRegistryAsyncClientTest.java @@ -18,7 +18,7 @@ import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; -public class CachedSchemaRegistryClientTest { +public class CachedSchemaRegistryAsyncClientTest { 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(); @@ -26,7 +26,7 @@ public class CachedSchemaRegistryClientTest { 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 CachedSchemaRegistryAsyncClient client; private AzureSchemaRegistryRestService restService; private HashMap guidCache; private HashMap schemaStringCache; @@ -41,7 +41,7 @@ protected void setUp() { this.typeParserDictionary.put(MOCK_SERIALIZATION, (s) -> s); this.restService = mock(AzureSchemaRegistryRestService.class); - this.client = new CachedSchemaRegistryClient( + this.client = new CachedSchemaRegistryAsyncClient( this.restService, this.guidCache, this.schemaStringCache, @@ -68,10 +68,10 @@ public void testRegisterThenSchemaCacheHit() throws Exception { assertEquals( MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).getSchemaId()); + client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); assertEquals( MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).getSchemaId()); + client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); verify(restService, times(1)) .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION, MOCK_AVRO_SCHEMA); @@ -90,8 +90,10 @@ public void testGetGuidThenSchemaCacheHit() throws Exception { 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)); + 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(restService, times(1)) .getIdBySchemaContentWithResponseAsync(anyString(), anyString(), anyString(), anyString()); @@ -111,8 +113,8 @@ public void testGetSchemaThenGuidCacheHit() throws Exception { MOCK_AVRO_SCHEMA, mockHeaders))); - SchemaRegistryObject first = client.getSchemaByGuid(mockId.toString()); - SchemaRegistryObject second = client.getSchemaByGuid(mockId.toString()); + SchemaRegistryObject first = client.getSchemaById(mockId.toString()).block(); + SchemaRegistryObject second = client.getSchemaById(mockId.toString()).block(); assertTrue(first.equals(second)); assertEquals(mockId.toString(), first.getSchemaId()); @@ -135,7 +137,7 @@ public void testClientReset() throws Exception { assertEquals( MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).getSchemaId()); + client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); client.reset(); @@ -147,7 +149,7 @@ public void testClientReset() throws Exception { assertEquals( MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).getSchemaId()); + client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); verify(restService, times(2)) .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION, MOCK_AVRO_SCHEMA); @@ -170,7 +172,7 @@ public void testBadRegisterRequestThenThrows() { "doesn't matter", "doesn't matter", "doesn't matter", - "doesn't matter"); + "doesn't matter").block(); fail("Should throw on 400 status code"); } catch (SchemaRegistryClientException e) { assert true; @@ -198,7 +200,7 @@ public void testGetIdBySchemaContentNotFoundThenThrows() { "doesn't matter", "doesn't matter", "doesn't matter", - "doesn't matter"); + "doesn't matter").block(); fail("Should throw on 404 status code"); } catch (SchemaRegistryClientException e) { assert true; @@ -221,10 +223,12 @@ public void testGetSchemaByIdNotFoundThenThrows() { null))); try { - client.getSchemaByGuid(mockId); + client.getSchemaById(mockId).block(); fail("Should have thrown on 404 status code"); } catch (SchemaRegistryClientException e) { assert true; + } catch (Exception e){ + assert false; } verify(restService, times(1)) From 6e734077a63485198fbffc60bcfd1649b45fc15e Mon Sep 17 00:00:00 2001 From: Arthur Erlendsson <30675661+arerlend@users.noreply.github.com> Date: Thu, 30 Jul 2020 22:09:56 -0700 Subject: [PATCH 02/17] Serializer-level updates to API defs (#13668) * remove setting codecs * update avro serializer constructor * move codec load to constructor * javadocs for constructor --- .../data/schemaregistry/avro/AvroCodec.java | 13 +++- .../SchemaRegistryAvroAsyncSerializer.java | 17 +++--- .../SchemaRegistryAvroSerializerBuilder.java | 8 +-- .../AbstractSchemaRegistrySerializer.java | 61 +++++++++---------- .../AbstractDataSerializerTest.java | 25 ++------ .../schemaregistry/TestDummySerializer.java | 12 +--- 6 files changed, 61 insertions(+), 75 deletions(-) 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 index 4b25995594527..ae022820c5870 100644 --- 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 @@ -25,14 +25,21 @@ public class AvroCodec implements Codec { private final ClientLogger logger = new ClientLogger(AvroCodec.class); private static final EncoderFactory ENCODER_FACTORY = EncoderFactory.get(); private static final DecoderFactory DECODER_FACTORY = DecoderFactory.get(); - private final boolean avroSpecificReader; + 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 */ - public AvroCodec(boolean avroSpecificReader) { - this.avroSpecificReader = avroSpecificReader; + public AvroCodec(Boolean avroSpecificReader) { + if (avroSpecificReader == null) { + this.avroSpecificReader = AvroCodec.AVRO_SPECIFIC_READER_DEFAULT; + } + else { + this.avroSpecificReader = avroSpecificReader; + } } @Override 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 index 6e2cf03202c85..17cea21c33556 100644 --- 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 @@ -11,6 +11,7 @@ import reactor.core.publisher.Mono; import java.io.InputStream; import java.io.OutputStream; +import java.util.Collections; /** * Asynchronous registry-based serializer implementation. @@ -26,15 +27,17 @@ public class SchemaRegistryAvroAsyncSerializer extends AbstractSchemaRegistrySer * @param autoRegisterSchemas */ SchemaRegistryAvroAsyncSerializer(CachedSchemaRegistryAsyncClient registryClient, AvroCodec codec, - String schemaGroup, boolean autoRegisterSchemas) { - super(registryClient); - - setSerializerCodec(codec); - addDeserializerCodec(codec); + String schemaGroup, Boolean autoRegisterSchemas) { + super(registryClient, codec, Collections.singletonList(codec)); // send configurations only - this.autoRegisterSchemas = autoRegisterSchemas; - this.schemaGroup = schemaGroup; + if (autoRegisterSchemas != null) { + this.autoRegisterSchemas = autoRegisterSchemas; + } + + if (schemaGroup != null) { + this.schemaGroup = schemaGroup; + } } @Override 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 83136b90893bb..0cc6f13e42153 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 @@ -16,10 +16,10 @@ public final class SchemaRegistryAvroSerializerBuilder { private String registryUrl; private TokenCredential credential; - private boolean autoRegisterSchemas; + private Boolean autoRegisterSchemas; private String schemaGroup; private Integer maxSchemaMapSize; - private boolean avroSpecificReader; + private Boolean avroSpecificReader; /** * Instantiates instance of Builder class. @@ -28,8 +28,8 @@ public final class SchemaRegistryAvroSerializerBuilder { public SchemaRegistryAvroSerializerBuilder() { this.registryUrl = null; this.credential = null; - this.autoRegisterSchemas = AbstractSchemaRegistrySerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; - this.schemaGroup = AbstractSchemaRegistrySerializer.SCHEMA_GROUP_DEFAULT; + this.autoRegisterSchemas = null; + this.schemaGroup = null; this.maxSchemaMapSize = null; this.avroSpecificReader = false; } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractSchemaRegistrySerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractSchemaRegistrySerializer.java index dcf9abf2d9306..7759d5ac35420 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractSchemaRegistrySerializer.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractSchemaRegistrySerializer.java @@ -17,7 +17,9 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.ConcurrentSkipListMap; import static com.azure.core.util.FluxUtil.monoError; @@ -30,42 +32,48 @@ public abstract class AbstractSchemaRegistrySerializer { public static final Boolean AUTO_REGISTER_SCHEMAS_DEFAULT = false; public static final String SCHEMA_GROUP_DEFAULT = "$default"; - public static final int SCHEMA_ID_SIZE = 32; + static final int SCHEMA_ID_SIZE = 32; - protected CachedSchemaRegistryAsyncClient schemaRegistryClient; + CachedSchemaRegistryAsyncClient schemaRegistryClient; - protected Codec serializerCodec = null; + private Codec serializerCodec; private final Map deserializerCodecMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); - protected String schemaType; + private String schemaType; + protected Boolean autoRegisterSchemas = AbstractSchemaRegistrySerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; protected String schemaGroup = AbstractSchemaRegistrySerializer.SCHEMA_GROUP_DEFAULT; /** - * @param schemaRegistryClient registry client to be used for storing schemas. Not null. + * Constructor for AbstractSchemaRegistrySerializer implementations. + * + * @param schemaRegistryClient client to be used for interfacing with Schema Registry service + * @param serializerCodec Codec to be used for serialization operations + * @param deserializerCodecList list of Codecs to be used to deserialize incoming payloads */ public AbstractSchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, - Codec serializerCodec, Map deserializerCodecMap) { + Codec serializerCodec, List deserializerCodecList) { + Objects.requireNonNull(serializerCodec); + Objects.requireNonNull(deserializerCodecList); + if (schemaRegistryClient == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Schema registry client must be initialized and passed into builder.")); } - this.schemaRegistryClient = schemaRegistryClient; - this.serializerCodec = serializerCodec; - this.deserializerCodecMap.putAll(deserializerCodecMap); - } - /** - * Set Codec class to be used for serialized objects into bytes - * - * @param codec Codec instance - */ - protected void setSerializerCodec(Codec codec) { - if (this.serializerCodec != null) { + if (deserializerCodecList.size() == 0) { throw logger.logExceptionAsError( - new IllegalArgumentException("Setting multiple encoders on serializer not permitted")); + new IllegalArgumentException("At least one Codec must be provided for deserialization.")); + } + + this.schemaRegistryClient = schemaRegistryClient; + this.serializerCodec = serializerCodec; + for (Codec c : deserializerCodecList) { + if (this.deserializerCodecMap.containsKey(c.getSchemaType())) { + throw logger.logExceptionAsError( + new IllegalArgumentException("Only on Codec can be provided per schema serialization type.")); + } + this.deserializerCodecMap.put(c.getSchemaType(), c); } - this.serializerCodec = codec; - this.schemaType = codec.getSchemaType(); } /** @@ -247,19 +255,6 @@ private String getSchemaIdFromPayload(ByteBuffer buffer) throws SerializationExc return new String(schemaGuidByteArray, schemaRegistryClient.getEncoding()); } - /** - * Loads Codec to be used for decoding message payloads of specified schema type. - * - * @param codec Codec class instance to be loaded - */ - protected void addDeserializerCodec(Codec codec) { - if (codec == null) { - throw logger.logExceptionAsError(new IllegalArgumentException("'codec' cannot be null")); - } - - this.deserializerCodecMap.put(codec.getSchemaType(), codec); - } - /** * 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 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 index 6ba39ea638dc7..3ee0abb305f14 100644 --- 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 @@ -50,7 +50,7 @@ public void testRegistryGuidPrefixedToPayload() { .thenReturn(Mono.just(encoder.getSchemaString(null))); TestDummySerializer serializer = new TestDummySerializer( - mockRegistryClient, true, false); + mockRegistryClient, false); try { ByteArrayOutputStream payload = serializer.serializeImpl(new ByteArrayOutputStream(), 1).block(); @@ -79,7 +79,6 @@ public void testRegistryGuidPrefixedToPayload() { public void testNullPayloadThrowsSerializationException() { TestDummySerializer serializer = new TestDummySerializer( getMockClient(), - true, false); try { @@ -90,24 +89,12 @@ public void testNullPayloadThrowsSerializationException() { } } - @Test - public void testSerializeWithNullByteEncoderThrows() { - // don't set byte encoder on constructor - TestDummySerializer serializer = new TestDummySerializer( - getMockClient(), false, false); - - try { - serializer.serializeImpl(new ByteArrayOutputStream(), null); - } catch (SerializationException e) { - assert (true); - } - } @Test public void testIfRegistryNullThenThrow() { try { TestDummySerializer serializer = new TestDummySerializer( - null, true, false); + null, false); fail("Building serializer instance with null registry client failed to throw"); } catch (IllegalArgumentException e) { assertTrue(true); @@ -135,7 +122,7 @@ public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientE Mockito.when(mockClient.getEncoding()).thenReturn(StandardCharsets.UTF_8); // constructor loads deserializer codec - TestDummySerializer serializer = new TestDummySerializer(mockClient, true, true); + TestDummySerializer serializer = new TestDummySerializer(mockClient, true); assertEquals(MOCK_GUID, serializer.schemaRegistryClient.getSchemaById(MOCK_GUID).block().getSchemaId()); @@ -153,14 +140,14 @@ public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientE @Test public void testNullPayload() throws SchemaRegistryClientException, SerializationException { TestDummySerializer deserializer = new TestDummySerializer( - getMockClient(), true, true); + getMockClient(), true); assertNull(deserializer.deserializeImpl(null).block()); } @Test public void testIfTooShortPayloadThrow() { TestDummySerializer serializer = new TestDummySerializer( - getMockClient(), true, true); + getMockClient(), true); try { serializer.deserializeImpl(new ByteArrayInputStream("bad payload".getBytes())).block(); @@ -175,7 +162,7 @@ public void testIfTooShortPayloadThrow() { @Test public void testIfRegistryClientNullOnBuildThrow() { try { - TestDummySerializer deserializer = new TestDummySerializer(null, true, true); + TestDummySerializer deserializer = new TestDummySerializer(null, true); fail("should not get here."); } catch (IllegalArgumentException e) { // good 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 index 94d45bb54da9b..e16c20685f856 100644 --- 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 @@ -5,19 +5,13 @@ import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; +import java.util.Collections; + public class TestDummySerializer extends AbstractSchemaRegistrySerializer { TestDummySerializer( CachedSchemaRegistryAsyncClient mockClient, - boolean byteEncoder, boolean autoRegisterSchemas) { - super(mockClient); - - // allows simulating improperly written serializer constructor that does not initialize byte encoder - if (byteEncoder) { - setSerializerCodec(new SampleCodec()); - } - - this.addDeserializerCodec(new SampleCodec()); + super(mockClient, new SampleCodec(), Collections.singletonList(new SampleCodec())); this.autoRegisterSchemas = autoRegisterSchemas; } From 57290b6d49475c5d52bdb2cc6dba5be8d088062b Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Fri, 31 Jul 2020 02:25:05 -0700 Subject: [PATCH 03/17] Update schema registry client APIs (#13676) --- .../SchemaRegistryAvroAsyncSerializer.java | 19 ++--- .../avro/SchemaRegistryAvroSerializer.java | 4 +- .../SchemaRegistryAvroSerializerBuilder.java | 23 +++-- ...zer.java => SchemaRegistrySerializer.java} | 48 +++++++---- .../CachedSchemaRegistryAsyncClient.java | 83 ++++++++++++++----- .../client/CachedSchemaRegistryClient.java | 34 +++++--- .../CachedSchemaRegistryClientBuilder.java | 13 ++- ...java => SchemaRegistrySerializerTest.java} | 27 +++--- .../schemaregistry/TestDummySerializer.java | 3 +- .../CachedSchemaRegistryAsyncClientTest.java | 18 ++-- 10 files changed, 165 insertions(+), 107 deletions(-) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{AbstractSchemaRegistrySerializer.java => SchemaRegistrySerializer.java} (86%) rename sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/{AbstractDataSerializerTest.java => SchemaRegistrySerializerTest.java} (86%) 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 index 17cea21c33556..a875e7a9161c5 100644 --- 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 @@ -5,7 +5,7 @@ import com.azure.core.experimental.serializer.ObjectSerializer; import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.AbstractSchemaRegistrySerializer; +import com.azure.data.schemaregistry.SchemaRegistrySerializer; import com.azure.data.schemaregistry.SerializationException; import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; import reactor.core.publisher.Mono; @@ -16,7 +16,7 @@ /** * Asynchronous registry-based serializer implementation. */ -public class SchemaRegistryAvroAsyncSerializer extends AbstractSchemaRegistrySerializer implements ObjectSerializer { +public class SchemaRegistryAvroAsyncSerializer extends SchemaRegistrySerializer implements ObjectSerializer { private final ClientLogger logger = new ClientLogger(SchemaRegistryAvroAsyncSerializer.class); /** @@ -28,16 +28,7 @@ public class SchemaRegistryAvroAsyncSerializer extends AbstractSchemaRegistrySer */ SchemaRegistryAvroAsyncSerializer(CachedSchemaRegistryAsyncClient registryClient, AvroCodec codec, String schemaGroup, Boolean autoRegisterSchemas) { - super(registryClient, codec, Collections.singletonList(codec)); - - // send configurations only - if (autoRegisterSchemas != null) { - this.autoRegisterSchemas = autoRegisterSchemas; - } - - if (schemaGroup != null) { - this.schemaGroup = schemaGroup; - } + super(registryClient, codec, Collections.singletonList(codec), autoRegisterSchemas, schemaGroup); } @Override @@ -46,12 +37,12 @@ public Mono serialize(S s, Object o) { return Mono.empty(); } - return this.serializeImpl(s, o); + return super.serialize(s, o); } @Override public Mono deserialize(InputStream stream, Class clazz) { - return this.deserializeImpl(stream) + return this.deserialize(stream) .map(o -> { if (clazz.isInstance(o)) { return clazz.cast(o); 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 942b36eb9fa32..fbc89c7134e83 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,7 +3,7 @@ package com.azure.data.schemaregistry.avro; -import com.azure.data.schemaregistry.AbstractSchemaRegistrySerializer; +import com.azure.data.schemaregistry.SchemaRegistrySerializer; import com.azure.data.schemaregistry.SerializationException; import java.io.ByteArrayInputStream; @@ -17,7 +17,7 @@ * * Pluggable with the core Azure SDK Serializer interface. * - * @see AbstractSchemaRegistrySerializer See AbstractSchemaRegistrySerializer for internal serialization implementation + * @see SchemaRegistrySerializer See AbstractSchemaRegistrySerializer for internal serialization implementation */ public class SchemaRegistryAvroSerializer { private final SchemaRegistryAvroAsyncSerializer serializer; 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 0cc6f13e42153..5c6c2da73a656 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 @@ -4,7 +4,6 @@ package com.azure.data.schemaregistry.avro; import com.azure.core.credential.TokenCredential; -import com.azure.data.schemaregistry.AbstractSchemaRegistrySerializer; import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; import com.azure.data.schemaregistry.client.CachedSchemaRegistryClientBuilder; @@ -18,7 +17,7 @@ public final class SchemaRegistryAvroSerializerBuilder { private TokenCredential credential; private Boolean autoRegisterSchemas; private String schemaGroup; - private Integer maxSchemaMapSize; + private Integer maxCacheSize; private Boolean avroSpecificReader; /** @@ -30,7 +29,7 @@ public SchemaRegistryAvroSerializerBuilder() { this.credential = null; this.autoRegisterSchemas = null; this.schemaGroup = null; - this.maxSchemaMapSize = null; + this.maxCacheSize = null; this.avroSpecificReader = false; } @@ -102,11 +101,11 @@ public SchemaRegistryAvroSerializerBuilder avroSpecificReader(boolean avroSpecif * Specifies maximum schema object cache size for underlying CachedSchemaRegistryAsyncClient. If specified cache * size is exceeded, all caches are recycled. * - * @param maxSchemaMapSize maximum number of schemas per cache + * @param maxCacheSize maximum number of schemas per cache * @return updated {@link SchemaRegistryAvroSerializerBuilder} instance */ - public SchemaRegistryAvroSerializerBuilder maxSchemaMapSize(int maxSchemaMapSize) { - this.maxSchemaMapSize = maxSchemaMapSize; + public SchemaRegistryAvroSerializerBuilder maxCacheSize(int maxCacheSize) { + this.maxCacheSize = maxCacheSize; return this; } @@ -117,8 +116,8 @@ public SchemaRegistryAvroSerializerBuilder maxSchemaMapSize(int maxSchemaMapSize * @throws NullPointerException if parameters are incorrectly set. * @throws IllegalArgumentException if credential is not set. */ - public SchemaRegistryAvroSerializer buildClient() { - return new SchemaRegistryAvroSerializer(this.buildAsyncClient()); + public SchemaRegistryAvroSerializer buildSerializer() { + return new SchemaRegistryAvroSerializer(this.buildAsyncSerializer()); } /** @@ -128,19 +127,19 @@ public SchemaRegistryAvroSerializer buildClient() { * @throws NullPointerException if parameters are incorrectly set. * @throws IllegalArgumentException if credential is not set. */ - public SchemaRegistryAvroAsyncSerializer buildAsyncClient() { + public SchemaRegistryAvroAsyncSerializer buildAsyncSerializer() { CachedSchemaRegistryClientBuilder builder = new CachedSchemaRegistryClientBuilder() .endpoint(registryUrl) .credential(credential); - if (maxSchemaMapSize != null) { - builder.maxSchemaMapSize(maxSchemaMapSize); + if (maxCacheSize != null) { + builder.maxCacheSize(maxCacheSize); } AvroCodec codec = new AvroCodec(this.avroSpecificReader); CachedSchemaRegistryAsyncClient client = builder - .addSchemaParser(codec) + .addCodec(codec) .buildAsyncClient(); return new SchemaRegistryAvroAsyncSerializer(client, codec, this.schemaGroup, diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractSchemaRegistrySerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java similarity index 86% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractSchemaRegistrySerializer.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java index 7759d5ac35420..f6740ab5a0899 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/AbstractSchemaRegistrySerializer.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java @@ -27,11 +27,11 @@ /** * Common implementation for all registry-based serializers. */ -public abstract class AbstractSchemaRegistrySerializer { - private final ClientLogger logger = new ClientLogger(AbstractSchemaRegistrySerializer.class); +public abstract class SchemaRegistrySerializer { + private final ClientLogger logger = new ClientLogger(SchemaRegistrySerializer.class); - public static final Boolean AUTO_REGISTER_SCHEMAS_DEFAULT = false; - public static final String SCHEMA_GROUP_DEFAULT = "$default"; + static final Boolean AUTO_REGISTER_SCHEMAS_DEFAULT = false; + static final String SCHEMA_GROUP_DEFAULT = "$default"; static final int SCHEMA_ID_SIZE = 32; CachedSchemaRegistryAsyncClient schemaRegistryClient; @@ -40,8 +40,8 @@ public abstract class AbstractSchemaRegistrySerializer { private final Map deserializerCodecMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); private String schemaType; - protected Boolean autoRegisterSchemas = AbstractSchemaRegistrySerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; - protected String schemaGroup = AbstractSchemaRegistrySerializer.SCHEMA_GROUP_DEFAULT; + Boolean autoRegisterSchemas = SchemaRegistrySerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; + String schemaGroup = SchemaRegistrySerializer.SCHEMA_GROUP_DEFAULT; /** * Constructor for AbstractSchemaRegistrySerializer implementations. @@ -50,8 +50,15 @@ public abstract class AbstractSchemaRegistrySerializer { * @param serializerCodec Codec to be used for serialization operations * @param deserializerCodecList list of Codecs to be used to deserialize incoming payloads */ - public AbstractSchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, + public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, Codec serializerCodec, List deserializerCodecList) { + this(schemaRegistryClient, serializerCodec, deserializerCodecList, null, null); + } + + public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, + Codec serializerCodec, List deserializerCodecList, Boolean autoRegisterSchemas, + String schemaGroup) { + Objects.requireNonNull(serializerCodec); Objects.requireNonNull(deserializerCodecList); @@ -74,6 +81,15 @@ public AbstractSchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRe } this.deserializerCodecMap.put(c.getSchemaType(), c); } + + // send configurations only + if (autoRegisterSchemas != null) { + this.autoRegisterSchemas = autoRegisterSchemas; + } + + if (schemaGroup != null) { + this.schemaGroup = schemaGroup; + } } /** @@ -87,7 +103,7 @@ public AbstractSchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRe * @return byte array containing encoded bytes with prefixed schema ID * @throws SerializationException if serialization operation fails during runtime. */ - protected Mono serializeImpl(T s, Object object) { + protected Mono serialize(T s, Object object) { if (object == null) { return monoError(logger, new SerializationException( "Null object, behavior should be defined in concrete serializer implementation.")); @@ -133,7 +149,7 @@ protected Mono serializeImpl(T s, Object object) { } }) .handle((id, sink) -> { - ByteBuffer idBuffer = ByteBuffer.allocate(AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE) + ByteBuffer idBuffer = ByteBuffer.allocate(SchemaRegistrySerializer.SCHEMA_ID_SIZE) .put(id.getBytes(StandardCharsets.UTF_8)); try { s.write(idBuffer.array()); @@ -154,7 +170,7 @@ protected Mono serializeImpl(T s, Object object) { * @return object, deserialized with the prefixed schema * @throws SerializationException if deserialization of registry schema or message payload fails. */ - protected Mono deserializeImpl(InputStream s) throws SerializationException { + protected Mono deserialize(InputStream s) throws SerializationException { if (s == null) { return Mono.empty(); } @@ -173,9 +189,9 @@ protected Mono deserializeImpl(InputStream s) throws SerializationExcept String schemaId = getSchemaIdFromPayload(buffer); System.out.println(schemaId); - SchemaRegistryObject block = this.schemaRegistryClient.getSchemaById(schemaId).block(); + SchemaRegistryObject block = this.schemaRegistryClient.getSchema(schemaId).block(); System.out.println(block); - return this.schemaRegistryClient.getSchemaById(schemaId) + return this.schemaRegistryClient.getSchema(schemaId) .onErrorMap(IOException.class, e -> logger.logExceptionAsError(new SerializationException(e.getMessage(), e))) .handle((registryObject, sink) -> { @@ -190,7 +206,7 @@ protected Mono deserializeImpl(InputStream s) throws SerializationExcept } int start = buffer.position() + buffer.arrayOffset(); - int length = buffer.limit() - AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE; + int length = buffer.limit() - SchemaRegistrySerializer.SCHEMA_ID_SIZE; byte[] b = Arrays.copyOfRange(buffer.array(), start, start + length); Codec codec = getDeserializerCodec(registryObject); @@ -245,14 +261,14 @@ private Codec getDeserializerCodec(SchemaRegistryObject registryObject) throws S * @throws SerializationException if schema ID could not be extracted from payload */ private String getSchemaIdFromPayload(ByteBuffer buffer) throws SerializationException { - byte[] schemaGuidByteArray = new byte[AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE]; + byte[] schemaGuidByteArray = new byte[SchemaRegistrySerializer.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()); + return new String(schemaGuidByteArray, StandardCharsets.UTF_8); } /** @@ -270,7 +286,7 @@ private String getSchemaIdFromPayload(ByteBuffer buffer) throws SerializationExc private Mono maybeRegisterSchema( String schemaGroup, String schemaName, String schemaString, String schemaType) { if (this.autoRegisterSchemas) { - return this.schemaRegistryClient.register(schemaGroup, schemaName, schemaString, schemaType) + return this.schemaRegistryClient.registerSchema(schemaGroup, schemaName, schemaString, schemaType) .map(SchemaRegistryObject::getSchemaId); } else { return this.schemaRegistryClient.getSchemaId( diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClient.java index a244f03a896c3..df86089a74d37 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClient.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClient.java @@ -5,6 +5,9 @@ import com.azure.core.annotation.ServiceClient; import com.azure.core.exception.HttpResponseException; +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.client.implementation.AzureSchemaRegistryRestService; import com.azure.data.schemaregistry.client.implementation.models.SchemaId; @@ -22,7 +25,8 @@ * 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. + * using {@link CachedSchemaRegistryClientBuilder#maxCacheSize(int)}, otherwise {@code 1000} will be used as the + * default. *

* Two maps are maintained. *

    @@ -37,9 +41,10 @@ builder = CachedSchemaRegistryClientBuilder.class, serviceInterfaces = AzureSchemaRegistryRestService.class) public final class CachedSchemaRegistryAsyncClient { + private final ClientLogger logger = new ClientLogger(CachedSchemaRegistryAsyncClient.class); - public static final Charset SCHEMA_REGISTRY_SERVICE_ENCODING = StandardCharsets.UTF_8; + 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; @@ -73,26 +78,30 @@ public final class CachedSchemaRegistryAsyncClient { this.maxSchemaMapSize = MAX_SCHEMA_MAP_SIZE_DEFAULT; } - /** - * @return Azure Schema Registry service string encoding - */ - public Charset getEncoding() { - return CachedSchemaRegistryAsyncClient.SCHEMA_REGISTRY_SERVICE_ENCODING; - } - - public Mono register( + public Mono registerSchema( String schemaGroup, String schemaName, String schemaString, String schemaType) { if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { logger.verbose( - "Cache hit schema string. Group: '{}', name: '{}', schema type: '{}', payload: '{}'", - schemaGroup, schemaName, schemaType, schemaString); + "Cache hit schema string. Group: '{}', name: '{}', schema type: '{}', payload: '{}'", + schemaGroup, schemaName, schemaType, schemaString); return Mono.fromCallable( () -> schemaStringCache.get(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))); } + return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType) + .map(response -> response.getValue()); + } + + public Mono> registerSchemaWithResponse(String schemaGroup, String schemaName, + String schemaString, String schemaType) { + return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE); + } + + Mono> registerSchemaWithResponse(String schemaGroup, String schemaName, + String schemaString, String schemaType, Context context) { logger.verbose( "Registering schema. Group: '{}', name: '{}', serialization type: '{}', payload: '{}'", - schemaGroup, schemaName, schemaType, schemaString); + schemaGroup, schemaName, schemaType, schemaString); return this.restService.createSchemaWithResponseAsync(schemaGroup, schemaName, schemaType, schemaString) .onErrorMap(HttpResponseException.class, e -> logger.logExceptionAsError( @@ -118,20 +127,30 @@ public Mono register( getParseFunc(schemaType)); resetIfNeeded(); - schemaStringCache.putIfAbsent(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString), registered); + schemaStringCache + .putIfAbsent(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString), registered); logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); - sink.next(registered); + SimpleResponse schemaRegistryObjectSimpleResponse = new SimpleResponse<>( + response.getRequest(), response.getStatusCode(), + response.getHeaders(), registered); + sink.next(schemaRegistryObjectSimpleResponse); }); } - public Mono getSchemaById(String schemaId) { - Objects.requireNonNull(schemaId, "'schemaId' should not be null"); - + 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); + } + + 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.getSchemaByIdWithResponseAsync(schemaId) .onErrorMap(HttpResponseException.class, e -> logger.logExceptionAsError( @@ -159,16 +178,33 @@ public Mono getSchemaById(String schemaId) { resetIfNeeded(); idCache.putIfAbsent(schemaId, schemaObject); logger.verbose("Cached schema object. Path: '{}'", schemaId); - sink.next(schemaObject); + SimpleResponse schemaRegistryObjectSimpleResponse = new SimpleResponse<>( + response.getRequest(), response.getStatusCode(), + response.getHeaders(), schemaObject); + sink.next(schemaRegistryObjectSimpleResponse); }); } + public Mono getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) { + if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { logger.verbose("Cache hit schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); return Mono.fromCallable(() -> schemaStringCache.get(schemaString).getSchemaId()); } + return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType) + .map(response -> response.getValue()); + } + + public Mono> getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, + String schemaType) { + return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE); + } + + Mono> getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, + String schemaType, Context context) { + return this.restService.getIdBySchemaContentWithResponseAsync(schemaGroup, schemaName, schemaType, schemaString) .onErrorMap(HttpResponseException.class, e -> logger.logExceptionAsError(new SchemaRegistryClientException(String.format( @@ -198,20 +234,25 @@ public Mono getSchemaId(String schemaGroup, String schemaName, String sc schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), getParseFunc(schemaType))); logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); - sink.next(schemaId.getId()); + + SimpleResponse schemaIdResponse = new SimpleResponse<>( + response.getRequest(), response.getStatusCode(), + response.getHeaders(), schemaId.getId()); + sink.next(schemaIdResponse); }); } /** * Explicit call to clear all caches. */ - public void reset() { + public 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 */ 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 index bc075b74ded65..3e4a3aa111ffa 100644 --- 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 @@ -1,11 +1,9 @@ package com.azure.data.schemaregistry.client; import com.azure.core.annotation.ServiceClient; -import com.azure.data.schemaregistry.Codec; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; import com.azure.data.schemaregistry.client.implementation.AzureSchemaRegistryRestService; -import reactor.core.publisher.Mono; - -import java.nio.charset.Charset; @ServiceClient( builder = CachedSchemaRegistryClientBuilder.class, @@ -17,19 +15,33 @@ public final class CachedSchemaRegistryClient { this.asyncClient = asyncClient; } - public Charset getEncoding() { - return this.asyncClient.getEncoding(); + public SchemaRegistryObject registerSchema(String schemaGroup, String schemaName, String schemaString, + String schemaType) { + return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE).getValue(); + } + + public Response registerSchemaWithResponse(String schemaGroup, String schemaName, + String schemaString, String schemaType, Context context) { + return this.asyncClient.registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType, + context).block(); } - public SchemaRegistryObject register(String schemaGroup, String schemaName, String schemaString, String schemaType) { - return this.asyncClient.register(schemaGroup, schemaName, schemaString, schemaType).block(); + public SchemaRegistryObject getSchema(String schemaId) { + return getSchemaWithResponse(schemaId, Context.NONE).getValue(); } - public SchemaRegistryObject getSchemaById(String schemaId) { - return this.asyncClient.getSchemaById(schemaId).block(); + public Response getSchemaWithResponse(String schemaId, Context context) { + return this.asyncClient.getSchemaWithResponse(schemaId).block(); } public String getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) { - return this.asyncClient.getSchemaId(schemaGroup, schemaName, schemaString, schemaType).block(); + return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE).getValue(); } + + public Response getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, + String schemaType, Context context) { + return this.asyncClient.getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType, context) + .block(); + } + } 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/client/CachedSchemaRegistryClientBuilder.java index f9cc105ff3eaa..36cec8ce65d15 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/client/CachedSchemaRegistryClientBuilder.java @@ -26,7 +26,6 @@ import com.azure.data.schemaregistry.Codec; import com.azure.data.schemaregistry.client.implementation.AzureSchemaRegistryRestService; import com.azure.data.schemaregistry.client.implementation.AzureSchemaRegistryRestServiceClientBuilder; - import java.net.MalformedURLException; import java.net.URL; import java.time.temporal.ChronoUnit; @@ -115,18 +114,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 CachedSchemaRegistryAsyncClient} + * @param maxCacheSize max size for internal schema caches in {@link CachedSchemaRegistryAsyncClient} * @return The updated {@link CachedSchemaRegistryClientBuilder} object. - * @throws IllegalArgumentException on invalid maxSchemaMapSize value + * @throws IllegalArgumentException on invalid maxCacheSize value */ - public CachedSchemaRegistryClientBuilder maxSchemaMapSize(int maxSchemaMapSize) { - if (maxSchemaMapSize < CachedSchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM) { + public CachedSchemaRegistryClientBuilder maxCacheSize(int maxCacheSize) { + if (maxCacheSize < CachedSchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM) { throw logger.logExceptionAsError(new IllegalArgumentException( String.format("Schema map size must be greater than %s entries", CachedSchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM))); } - this.maxSchemaMapSize = maxSchemaMapSize; + this.maxSchemaMapSize = maxCacheSize; return this; } @@ -223,7 +222,7 @@ public CachedSchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) { * @param codec Codec class implementation * @return The updated {@link CachedSchemaRegistryClientBuilder} object. */ - public CachedSchemaRegistryClientBuilder addSchemaParser(Codec codec) { + public CachedSchemaRegistryClientBuilder addCodec(Codec codec) { Objects.requireNonNull(codec, "'codec' cannot be null."); if (CoreUtils.isNullOrEmpty(codec.getSchemaType())) { throw logger.logExceptionAsError( 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/SchemaRegistrySerializerTest.java similarity index 86% rename from sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/AbstractDataSerializerTest.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java index 3ee0abb305f14..101f9ce39cdbb 100644 --- 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/SchemaRegistrySerializerTest.java @@ -28,8 +28,8 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; -public class AbstractDataSerializerTest { - private static final String MOCK_GUID = new String(new char[AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE]).replace("\0", "a"); +public class SchemaRegistrySerializerTest { + private static final String MOCK_GUID = new String(new char[SchemaRegistrySerializer.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); @@ -53,9 +53,9 @@ public void testRegistryGuidPrefixedToPayload() { mockRegistryClient, false); try { - ByteArrayOutputStream payload = serializer.serializeImpl(new ByteArrayOutputStream(), 1).block(); + ByteArrayOutputStream payload = serializer.serialize(new ByteArrayOutputStream(), 1).block(); ByteBuffer buffer = ByteBuffer.wrap(payload.toByteArray()); - byte[] schemaGuidByteArray = new byte[AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE]; + byte[] schemaGuidByteArray = new byte[SchemaRegistrySerializer.SCHEMA_ID_SIZE]; try { buffer.get(schemaGuidByteArray); } catch (BufferUnderflowException e) { @@ -66,7 +66,7 @@ public void testRegistryGuidPrefixedToPayload() { assertEquals(MOCK_GUID, new String(schemaGuidByteArray)); int start = buffer.position() + buffer.arrayOffset(); - int length = buffer.limit() - AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE; + int length = buffer.limit() - SchemaRegistrySerializer.SCHEMA_ID_SIZE; byte[] encodedBytes = Arrays.copyOfRange(buffer.array(), start, start + length); assertTrue(Arrays.equals(encoder.encode(null).toByteArray(), encodedBytes)); } catch (SerializationException e) { @@ -82,7 +82,7 @@ public void testNullPayloadThrowsSerializationException() { false); try { - serializer.serializeImpl(new ByteArrayOutputStream(), null).block(); + serializer.serialize(new ByteArrayOutputStream(), null).block(); fail("Serializing null payload failed to throw SerializationException"); } catch (SerializationException e) { assertTrue(true); @@ -117,31 +117,30 @@ public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientE assertTrue(registered.deserialize() != null); CachedSchemaRegistryAsyncClient mockClient = getMockClient(); - Mockito.when(mockClient.getSchemaById(anyString())) + Mockito.when(mockClient.getSchema(anyString())) .thenReturn(Mono.just(registered)); - Mockito.when(mockClient.getEncoding()).thenReturn(StandardCharsets.UTF_8); // constructor loads deserializer codec TestDummySerializer serializer = new TestDummySerializer(mockClient, true); assertEquals(MOCK_GUID, - serializer.schemaRegistryClient.getSchemaById(MOCK_GUID).block().getSchemaId()); + serializer.schemaRegistryClient.getSchema(MOCK_GUID).block().getSchemaId()); - serializer.deserializeImpl(new ByteArrayInputStream(getPayload())) + serializer.deserialize(new ByteArrayInputStream(getPayload())) .subscribe(unused -> { System.out.println(unused); }, ex -> System.out.println(ex)); assertEquals(SampleCodec.CONSTANT_PAYLOAD, - serializer.deserializeImpl(new ByteArrayInputStream(getPayload())).block()); + serializer.deserialize(new ByteArrayInputStream(getPayload())).block()); } @Test public void testNullPayload() throws SchemaRegistryClientException, SerializationException { TestDummySerializer deserializer = new TestDummySerializer( getMockClient(), true); - assertNull(deserializer.deserializeImpl(null).block()); + assertNull(deserializer.deserialize(null).block()); } @Test @@ -150,7 +149,7 @@ public void testIfTooShortPayloadThrow() { getMockClient(), true); try { - serializer.deserializeImpl(new ByteArrayInputStream("bad payload".getBytes())).block(); + serializer.deserialize(new ByteArrayInputStream("bad payload".getBytes())).block(); fail("Too short payload did not throw SerializationException"); } catch (SerializationException e) { assertTrue(true); @@ -175,7 +174,7 @@ private CachedSchemaRegistryAsyncClient getMockClient() { private byte[] getPayload() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(ByteBuffer.allocate(AbstractSchemaRegistrySerializer.SCHEMA_ID_SIZE) + out.write(ByteBuffer.allocate(SchemaRegistrySerializer.SCHEMA_ID_SIZE) .put(MOCK_GUID.getBytes(StandardCharsets.UTF_8)) .array()); GenericRecord record = getAvroRecord(); 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 index e16c20685f856..833dd1654bf1d 100644 --- 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 @@ -7,12 +7,13 @@ import java.util.Collections; -public class TestDummySerializer extends AbstractSchemaRegistrySerializer { +public class TestDummySerializer extends SchemaRegistrySerializer { TestDummySerializer( CachedSchemaRegistryAsyncClient mockClient, boolean autoRegisterSchemas) { super(mockClient, new SampleCodec(), Collections.singletonList(new SampleCodec())); + // allows simulating improperly written serializer constructor that does not initialize byte encoder this.autoRegisterSchemas = autoRegisterSchemas; } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClientTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClientTest.java index c2b4792b5a00b..e89cdee323665 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClientTest.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClientTest.java @@ -68,10 +68,10 @@ public void testRegisterThenSchemaCacheHit() throws Exception { assertEquals( MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); assertEquals( MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); verify(restService, times(1)) .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION, MOCK_AVRO_SCHEMA); @@ -113,8 +113,8 @@ public void testGetSchemaThenGuidCacheHit() throws Exception { MOCK_AVRO_SCHEMA, mockHeaders))); - SchemaRegistryObject first = client.getSchemaById(mockId.toString()).block(); - SchemaRegistryObject second = client.getSchemaById(mockId.toString()).block(); + SchemaRegistryObject first = client.getSchema(mockId.toString()).block(); + SchemaRegistryObject second = client.getSchema(mockId.toString()).block(); assertTrue(first.equals(second)); assertEquals(mockId.toString(), first.getSchemaId()); @@ -137,9 +137,9 @@ public void testClientReset() throws Exception { assertEquals( MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); - client.reset(); + client.clearCache(); assertEquals(0, guidCache.size()); assertEquals(0, schemaStringCache.size()); @@ -149,7 +149,7 @@ public void testClientReset() throws Exception { assertEquals( MOCK_ID, - client.register(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); verify(restService, times(2)) .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION, MOCK_AVRO_SCHEMA); @@ -168,7 +168,7 @@ public void testBadRegisterRequestThenThrows() { null, null))); try { - client.register( + client.registerSchema( "doesn't matter", "doesn't matter", "doesn't matter", @@ -223,7 +223,7 @@ public void testGetSchemaByIdNotFoundThenThrows() { null))); try { - client.getSchemaById(mockId).block(); + client.getSchema(mockId).block(); fail("Should have thrown on 404 status code"); } catch (SchemaRegistryClientException e) { assert true; From a5229d5e4f3759fad8412bf8ef878ecae583b3e7 Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Fri, 31 Jul 2020 03:24:34 -0700 Subject: [PATCH 04/17] Schema registry api view updates (#13678) * Update schema registry client APIs * Update package structure for schema registry * Update model classes * Add clear cache method to sync client --- .../checkstyle/checkstyle-suppressions.xml | 2 +- .../data/schemaregistry/avro/AvroCodec.java | 13 +++++++---- .../SchemaRegistryAvroAsyncSerializer.java | 4 ++-- .../avro/SchemaRegistryAvroSerializer.java | 2 +- .../SchemaRegistryAvroSerializerBuilder.java | 4 ++-- .../CachedSchemaRegistryAsyncClient.java | 23 ++++++++++++++++--- .../CachedSchemaRegistryClient.java | 17 ++++++++++++-- .../CachedSchemaRegistryClientBuilder.java | 7 +++--- .../com/azure/data/schemaregistry/Codec.java | 8 ++++--- .../SchemaRegistrySerializer.java | 16 ++++++------- .../schemaregistry/client/package-info.java | 7 ------ .../AzureSchemaRegistryRestService.java | 22 +++++++++--------- ...chemaRegistryRestServiceClientBuilder.java | 2 +- .../models/CreateGroupHeaders.java | 2 +- .../models/CreateGroupResponse.java | 2 +- .../models/CreateSchemaHeaders.java | 2 +- .../models/CreateSchemaResponse.java | 2 +- .../models/GetIdBySchemaContentHeaders.java | 2 +- .../models/GetIdBySchemaContentResponse.java | 2 +- .../models/GetLatestSchemaHeaders.java | 2 +- .../models/GetLatestSchemaResponse.java | 2 +- .../models/GetSchemaByIdHeaders.java | 2 +- .../models/GetSchemaByIdResponse.java | 2 +- .../models/GetSchemaVersionHeaders.java | 2 +- .../models/GetSchemaVersionResponse.java | 2 +- .../models/GetSchemaVersionsHeaders.java | 2 +- .../models/GetSchemaVersionsResponse.java | 2 +- .../models/GetSchemasByGroupHeaders.java | 2 +- .../models/GetSchemasByGroupResponse.java | 2 +- .../implementation/models/SchemaGroup.java | 2 +- .../implementation/models/SchemaId.java | 2 +- .../implementation/models/package-info.java | 2 +- .../implementation/package-info.java | 2 +- .../SchemaRegistryClientException.java | 6 ++--- .../SchemaRegistryObject.java | 22 +++++++++++++++--- .../{ => models}/SerializationException.java | 2 +- .../schemaregistry/models/package-info.java | 7 ++++++ .../data/schemaregistry/package-info.java | 3 +++ .../src/main/module-info.java | 2 +- .../CachedSchemaRegistryAsyncClientTest.java | 14 +++++++---- .../data/schemaregistry/SampleCodec.java | 12 +++++++--- .../SchemaRegistrySerializerTest.java | 16 ++++++++----- .../schemaregistry/TestDummySerializer.java | 2 -- 43 files changed, 161 insertions(+), 92 deletions(-) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/CachedSchemaRegistryAsyncClient.java (93%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/CachedSchemaRegistryClient.java (75%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/CachedSchemaRegistryClientBuilder.java (97%) delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/package-info.java rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/AzureSchemaRegistryRestService.java (98%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/AzureSchemaRegistryRestServiceClientBuilder.java (97%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/CreateGroupHeaders.java (93%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/CreateGroupResponse.java (93%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/CreateSchemaHeaders.java (98%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/CreateSchemaResponse.java (94%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetIdBySchemaContentHeaders.java (98%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetIdBySchemaContentResponse.java (94%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetLatestSchemaHeaders.java (98%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetLatestSchemaResponse.java (94%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetSchemaByIdHeaders.java (98%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetSchemaByIdResponse.java (94%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetSchemaVersionHeaders.java (98%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetSchemaVersionResponse.java (94%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetSchemaVersionsHeaders.java (94%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetSchemaVersionsResponse.java (94%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetSchemasByGroupHeaders.java (94%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/GetSchemasByGroupResponse.java (94%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/SchemaGroup.java (98%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/SchemaId.java (93%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/models/package-info.java (55%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => }/implementation/package-info.java (56%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => models}/SchemaRegistryClientException.java (77%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{client => models}/SchemaRegistryObject.java (79%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{ => models}/SerializationException.java (94%) create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/package-info.java rename sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/{client => }/CachedSchemaRegistryAsyncClientTest.java (92%) 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 c2c99513d90a0..b572d64f95b8c 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 @@ -408,7 +408,7 @@ - + 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 index ae022820c5870..7ef823a93061e 100644 --- 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 @@ -5,7 +5,7 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.data.schemaregistry.Codec; -import com.azure.data.schemaregistry.SerializationException; +import com.azure.data.schemaregistry.models.SerializationException; import org.apache.avro.Schema; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericDatumWriter; @@ -79,6 +79,11 @@ public String getSchemaName(Object object) { return AvroSchemaUtils.getSchema(object).getFullName(); } + @Override + public String getSchemaGroup() { + return "$Default"; + } + /** * Returns ByteArrayOutputStream containing Avro encoding of object parameter * @param object Object to be encoded into byte stream @@ -86,7 +91,7 @@ public String getSchemaName(Object object) { * @throws SerializationException wraps runtime exceptions */ @Override - public ByteArrayOutputStream encode(Object object) { + public byte[] encode(Object object) { Schema schema = AvroSchemaUtils.getSchema(object); try { @@ -104,7 +109,7 @@ public ByteArrayOutputStream encode(Object object) { writer.write(object, encoder); encoder.flush(); } - return out; + return out.toByteArray(); } catch (IOException | RuntimeException e) { // Avro serialization can throw AvroRuntimeException, NullPointerException, ClassCastException, etc throw logger.logExceptionAsError( @@ -119,7 +124,7 @@ public ByteArrayOutputStream encode(Object object) { * @return deserialized object * @throws SerializationException upon deserialization failure */ - public Object decodeBytes(byte[] b, Object object) { + public Object decode(byte[] b, Object object) { Objects.requireNonNull(object, "Schema must not be null."); if (!(object instanceof Schema)) { 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 index a875e7a9161c5..ad2356ed07a1a 100644 --- 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 @@ -6,8 +6,8 @@ import com.azure.core.experimental.serializer.ObjectSerializer; import com.azure.core.util.logging.ClientLogger; import com.azure.data.schemaregistry.SchemaRegistrySerializer; -import com.azure.data.schemaregistry.SerializationException; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; +import com.azure.data.schemaregistry.models.SerializationException; +import com.azure.data.schemaregistry.CachedSchemaRegistryAsyncClient; import reactor.core.publisher.Mono; import java.io.InputStream; import java.io.OutputStream; 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 fbc89c7134e83..595833250d9c9 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 @@ -4,7 +4,7 @@ package com.azure.data.schemaregistry.avro; import com.azure.data.schemaregistry.SchemaRegistrySerializer; -import com.azure.data.schemaregistry.SerializationException; +import com.azure.data.schemaregistry.models.SerializationException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; 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 5c6c2da73a656..ab9ded5e224d9 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 @@ -4,8 +4,8 @@ package com.azure.data.schemaregistry.avro; import com.azure.core.credential.TokenCredential; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryClientBuilder; +import com.azure.data.schemaregistry.CachedSchemaRegistryAsyncClient; +import com.azure.data.schemaregistry.CachedSchemaRegistryClientBuilder; import java.util.Objects; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClient.java similarity index 93% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClient.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClient.java index df86089a74d37..94e9b1f95aaf3 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClient.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClient.java @@ -1,16 +1,20 @@ // 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.ReturnType; import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; import com.azure.core.exception.HttpResponseException; 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.client.implementation.AzureSchemaRegistryRestService; -import com.azure.data.schemaregistry.client.implementation.models.SchemaId; +import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestService; +import com.azure.data.schemaregistry.implementation.models.SchemaId; +import com.azure.data.schemaregistry.models.SchemaRegistryClientException; +import com.azure.data.schemaregistry.models.SchemaRegistryObject; import reactor.core.publisher.Mono; import java.nio.charset.Charset; @@ -78,8 +82,10 @@ public final class CachedSchemaRegistryAsyncClient { this.maxSchemaMapSize = MAX_SCHEMA_MAP_SIZE_DEFAULT; } + @ServiceMethod(returns = ReturnType.SINGLE) public Mono registerSchema( String schemaGroup, String schemaName, String schemaString, String schemaType) { + if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { logger.verbose( "Cache hit schema string. Group: '{}', name: '{}', schema type: '{}', payload: '{}'", @@ -92,6 +98,7 @@ public Mono registerSchema( .map(response -> response.getValue()); } + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> registerSchemaWithResponse(String schemaGroup, String schemaName, String schemaString, String schemaType) { return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE); @@ -123,6 +130,8 @@ Mono> registerSchemaWithResponse(String schemaGro SchemaRegistryObject registered = new SchemaRegistryObject(schemaId.getId(), schemaType, + schemaName, + schemaGroup, schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), getParseFunc(schemaType)); @@ -137,6 +146,7 @@ Mono> registerSchemaWithResponse(String schemaGro }); } + @ServiceMethod(returns = ReturnType.SINGLE) public Mono getSchema(String schemaId) { if (idCache.containsKey(schemaId)) { logger.verbose("Cache hit for schema id '{}'", schemaId); @@ -145,6 +155,7 @@ public Mono getSchema(String schemaId) { return getSchemaWithResponse(schemaId).map(Response::getValue); } + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getSchemaWithResponse(String schemaId) { return getSchemaWithResponse(schemaId, Context.NONE); } @@ -172,6 +183,8 @@ Mono> getSchemaWithResponse(String schemaId, Cont SchemaRegistryObject schemaObject = new SchemaRegistryObject(schemaId, schemaType, + null, + null, response.getValue().getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), getParseFunc(schemaType)); @@ -186,6 +199,7 @@ Mono> getSchemaWithResponse(String schemaId, Cont } + @ServiceMethod(returns = ReturnType.SINGLE) public Mono getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) { if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { @@ -197,6 +211,7 @@ public Mono getSchemaId(String schemaGroup, String schemaName, String sc .map(response -> response.getValue()); } + @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, String schemaType) { return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE); @@ -231,6 +246,8 @@ Mono> getSchemaIdWithResponse(String schemaGroup, String schema new SchemaRegistryObject( schemaId.getId(), schemaType, + schemaName, + schemaGroup, schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), getParseFunc(schemaType))); logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); 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/CachedSchemaRegistryClient.java similarity index 75% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryClient.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClient.java index 3e4a3aa111ffa..c0c3a5c2f5f12 100644 --- 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/CachedSchemaRegistryClient.java @@ -1,9 +1,12 @@ -package com.azure.data.schemaregistry.client; +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.client.implementation.AzureSchemaRegistryRestService; +import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestService; +import com.azure.data.schemaregistry.models.SchemaRegistryObject; @ServiceClient( builder = CachedSchemaRegistryClientBuilder.class, @@ -15,33 +18,43 @@ public final class CachedSchemaRegistryClient { this.asyncClient = asyncClient; } + @ServiceMethod(returns = ReturnType.SINGLE) public SchemaRegistryObject registerSchema(String schemaGroup, String schemaName, String schemaString, String schemaType) { return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE).getValue(); } + @ServiceMethod(returns = ReturnType.SINGLE) public Response registerSchemaWithResponse(String schemaGroup, String schemaName, String schemaString, String schemaType, Context context) { return this.asyncClient.registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType, context).block(); } + @ServiceMethod(returns = ReturnType.SINGLE) public SchemaRegistryObject getSchema(String schemaId) { return getSchemaWithResponse(schemaId, Context.NONE).getValue(); } + @ServiceMethod(returns = ReturnType.SINGLE) public Response getSchemaWithResponse(String schemaId, Context context) { return this.asyncClient.getSchemaWithResponse(schemaId).block(); } + @ServiceMethod(returns = ReturnType.SINGLE) public String getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) { return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE).getValue(); } + @ServiceMethod(returns = ReturnType.SINGLE) public Response getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, String schemaType, Context context) { return this.asyncClient.getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType, context) .block(); } + public 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/CachedSchemaRegistryClientBuilder.java similarity index 97% 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/CachedSchemaRegistryClientBuilder.java index 36cec8ce65d15..e4b14e27595d4 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/CachedSchemaRegistryClientBuilder.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,9 +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.AzureSchemaRegistryRestService; +import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestServiceClientBuilder; import java.net.MalformedURLException; import java.net.URL; import java.time.temporal.ChronoUnit; 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 index ca4ff37afedf1..8703c9e0b15f8 100644 --- 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 @@ -3,7 +3,7 @@ package com.azure.data.schemaregistry; -import java.io.ByteArrayOutputStream; +import com.azure.data.schemaregistry.models.SerializationException; /** * An interface defining operations required for registry-based serialization and deserialization. @@ -34,6 +34,8 @@ public interface Codec { */ String getSchemaName(Object object); + String getSchemaGroup(); + /** * Returns string representation of schema object to be stored in the service. * @@ -49,7 +51,7 @@ public interface Codec { * @return output stream containing byte representation of object * @throws SerializationException if generating byte representation of object fails */ - ByteArrayOutputStream encode(Object object); + byte[] encode(Object object); /** * Decodes byte array into Object given provided schema object. @@ -58,5 +60,5 @@ public interface Codec { * @return deserialized object * @throws SerializationException if decode operation fails */ - Object decodeBytes(byte[] encodedBytes, Object schemaObject); + Object decode(byte[] encodedBytes, Object schemaObject); } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java index f6740ab5a0899..0297623541164 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java @@ -5,9 +5,9 @@ import com.azure.core.exception.HttpResponseException; import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; -import com.azure.data.schemaregistry.client.SchemaRegistryClientException; -import com.azure.data.schemaregistry.client.SchemaRegistryObject; +import com.azure.data.schemaregistry.models.SchemaRegistryClientException; +import com.azure.data.schemaregistry.models.SchemaRegistryObject; +import com.azure.data.schemaregistry.models.SerializationException; import reactor.core.publisher.Mono; import java.io.IOException; @@ -55,7 +55,7 @@ public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryCl this(schemaRegistryClient, serializerCodec, deserializerCodecList, null, null); } - public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, + public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, Codec serializerCodec, List deserializerCodecList, Boolean autoRegisterSchemas, String schemaGroup) { @@ -153,7 +153,7 @@ protected Mono serialize(T s, Object object) { .put(id.getBytes(StandardCharsets.UTF_8)); try { s.write(idBuffer.array()); - serializerCodec.encode(object).writeTo(s); + s.write(serializerCodec.encode(object)); } catch (IOException e) { sink.error(new SerializationException(e.getMessage(), e)); } @@ -170,7 +170,7 @@ protected Mono serialize(T s, Object object) { * @return object, deserialized with the prefixed schema * @throws SerializationException if deserialization of registry schema or message payload fails. */ - protected Mono deserialize(InputStream s) throws SerializationException { + protected Mono deserialize(InputStream s) { if (s == null) { return Mono.empty(); } @@ -195,7 +195,7 @@ protected Mono deserialize(InputStream s) throws SerializationException .onErrorMap(IOException.class, e -> logger.logExceptionAsError(new SerializationException(e.getMessage(), e))) .handle((registryObject, sink) -> { - Object payloadSchema = registryObject.deserialize(); + Object payloadSchema = registryObject.getSchema(); if (payloadSchema == null) { sink.error(logger.logExceptionAsError( @@ -210,7 +210,7 @@ protected Mono deserialize(InputStream s) throws SerializationException byte[] b = Arrays.copyOfRange(buffer.array(), start, start + length); Codec codec = getDeserializerCodec(registryObject); - sink.next(codec.decodeBytes(b, payloadSchema)); + sink.next(codec.decode(b, payloadSchema)); }) .onErrorMap(e -> { if (e instanceof SchemaRegistryClientException) { 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 037a0fecb1582..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 - * - CachedSchemaRegistryClient - * - CachedSchemaRegistryAsyncClient - * - AzureSchemaRegistryRestService. - */ -package com.azure.data.schemaregistry.client; 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/implementation/AzureSchemaRegistryRestService.java similarity index 98% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/AzureSchemaRegistryRestService.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistryRestService.java index f44e765505afe..3c8be332324b4 100644 --- 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/implementation/AzureSchemaRegistryRestService.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client.implementation; +package com.azure.data.schemaregistry.implementation; import com.azure.core.annotation.BodyParam; import com.azure.core.annotation.Delete; @@ -27,16 +27,16 @@ 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 com.azure.data.schemaregistry.implementation.models.CreateGroupResponse; +import com.azure.data.schemaregistry.implementation.models.CreateSchemaResponse; +import com.azure.data.schemaregistry.implementation.models.GetIdBySchemaContentResponse; +import com.azure.data.schemaregistry.implementation.models.GetLatestSchemaResponse; +import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdResponse; +import com.azure.data.schemaregistry.implementation.models.GetSchemaVersionResponse; +import com.azure.data.schemaregistry.implementation.models.GetSchemaVersionsResponse; +import com.azure.data.schemaregistry.implementation.models.GetSchemasByGroupResponse; +import com.azure.data.schemaregistry.implementation.models.SchemaGroup; +import com.azure.data.schemaregistry.implementation.models.SchemaId; import java.util.List; import reactor.core.publisher.Mono; 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/implementation/AzureSchemaRegistryRestServiceClientBuilder.java similarity index 97% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/AzureSchemaRegistryRestServiceClientBuilder.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistryRestServiceClientBuilder.java index 4dbf94d09ca5d..4aea3ea89ef52 100644 --- 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/implementation/AzureSchemaRegistryRestServiceClientBuilder.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client.implementation; +package com.azure.data.schemaregistry.implementation; import com.azure.core.annotation.ServiceClientBuilder; import com.azure.core.http.HttpPipeline; 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/implementation/models/CreateGroupHeaders.java similarity index 93% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateGroupHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateGroupHeaders.java index ba373f71b19d1..c3db80e8040cd 100644 --- 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/implementation/models/CreateGroupHeaders.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; 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/implementation/models/CreateGroupResponse.java similarity index 93% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateGroupResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateGroupResponse.java index 7f6b958bbd68a..bc20e0ac954e1 100644 --- 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/implementation/models/CreateGroupResponse.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.http.HttpHeaders; import com.azure.core.http.HttpRequest; 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/CreateSchemaHeaders.java similarity index 98% 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/CreateSchemaHeaders.java index fcdac46e5b9f0..d2f470271d9c1 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/CreateSchemaHeaders.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; 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/implementation/models/CreateSchemaResponse.java similarity index 94% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/CreateSchemaResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateSchemaResponse.java index 5612686cb87f8..cd37671a2514f 100644 --- 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/implementation/models/CreateSchemaResponse.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.http.HttpHeaders; import com.azure.core.http.HttpRequest; 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/implementation/models/GetIdBySchemaContentHeaders.java similarity index 98% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetIdBySchemaContentHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetIdBySchemaContentHeaders.java index 45e63cd1e4a11..b825d8118cd7f 100644 --- 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/implementation/models/GetIdBySchemaContentHeaders.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; 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/GetIdBySchemaContentResponse.java similarity index 94% 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/GetIdBySchemaContentResponse.java index 4061fd93f9370..cf780ffaad79a 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/GetIdBySchemaContentResponse.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.http.HttpHeaders; import com.azure.core.http.HttpRequest; 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/GetLatestSchemaHeaders.java similarity index 98% 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/GetLatestSchemaHeaders.java index 6fc62f9ad8093..646bffe9411d7 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/GetLatestSchemaHeaders.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; 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/implementation/models/GetLatestSchemaResponse.java similarity index 94% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetLatestSchemaResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetLatestSchemaResponse.java index b1aec099e8682..2e4e65822c924 100644 --- 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/implementation/models/GetLatestSchemaResponse.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.http.HttpHeaders; import com.azure.core.http.HttpRequest; 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/GetSchemaByIdHeaders.java similarity index 98% 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/GetSchemaByIdHeaders.java index cb6e7f5df9478..d31de2971a2ee 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/GetSchemaByIdHeaders.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; 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/GetSchemaByIdResponse.java similarity index 94% 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/GetSchemaByIdResponse.java index 9f5f8392a987c..5a0c67a8c9926 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/GetSchemaByIdResponse.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.http.HttpHeaders; import com.azure.core.http.HttpRequest; 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/implementation/models/GetSchemaVersionHeaders.java similarity index 98% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionHeaders.java index 6210361d7a1cc..014da2ac0bd08 100644 --- 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/implementation/models/GetSchemaVersionHeaders.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; 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/GetSchemaVersionResponse.java similarity index 94% 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/GetSchemaVersionResponse.java index 4b4f3bfbc24c1..fe2d718d28dd9 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/GetSchemaVersionResponse.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.http.HttpHeaders; import com.azure.core.http.HttpRequest; 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/implementation/models/GetSchemaVersionsHeaders.java similarity index 94% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionsHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionsHeaders.java index db011b690a669..4902359c6f4b8 100644 --- 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/implementation/models/GetSchemaVersionsHeaders.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; 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/implementation/models/GetSchemaVersionsResponse.java similarity index 94% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemaVersionsResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionsResponse.java index 67afbfed471b0..4da3f44617cd0 100644 --- 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/implementation/models/GetSchemaVersionsResponse.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.http.HttpHeaders; import com.azure.core.http.HttpRequest; 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/implementation/models/GetSchemasByGroupHeaders.java similarity index 94% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemasByGroupHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemasByGroupHeaders.java index a8162e0af75ac..7597a0a0a03c6 100644 --- 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/implementation/models/GetSchemasByGroupHeaders.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; 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/implementation/models/GetSchemasByGroupResponse.java similarity index 94% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/GetSchemasByGroupResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemasByGroupResponse.java index 796219fe422d2..0c29e36fc7580 100644 --- 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/implementation/models/GetSchemasByGroupResponse.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.http.HttpHeaders; import com.azure.core.http.HttpRequest; 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/implementation/models/SchemaGroup.java similarity index 98% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/SchemaGroup.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemaGroup.java index 98d2e8e3ca719..fc416152e6297 100644 --- 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/implementation/models/SchemaGroup.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; 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 93% 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..80e6b35775ff6 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; 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/implementation/models/package-info.java similarity index 55% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/models/package-info.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/package-info.java index cdb3fcbbeaf8d..bdeef3522a149 100644 --- 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/implementation/models/package-info.java @@ -1,2 +1,2 @@ /** Package containing the data models for AzureSchemaRegistryRestService. null. */ -package com.azure.data.schemaregistry.client.implementation.models; +package com.azure.data.schemaregistry.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/implementation/package-info.java similarity index 56% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/implementation/package-info.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/package-info.java index b9afd3e65bc9c..6f1ee3cf00e96 100644 --- 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/implementation/package-info.java @@ -1,2 +1,2 @@ /** Package containing the classes for AzureSchemaRegistryRestService. null. */ -package com.azure.data.schemaregistry.client.implementation; +package com.azure.data.schemaregistry.implementation; 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/models/SchemaRegistryClientException.java similarity index 77% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryClientException.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryClientException.java index 92e302e422d53..474c0f059996b 100644 --- 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/models/SchemaRegistryClientException.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.models; import com.azure.core.exception.AzureException; @@ -12,7 +12,7 @@ public class SchemaRegistryClientException extends AzureException { /** * @param s error message returned from schema registry client */ - SchemaRegistryClientException(String s) { + public SchemaRegistryClientException(String s) { super(s); } @@ -20,7 +20,7 @@ public class SchemaRegistryClientException extends AzureException { * @param s error message returned from schema registry client * @param cause Throwable cause of the exception */ - SchemaRegistryClientException(String s, Throwable cause) { + public 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/models/SchemaRegistryObject.java similarity index 79% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/client/SchemaRegistryObject.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryObject.java index e152c13f1819c..97eeb5df19064 100644 --- 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/models/SchemaRegistryObject.java @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry.client; +package com.azure.data.schemaregistry.models; import com.azure.core.util.logging.ClientLogger; +import com.azure.data.schemaregistry.CachedSchemaRegistryAsyncClient; +import java.nio.charset.StandardCharsets; import java.util.function.Function; /** @@ -16,6 +18,8 @@ public class SchemaRegistryObject { private final String schemaType; private final Function parseMethod; private final byte[] schemaBytes; + private final String schemaName; + private final String schemaGroup; private Object deserialized; @@ -30,6 +34,8 @@ public class SchemaRegistryObject { public SchemaRegistryObject( String schemaId, String schemaType, + String schemaName, + String schemaGroup, byte[] schemaByteArray, Function parseMethod) { this.schemaId = schemaId; @@ -37,6 +43,8 @@ public SchemaRegistryObject( this.schemaBytes = schemaByteArray.clone(); this.deserialized = null; this.parseMethod = parseMethod; + this.schemaGroup = schemaGroup; + this.schemaName = schemaName; } /** @@ -53,16 +61,24 @@ public String getSchemaType() { return schemaType; } + public String getSchemaGroup() { + return null; + } + + public String getSchemaName() { + return null; + } + /** * 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() { + public Object getSchema() { if (this.deserialized == null) { String schemaString = new String( - this.schemaBytes, CachedSchemaRegistryAsyncClient.SCHEMA_REGISTRY_SERVICE_ENCODING); + this.schemaBytes, StandardCharsets.UTF_8); logger.verbose("Deserializing schema, id: '{}', schema string '{}'", this.schemaId, schemaString); 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/models/SerializationException.java similarity index 94% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SerializationException.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SerializationException.java index b526a8843721b..52f0aa20284d9 100644 --- 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/models/SerializationException.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.data.schemaregistry; +package com.azure.data.schemaregistry.models; import com.azure.core.exception.AzureException; 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..f0a21847c2ffd 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,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + /** * Package containing core serialization and deserialization implementations for Azure Schema Registry SDK. */ 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/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClientTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClientTest.java similarity index 92% rename from sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClientTest.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClientTest.java index e89cdee323665..c7e31a1f5ca21 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/client/CachedSchemaRegistryAsyncClientTest.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClientTest.java @@ -1,10 +1,16 @@ // 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.*; +package com.azure.data.schemaregistry; + +import com.azure.data.schemaregistry.implementation.models.CreateSchemaResponse; +import com.azure.data.schemaregistry.implementation.models.GetIdBySchemaContentResponse; +import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdHeaders; +import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdResponse; +import com.azure.data.schemaregistry.implementation.models.SchemaId; +import com.azure.data.schemaregistry.models.SchemaRegistryClientException; +import com.azure.data.schemaregistry.models.SchemaRegistryObject; +import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java index 41882d67b189c..529c0db93694c 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java @@ -3,6 +3,7 @@ package com.azure.data.schemaregistry; +import com.azure.data.schemaregistry.models.SerializationException; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -15,13 +16,18 @@ public String getSchemaName(Object object) throws SerializationException { return "schema name"; } + @Override + public String getSchemaGroup() { + return "schema group"; + } + @Override public String getSchemaString(Object object) { return "string representation of schema"; } @Override - public ByteArrayOutputStream encode(Object object) throws SerializationException { + public byte[] encode(Object object) throws SerializationException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { outputStream.write("sample payload".getBytes()); @@ -31,7 +37,7 @@ public ByteArrayOutputStream encode(Object object) throws SerializationException e.printStackTrace(); throw new SerializationException("this should never happen", e); } - return outputStream; + return outputStream.toByteArray(); } @Override @@ -47,7 +53,7 @@ public String parseSchemaString(String s) { public static final String CONSTANT_PAYLOAD = "sample payload!"; @Override - public Object decodeBytes(byte[] bytes, Object o) throws SerializationException { + public Object decode(byte[] bytes, Object o) throws SerializationException { return CONSTANT_PAYLOAD; } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java index 101f9ce39cdbb..69120ae5e4dbc 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java @@ -3,9 +3,9 @@ package com.azure.data.schemaregistry; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; -import com.azure.data.schemaregistry.client.SchemaRegistryClientException; -import com.azure.data.schemaregistry.client.SchemaRegistryObject; +import com.azure.data.schemaregistry.models.SchemaRegistryClientException; +import com.azure.data.schemaregistry.models.SchemaRegistryObject; +import com.azure.data.schemaregistry.models.SerializationException; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericDatumWriter; @@ -40,10 +40,12 @@ public void testRegistryGuidPrefixedToPayload() { SampleCodec encoder = new SampleCodec(); SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, encoder.getSchemaType(), + encoder.getSchemaName(null), + encoder.getSchemaGroup(), encoder.getSchemaString(null).getBytes(), // always returns same schema string encoder::parseSchemaString); - assertEquals(encoder.getSchemaString(null), registered.deserialize()); + assertEquals(encoder.getSchemaString(null), registered.getSchema()); CachedSchemaRegistryAsyncClient mockRegistryClient = getMockClient(); Mockito.when(mockRegistryClient.getSchemaId(anyString(), anyString(), anyString(), anyString())) @@ -68,7 +70,7 @@ public void testRegistryGuidPrefixedToPayload() { int start = buffer.position() + buffer.arrayOffset(); int length = buffer.limit() - SchemaRegistrySerializer.SCHEMA_ID_SIZE; byte[] encodedBytes = Arrays.copyOfRange(buffer.array(), start, start + length); - assertTrue(Arrays.equals(encoder.encode(null).toByteArray(), encodedBytes)); + assertTrue(Arrays.equals(encoder.encode(null), encodedBytes)); } catch (SerializationException e) { e.printStackTrace(); fail(); @@ -111,10 +113,12 @@ public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientE // manually add SchemaRegistryObject to cache SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, decoder.getSchemaType(), + decoder.getSchemaName(null), + decoder.getSchemaGroup(), MOCK_AVRO_SCHEMA_STRING.getBytes(), decoder::parseSchemaString); - assertTrue(registered.deserialize() != null); + assertTrue(registered.getSchema() != null); CachedSchemaRegistryAsyncClient mockClient = getMockClient(); Mockito.when(mockClient.getSchema(anyString())) 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 index 833dd1654bf1d..e585b5d8ae499 100644 --- 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 @@ -3,8 +3,6 @@ package com.azure.data.schemaregistry; -import com.azure.data.schemaregistry.client.CachedSchemaRegistryAsyncClient; - import java.util.Collections; public class TestDummySerializer extends SchemaRegistrySerializer { From d63c875aa4db0bb688dfd2f354eec631c0a0d9fd Mon Sep 17 00:00:00 2001 From: Srikanta Date: Fri, 31 Jul 2020 15:59:56 -0700 Subject: [PATCH 05/17] Rename Codec to SchemaRegistryCodec --- ...odec.java => AvroSchemaRegistryCodec.java} | 8 ++-- .../SchemaRegistryAvroAsyncSerializer.java | 2 +- .../SchemaRegistryAvroSerializerBuilder.java | 2 +- .../CachedSchemaRegistryClientBuilder.java | 12 ++--- .../{Codec.java => SchemaRegistryCodec.java} | 2 +- .../SchemaRegistrySerializer.java | 46 +++++++++---------- ...ec.java => SampleSchemaRegistryCodec.java} | 4 +- .../SchemaRegistrySerializerTest.java | 6 +-- .../schemaregistry/TestDummySerializer.java | 2 +- 9 files changed, 42 insertions(+), 42 deletions(-) rename sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/{AvroCodec.java => AvroSchemaRegistryCodec.java} (95%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{Codec.java => SchemaRegistryCodec.java} (98%) rename sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/{SampleCodec.java => SampleSchemaRegistryCodec.java} (92%) 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/AvroSchemaRegistryCodec.java similarity index 95% rename from sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroCodec.java rename to sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java index 7ef823a93061e..8b5e9a00077b1 100644 --- 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/AvroSchemaRegistryCodec.java @@ -4,7 +4,7 @@ package com.azure.data.schemaregistry.avro; import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.Codec; +import com.azure.data.schemaregistry.SchemaRegistryCodec; import com.azure.data.schemaregistry.models.SerializationException; import org.apache.avro.Schema; import org.apache.avro.generic.GenericDatumReader; @@ -21,7 +21,7 @@ /** * Base Codec class for Avro encoder and decoder implementations */ -public class AvroCodec implements Codec { +public class AvroSchemaRegistryCodec implements SchemaRegistryCodec { private final ClientLogger logger = new ClientLogger(AvroCodec.class); private static final EncoderFactory ENCODER_FACTORY = EncoderFactory.get(); private static final DecoderFactory DECODER_FACTORY = DecoderFactory.get(); @@ -33,9 +33,9 @@ public class AvroCodec implements Codec { * Instantiates AvroCodec instance * @param avroSpecificReader flag indicating if decoder should decode records as SpecificRecords */ - public AvroCodec(Boolean avroSpecificReader) { + public AvroSchemaRegistryCodec(Boolean avroSpecificReader) { if (avroSpecificReader == null) { - this.avroSpecificReader = AvroCodec.AVRO_SPECIFIC_READER_DEFAULT; + this.avroSpecificReader = AvroSchemaRegistryCodec.AVRO_SPECIFIC_READER_DEFAULT; } else { this.avroSpecificReader = avroSpecificReader; 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 index ad2356ed07a1a..f6118e8c5d4bd 100644 --- 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 @@ -26,7 +26,7 @@ public class SchemaRegistryAvroAsyncSerializer extends SchemaRegistrySerializer * @param schemaGroup * @param autoRegisterSchemas */ - SchemaRegistryAvroAsyncSerializer(CachedSchemaRegistryAsyncClient registryClient, AvroCodec codec, + SchemaRegistryAvroAsyncSerializer(CachedSchemaRegistryAsyncClient registryClient, AvroSchemaRegistryCodec codec, String schemaGroup, Boolean autoRegisterSchemas) { super(registryClient, codec, Collections.singletonList(codec), autoRegisterSchemas, schemaGroup); } 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 ab9ded5e224d9..d13ab42207f94 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 @@ -136,7 +136,7 @@ public SchemaRegistryAvroAsyncSerializer buildAsyncSerializer() { builder.maxCacheSize(maxCacheSize); } - AvroCodec codec = new AvroCodec(this.avroSpecificReader); + AvroSchemaRegistryCodec codec = new AvroSchemaRegistryCodec(this.avroSpecificReader); CachedSchemaRegistryAsyncClient client = builder .addCodec(codec) diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java index e4b14e27595d4..b962ec53f8f98 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java @@ -218,20 +218,20 @@ public CachedSchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) { * * The parseMethod argument should be a stateless, idempotent function. * - * @param codec Codec class implementation + * @param schemaRegistryCodec Codec class implementation * @return The updated {@link CachedSchemaRegistryClientBuilder} object. */ - public CachedSchemaRegistryClientBuilder addCodec(Codec codec) { - Objects.requireNonNull(codec, "'codec' cannot be null."); - if (CoreUtils.isNullOrEmpty(codec.getSchemaType())) { + public CachedSchemaRegistryClientBuilder addCodec(SchemaRegistryCodec schemaRegistryCodec) { + Objects.requireNonNull(schemaRegistryCodec, "'codec' cannot be null."); + if (CoreUtils.isNullOrEmpty(schemaRegistryCodec.getSchemaType())) { throw logger.logExceptionAsError( new IllegalArgumentException("Serialization type cannot be null or empty.")); } - if (this.typeParserMap.containsKey(codec.getSchemaType())) { + if (this.typeParserMap.containsKey(schemaRegistryCodec.getSchemaType())) { throw logger.logExceptionAsError( new IllegalArgumentException("Multiple parse methods for single serialization type may not be added.")); } - this.typeParserMap.put(codec.getSchemaType(), codec::parseSchemaString); + this.typeParserMap.put(schemaRegistryCodec.getSchemaType(), schemaRegistryCodec::parseSchemaString); return this; } 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/SchemaRegistryCodec.java similarity index 98% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/Codec.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryCodec.java index 8703c9e0b15f8..ee4097bc20a3a 100644 --- 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/SchemaRegistryCodec.java @@ -8,7 +8,7 @@ /** * An interface defining operations required for registry-based serialization and deserialization. */ -public interface Codec { +public interface SchemaRegistryCodec { /** * @return String representation of schema type, e.g. "avro" or "json". * diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java index 0297623541164..955ba5f69bdf2 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java @@ -36,8 +36,8 @@ public abstract class SchemaRegistrySerializer { CachedSchemaRegistryAsyncClient schemaRegistryClient; - private Codec serializerCodec; - private final Map deserializerCodecMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); + private SchemaRegistryCodec serializerSchemaRegistryCodec; + private final Map deserializerCodecMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); private String schemaType; Boolean autoRegisterSchemas = SchemaRegistrySerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; @@ -47,34 +47,34 @@ public abstract class SchemaRegistrySerializer { * Constructor for AbstractSchemaRegistrySerializer implementations. * * @param schemaRegistryClient client to be used for interfacing with Schema Registry service - * @param serializerCodec Codec to be used for serialization operations - * @param deserializerCodecList list of Codecs to be used to deserialize incoming payloads + * @param serializerSchemaRegistryCodec Codec to be used for serialization operations + * @param deserializerSchemaRegistryCodecList list of Codecs to be used to deserialize incoming payloads */ public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, - Codec serializerCodec, List deserializerCodecList) { - this(schemaRegistryClient, serializerCodec, deserializerCodecList, null, null); + SchemaRegistryCodec serializerSchemaRegistryCodec, List deserializerSchemaRegistryCodecList) { + this(schemaRegistryClient, serializerSchemaRegistryCodec, deserializerSchemaRegistryCodecList, null, null); } public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, - Codec serializerCodec, List deserializerCodecList, Boolean autoRegisterSchemas, + SchemaRegistryCodec serializerSchemaRegistryCodec, List deserializerSchemaRegistryCodecList, Boolean autoRegisterSchemas, String schemaGroup) { - Objects.requireNonNull(serializerCodec); - Objects.requireNonNull(deserializerCodecList); + Objects.requireNonNull(serializerSchemaRegistryCodec); + Objects.requireNonNull(deserializerSchemaRegistryCodecList); if (schemaRegistryClient == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Schema registry client must be initialized and passed into builder.")); } - if (deserializerCodecList.size() == 0) { + if (deserializerSchemaRegistryCodecList.size() == 0) { throw logger.logExceptionAsError( new IllegalArgumentException("At least one Codec must be provided for deserialization.")); } this.schemaRegistryClient = schemaRegistryClient; - this.serializerCodec = serializerCodec; - for (Codec c : deserializerCodecList) { + this.serializerSchemaRegistryCodec = serializerSchemaRegistryCodec; + for (SchemaRegistryCodec c : deserializerSchemaRegistryCodecList) { if (this.deserializerCodecMap.containsKey(c.getSchemaType())) { throw logger.logExceptionAsError( new IllegalArgumentException("Only on Codec can be provided per schema serialization type.")); @@ -109,17 +109,17 @@ protected Mono serialize(T s, Object object) { "Null object, behavior should be defined in concrete serializer implementation.")); } - if (serializerCodec == null) { + if (serializerSchemaRegistryCodec == null) { return monoError(logger, new SerializationException( "Byte encoder null, serializer must be initialized with a byte encoder.")); } if (schemaType == null) { - schemaType = serializerCodec.getSchemaType(); + schemaType = serializerSchemaRegistryCodec.getSchemaType(); } - String schemaString = serializerCodec.getSchemaString(object); - String schemaName = serializerCodec.getSchemaName(object); + String schemaString = serializerSchemaRegistryCodec.getSchemaString(object); + String schemaName = serializerSchemaRegistryCodec.getSchemaName(object); return this.maybeRegisterSchema(this.schemaGroup, schemaName, schemaString, this.schemaType) .onErrorMap(e -> { @@ -153,7 +153,7 @@ protected Mono serialize(T s, Object object) { .put(id.getBytes(StandardCharsets.UTF_8)); try { s.write(idBuffer.array()); - s.write(serializerCodec.encode(object)); + s.write(serializerSchemaRegistryCodec.encode(object)); } catch (IOException e) { sink.error(new SerializationException(e.getMessage(), e)); } @@ -209,8 +209,8 @@ protected Mono deserialize(InputStream s) { int length = buffer.limit() - SchemaRegistrySerializer.SCHEMA_ID_SIZE; byte[] b = Arrays.copyOfRange(buffer.array(), start, start + length); - Codec codec = getDeserializerCodec(registryObject); - sink.next(codec.decode(b, payloadSchema)); + SchemaRegistryCodec schemaRegistryCodec = getDeserializerCodec(registryObject); + sink.next(schemaRegistryCodec.decode(b, payloadSchema)); }) .onErrorMap(e -> { if (e instanceof SchemaRegistryClientException) { @@ -243,16 +243,16 @@ protected Mono deserialize(InputStream s) { * @return Codec to be used to deserialize encoded payload bytes * @throws SerializationException if decoder for the required schema type has not been loaded */ - private Codec getDeserializerCodec(SchemaRegistryObject registryObject) throws SerializationException { - Codec codec = deserializerCodecMap.get(registryObject.getSchemaType()); - if (codec == null) { + private SchemaRegistryCodec getDeserializerCodec(SchemaRegistryObject registryObject) throws SerializationException { + SchemaRegistryCodec schemaRegistryCodec = deserializerCodecMap.get(registryObject.getSchemaType()); + if (schemaRegistryCodec == null) { throw logger.logExceptionAsError( new SerializationException( String.format("No deserializer codec class found for schema type '%s'.", registryObject.getSchemaType()) )); } - return codec; + return schemaRegistryCodec; } /** diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java similarity index 92% rename from sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java index 529c0db93694c..6c823740d66f2 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java @@ -7,9 +7,9 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -public class SampleCodec implements Codec { +public class SampleSchemaRegistryCodec implements SchemaRegistryCodec { - public SampleCodec() { } + public SampleSchemaRegistryCodec() { } @Override public String getSchemaName(Object object) throws SerializationException { diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java index 69120ae5e4dbc..0b5cd210676bc 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java @@ -37,7 +37,7 @@ public class SchemaRegistrySerializerTest { @Test public void testRegistryGuidPrefixedToPayload() { // manually add SchemaRegistryObject into mock registry client cache - SampleCodec encoder = new SampleCodec(); + SampleSchemaRegistryCodec encoder = new SampleSchemaRegistryCodec(); SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, encoder.getSchemaType(), encoder.getSchemaName(null), @@ -108,7 +108,7 @@ public void testIfRegistryNullThenThrow() { @Test public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientException, SerializationException { // add sample codec impl and test that it is used for decoding payload - SampleCodec decoder = new SampleCodec(); + SampleSchemaRegistryCodec decoder = new SampleSchemaRegistryCodec(); // manually add SchemaRegistryObject to cache SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, @@ -136,7 +136,7 @@ public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientE }, ex -> System.out.println(ex)); - assertEquals(SampleCodec.CONSTANT_PAYLOAD, + assertEquals(SampleSchemaRegistryCodec.CONSTANT_PAYLOAD, serializer.deserialize(new ByteArrayInputStream(getPayload())).block()); } 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 index e585b5d8ae499..1a293d63d8c01 100644 --- 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 @@ -9,7 +9,7 @@ public class TestDummySerializer extends SchemaRegistrySerializer { TestDummySerializer( CachedSchemaRegistryAsyncClient mockClient, boolean autoRegisterSchemas) { - super(mockClient, new SampleCodec(), Collections.singletonList(new SampleCodec())); + super(mockClient, new SampleSchemaRegistryCodec(), Collections.singletonList(new SampleSchemaRegistryCodec())); // allows simulating improperly written serializer constructor that does not initialize byte encoder this.autoRegisterSchemas = autoRegisterSchemas; From 7d2859ba8bcd24d4ddce07be2a97c6b9ad738f50 Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Fri, 31 Jul 2020 16:01:41 -0700 Subject: [PATCH 06/17] Rename Codec to SchemaRegistryCodec (#13698) --- ...odec.java => AvroSchemaRegistryCodec.java} | 8 ++-- .../SchemaRegistryAvroAsyncSerializer.java | 2 +- .../SchemaRegistryAvroSerializerBuilder.java | 2 +- .../CachedSchemaRegistryClientBuilder.java | 12 ++--- .../{Codec.java => SchemaRegistryCodec.java} | 2 +- .../SchemaRegistrySerializer.java | 46 +++++++++---------- ...ec.java => SampleSchemaRegistryCodec.java} | 4 +- .../SchemaRegistrySerializerTest.java | 6 +-- .../schemaregistry/TestDummySerializer.java | 2 +- 9 files changed, 42 insertions(+), 42 deletions(-) rename sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/{AvroCodec.java => AvroSchemaRegistryCodec.java} (95%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{Codec.java => SchemaRegistryCodec.java} (98%) rename sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/{SampleCodec.java => SampleSchemaRegistryCodec.java} (92%) 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/AvroSchemaRegistryCodec.java similarity index 95% rename from sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroCodec.java rename to sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java index 7ef823a93061e..8b5e9a00077b1 100644 --- 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/AvroSchemaRegistryCodec.java @@ -4,7 +4,7 @@ package com.azure.data.schemaregistry.avro; import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.Codec; +import com.azure.data.schemaregistry.SchemaRegistryCodec; import com.azure.data.schemaregistry.models.SerializationException; import org.apache.avro.Schema; import org.apache.avro.generic.GenericDatumReader; @@ -21,7 +21,7 @@ /** * Base Codec class for Avro encoder and decoder implementations */ -public class AvroCodec implements Codec { +public class AvroSchemaRegistryCodec implements SchemaRegistryCodec { private final ClientLogger logger = new ClientLogger(AvroCodec.class); private static final EncoderFactory ENCODER_FACTORY = EncoderFactory.get(); private static final DecoderFactory DECODER_FACTORY = DecoderFactory.get(); @@ -33,9 +33,9 @@ public class AvroCodec implements Codec { * Instantiates AvroCodec instance * @param avroSpecificReader flag indicating if decoder should decode records as SpecificRecords */ - public AvroCodec(Boolean avroSpecificReader) { + public AvroSchemaRegistryCodec(Boolean avroSpecificReader) { if (avroSpecificReader == null) { - this.avroSpecificReader = AvroCodec.AVRO_SPECIFIC_READER_DEFAULT; + this.avroSpecificReader = AvroSchemaRegistryCodec.AVRO_SPECIFIC_READER_DEFAULT; } else { this.avroSpecificReader = avroSpecificReader; 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 index ad2356ed07a1a..f6118e8c5d4bd 100644 --- 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 @@ -26,7 +26,7 @@ public class SchemaRegistryAvroAsyncSerializer extends SchemaRegistrySerializer * @param schemaGroup * @param autoRegisterSchemas */ - SchemaRegistryAvroAsyncSerializer(CachedSchemaRegistryAsyncClient registryClient, AvroCodec codec, + SchemaRegistryAvroAsyncSerializer(CachedSchemaRegistryAsyncClient registryClient, AvroSchemaRegistryCodec codec, String schemaGroup, Boolean autoRegisterSchemas) { super(registryClient, codec, Collections.singletonList(codec), autoRegisterSchemas, schemaGroup); } 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 ab9ded5e224d9..d13ab42207f94 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 @@ -136,7 +136,7 @@ public SchemaRegistryAvroAsyncSerializer buildAsyncSerializer() { builder.maxCacheSize(maxCacheSize); } - AvroCodec codec = new AvroCodec(this.avroSpecificReader); + AvroSchemaRegistryCodec codec = new AvroSchemaRegistryCodec(this.avroSpecificReader); CachedSchemaRegistryAsyncClient client = builder .addCodec(codec) diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java index e4b14e27595d4..b962ec53f8f98 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java @@ -218,20 +218,20 @@ public CachedSchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) { * * The parseMethod argument should be a stateless, idempotent function. * - * @param codec Codec class implementation + * @param schemaRegistryCodec Codec class implementation * @return The updated {@link CachedSchemaRegistryClientBuilder} object. */ - public CachedSchemaRegistryClientBuilder addCodec(Codec codec) { - Objects.requireNonNull(codec, "'codec' cannot be null."); - if (CoreUtils.isNullOrEmpty(codec.getSchemaType())) { + public CachedSchemaRegistryClientBuilder addCodec(SchemaRegistryCodec schemaRegistryCodec) { + Objects.requireNonNull(schemaRegistryCodec, "'codec' cannot be null."); + if (CoreUtils.isNullOrEmpty(schemaRegistryCodec.getSchemaType())) { throw logger.logExceptionAsError( new IllegalArgumentException("Serialization type cannot be null or empty.")); } - if (this.typeParserMap.containsKey(codec.getSchemaType())) { + if (this.typeParserMap.containsKey(schemaRegistryCodec.getSchemaType())) { throw logger.logExceptionAsError( new IllegalArgumentException("Multiple parse methods for single serialization type may not be added.")); } - this.typeParserMap.put(codec.getSchemaType(), codec::parseSchemaString); + this.typeParserMap.put(schemaRegistryCodec.getSchemaType(), schemaRegistryCodec::parseSchemaString); return this; } 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/SchemaRegistryCodec.java similarity index 98% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/Codec.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryCodec.java index 8703c9e0b15f8..ee4097bc20a3a 100644 --- 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/SchemaRegistryCodec.java @@ -8,7 +8,7 @@ /** * An interface defining operations required for registry-based serialization and deserialization. */ -public interface Codec { +public interface SchemaRegistryCodec { /** * @return String representation of schema type, e.g. "avro" or "json". * diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java index 0297623541164..955ba5f69bdf2 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java @@ -36,8 +36,8 @@ public abstract class SchemaRegistrySerializer { CachedSchemaRegistryAsyncClient schemaRegistryClient; - private Codec serializerCodec; - private final Map deserializerCodecMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); + private SchemaRegistryCodec serializerSchemaRegistryCodec; + private final Map deserializerCodecMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); private String schemaType; Boolean autoRegisterSchemas = SchemaRegistrySerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; @@ -47,34 +47,34 @@ public abstract class SchemaRegistrySerializer { * Constructor for AbstractSchemaRegistrySerializer implementations. * * @param schemaRegistryClient client to be used for interfacing with Schema Registry service - * @param serializerCodec Codec to be used for serialization operations - * @param deserializerCodecList list of Codecs to be used to deserialize incoming payloads + * @param serializerSchemaRegistryCodec Codec to be used for serialization operations + * @param deserializerSchemaRegistryCodecList list of Codecs to be used to deserialize incoming payloads */ public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, - Codec serializerCodec, List deserializerCodecList) { - this(schemaRegistryClient, serializerCodec, deserializerCodecList, null, null); + SchemaRegistryCodec serializerSchemaRegistryCodec, List deserializerSchemaRegistryCodecList) { + this(schemaRegistryClient, serializerSchemaRegistryCodec, deserializerSchemaRegistryCodecList, null, null); } public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, - Codec serializerCodec, List deserializerCodecList, Boolean autoRegisterSchemas, + SchemaRegistryCodec serializerSchemaRegistryCodec, List deserializerSchemaRegistryCodecList, Boolean autoRegisterSchemas, String schemaGroup) { - Objects.requireNonNull(serializerCodec); - Objects.requireNonNull(deserializerCodecList); + Objects.requireNonNull(serializerSchemaRegistryCodec); + Objects.requireNonNull(deserializerSchemaRegistryCodecList); if (schemaRegistryClient == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Schema registry client must be initialized and passed into builder.")); } - if (deserializerCodecList.size() == 0) { + if (deserializerSchemaRegistryCodecList.size() == 0) { throw logger.logExceptionAsError( new IllegalArgumentException("At least one Codec must be provided for deserialization.")); } this.schemaRegistryClient = schemaRegistryClient; - this.serializerCodec = serializerCodec; - for (Codec c : deserializerCodecList) { + this.serializerSchemaRegistryCodec = serializerSchemaRegistryCodec; + for (SchemaRegistryCodec c : deserializerSchemaRegistryCodecList) { if (this.deserializerCodecMap.containsKey(c.getSchemaType())) { throw logger.logExceptionAsError( new IllegalArgumentException("Only on Codec can be provided per schema serialization type.")); @@ -109,17 +109,17 @@ protected Mono serialize(T s, Object object) { "Null object, behavior should be defined in concrete serializer implementation.")); } - if (serializerCodec == null) { + if (serializerSchemaRegistryCodec == null) { return monoError(logger, new SerializationException( "Byte encoder null, serializer must be initialized with a byte encoder.")); } if (schemaType == null) { - schemaType = serializerCodec.getSchemaType(); + schemaType = serializerSchemaRegistryCodec.getSchemaType(); } - String schemaString = serializerCodec.getSchemaString(object); - String schemaName = serializerCodec.getSchemaName(object); + String schemaString = serializerSchemaRegistryCodec.getSchemaString(object); + String schemaName = serializerSchemaRegistryCodec.getSchemaName(object); return this.maybeRegisterSchema(this.schemaGroup, schemaName, schemaString, this.schemaType) .onErrorMap(e -> { @@ -153,7 +153,7 @@ protected Mono serialize(T s, Object object) { .put(id.getBytes(StandardCharsets.UTF_8)); try { s.write(idBuffer.array()); - s.write(serializerCodec.encode(object)); + s.write(serializerSchemaRegistryCodec.encode(object)); } catch (IOException e) { sink.error(new SerializationException(e.getMessage(), e)); } @@ -209,8 +209,8 @@ protected Mono deserialize(InputStream s) { int length = buffer.limit() - SchemaRegistrySerializer.SCHEMA_ID_SIZE; byte[] b = Arrays.copyOfRange(buffer.array(), start, start + length); - Codec codec = getDeserializerCodec(registryObject); - sink.next(codec.decode(b, payloadSchema)); + SchemaRegistryCodec schemaRegistryCodec = getDeserializerCodec(registryObject); + sink.next(schemaRegistryCodec.decode(b, payloadSchema)); }) .onErrorMap(e -> { if (e instanceof SchemaRegistryClientException) { @@ -243,16 +243,16 @@ protected Mono deserialize(InputStream s) { * @return Codec to be used to deserialize encoded payload bytes * @throws SerializationException if decoder for the required schema type has not been loaded */ - private Codec getDeserializerCodec(SchemaRegistryObject registryObject) throws SerializationException { - Codec codec = deserializerCodecMap.get(registryObject.getSchemaType()); - if (codec == null) { + private SchemaRegistryCodec getDeserializerCodec(SchemaRegistryObject registryObject) throws SerializationException { + SchemaRegistryCodec schemaRegistryCodec = deserializerCodecMap.get(registryObject.getSchemaType()); + if (schemaRegistryCodec == null) { throw logger.logExceptionAsError( new SerializationException( String.format("No deserializer codec class found for schema type '%s'.", registryObject.getSchemaType()) )); } - return codec; + return schemaRegistryCodec; } /** diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java similarity index 92% rename from sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java index 529c0db93694c..6c823740d66f2 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleCodec.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java @@ -7,9 +7,9 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -public class SampleCodec implements Codec { +public class SampleSchemaRegistryCodec implements SchemaRegistryCodec { - public SampleCodec() { } + public SampleSchemaRegistryCodec() { } @Override public String getSchemaName(Object object) throws SerializationException { diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java index 69120ae5e4dbc..0b5cd210676bc 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java @@ -37,7 +37,7 @@ public class SchemaRegistrySerializerTest { @Test public void testRegistryGuidPrefixedToPayload() { // manually add SchemaRegistryObject into mock registry client cache - SampleCodec encoder = new SampleCodec(); + SampleSchemaRegistryCodec encoder = new SampleSchemaRegistryCodec(); SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, encoder.getSchemaType(), encoder.getSchemaName(null), @@ -108,7 +108,7 @@ public void testIfRegistryNullThenThrow() { @Test public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientException, SerializationException { // add sample codec impl and test that it is used for decoding payload - SampleCodec decoder = new SampleCodec(); + SampleSchemaRegistryCodec decoder = new SampleSchemaRegistryCodec(); // manually add SchemaRegistryObject to cache SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, @@ -136,7 +136,7 @@ public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientE }, ex -> System.out.println(ex)); - assertEquals(SampleCodec.CONSTANT_PAYLOAD, + assertEquals(SampleSchemaRegistryCodec.CONSTANT_PAYLOAD, serializer.deserialize(new ByteArrayInputStream(getPayload())).block()); } 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 index e585b5d8ae499..1a293d63d8c01 100644 --- 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 @@ -9,7 +9,7 @@ public class TestDummySerializer extends SchemaRegistrySerializer { TestDummySerializer( CachedSchemaRegistryAsyncClient mockClient, boolean autoRegisterSchemas) { - super(mockClient, new SampleCodec(), Collections.singletonList(new SampleCodec())); + super(mockClient, new SampleSchemaRegistryCodec(), Collections.singletonList(new SampleSchemaRegistryCodec())); // allows simulating improperly written serializer constructor that does not initialize byte encoder this.autoRegisterSchemas = autoRegisterSchemas; From 154dcb6d7cf41476ca4c2642c16d9beeb664711e Mon Sep 17 00:00:00 2001 From: Srikanta Date: Fri, 31 Jul 2020 16:31:14 -0700 Subject: [PATCH 07/17] minor updates to API --- .../data/schemaregistry/avro/AvroSchemaRegistryCodec.java | 3 ++- .../schemaregistry/avro/SchemaRegistryAvroSerializer.java | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java index 8b5e9a00077b1..f37b3c3f775b6 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java @@ -22,7 +22,7 @@ * Base Codec class for Avro encoder and decoder implementations */ public class AvroSchemaRegistryCodec implements SchemaRegistryCodec { - private final ClientLogger logger = new ClientLogger(AvroCodec.class); + private final ClientLogger logger = new ClientLogger(AvroSchemaRegistryCodec.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; @@ -124,6 +124,7 @@ public byte[] encode(Object object) { * @return deserialized object * @throws SerializationException upon deserialization failure */ + @Override public Object decode(byte[] b, Object object) { Objects.requireNonNull(object, "Schema must not be null."); 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 595833250d9c9..42d39463f4652 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 @@ -31,7 +31,7 @@ public class SchemaRegistryAvroSerializer { * @return byte array containing unique ID reference to schema, then the object serialized into bytes * @throws SerializationException Throws on serialization failure. */ - public byte[] serialize(Object object) throws SerializationException { + public byte[] serialize(Object object) { if (object == null) { return null; } @@ -53,7 +53,7 @@ public byte[] serialize(Object object) throws SerializationException { * @throws SerializationException Throws on deserialization failure. * Exception may contain inner exceptions detailing failure condition. */ - public Object deserialize(byte[] data) throws SerializationException { + public Object deserialize(byte[] data) { return serializer.deserialize(new ByteArrayInputStream(data), Object.class); } } From 3adda8a0619831678878f74a5f2d24092485c2ac Mon Sep 17 00:00:00 2001 From: Srikanta Date: Fri, 31 Jul 2020 16:38:54 -0700 Subject: [PATCH 08/17] Update deserializer method --- .../schemaregistry/avro/SchemaRegistryAvroSerializer.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 42d39463f4652..b514ef88bd63e 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 @@ -53,8 +53,8 @@ public byte[] serialize(Object object) { * @throws SerializationException Throws on deserialization failure. * Exception may contain inner exceptions detailing failure condition. */ - public Object deserialize(byte[] data) { - return serializer.deserialize(new ByteArrayInputStream(data), Object.class); + public T deserialize(byte[] data, Class clazz) { + return serializer.deserialize(new ByteArrayInputStream(data), clazz).block(); } } From 84c5569f8af9e996db94a58290d177b72ccd572d Mon Sep 17 00:00:00 2001 From: Srikanta Date: Fri, 31 Jul 2020 16:44:31 -0700 Subject: [PATCH 09/17] more api changes --- .../schemaregistry/avro/SchemaRegistryAvroAsyncSerializer.java | 2 +- .../data/schemaregistry/avro/SchemaRegistryAvroSerializer.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 index f6118e8c5d4bd..42b236069676a 100644 --- 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 @@ -16,7 +16,7 @@ /** * Asynchronous registry-based serializer implementation. */ -public class SchemaRegistryAvroAsyncSerializer extends SchemaRegistrySerializer implements ObjectSerializer { +public final class SchemaRegistryAvroAsyncSerializer extends SchemaRegistrySerializer implements ObjectSerializer { private final ClientLogger logger = new ClientLogger(SchemaRegistryAvroAsyncSerializer.class); /** 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 b514ef88bd63e..91a86a380a745 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 @@ -19,7 +19,7 @@ * * @see SchemaRegistrySerializer See AbstractSchemaRegistrySerializer for internal serialization implementation */ -public class SchemaRegistryAvroSerializer { +public final class SchemaRegistryAvroSerializer { private final SchemaRegistryAvroAsyncSerializer serializer; SchemaRegistryAvroSerializer(SchemaRegistryAvroAsyncSerializer serializer) { this.serializer = serializer; From a43bc6b0cbeecf0862c1361cd0fcba9ca109cf09 Mon Sep 17 00:00:00 2001 From: Srikanta <51379715+srnagar@users.noreply.github.com> Date: Fri, 31 Jul 2020 16:56:51 -0700 Subject: [PATCH 10/17] More API updates (#13699) * Rename Codec to SchemaRegistryCodec * minor updates to API * Update deserializer method * more api changes --- .../data/schemaregistry/avro/AvroSchemaRegistryCodec.java | 3 ++- .../avro/SchemaRegistryAvroAsyncSerializer.java | 2 +- .../schemaregistry/avro/SchemaRegistryAvroSerializer.java | 8 ++++---- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java index 8b5e9a00077b1..f37b3c3f775b6 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java @@ -22,7 +22,7 @@ * Base Codec class for Avro encoder and decoder implementations */ public class AvroSchemaRegistryCodec implements SchemaRegistryCodec { - private final ClientLogger logger = new ClientLogger(AvroCodec.class); + private final ClientLogger logger = new ClientLogger(AvroSchemaRegistryCodec.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; @@ -124,6 +124,7 @@ public byte[] encode(Object object) { * @return deserialized object * @throws SerializationException upon deserialization failure */ + @Override public Object decode(byte[] b, Object object) { Objects.requireNonNull(object, "Schema must not be null."); 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 index f6118e8c5d4bd..42b236069676a 100644 --- 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 @@ -16,7 +16,7 @@ /** * Asynchronous registry-based serializer implementation. */ -public class SchemaRegistryAvroAsyncSerializer extends SchemaRegistrySerializer implements ObjectSerializer { +public final class SchemaRegistryAvroAsyncSerializer extends SchemaRegistrySerializer implements ObjectSerializer { private final ClientLogger logger = new ClientLogger(SchemaRegistryAvroAsyncSerializer.class); /** 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 595833250d9c9..91a86a380a745 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 @@ -19,7 +19,7 @@ * * @see SchemaRegistrySerializer See AbstractSchemaRegistrySerializer for internal serialization implementation */ -public class SchemaRegistryAvroSerializer { +public final class SchemaRegistryAvroSerializer { private final SchemaRegistryAvroAsyncSerializer serializer; SchemaRegistryAvroSerializer(SchemaRegistryAvroAsyncSerializer serializer) { this.serializer = serializer; @@ -31,7 +31,7 @@ public class SchemaRegistryAvroSerializer { * @return byte array containing unique ID reference to schema, then the object serialized into bytes * @throws SerializationException Throws on serialization failure. */ - public byte[] serialize(Object object) throws SerializationException { + public byte[] serialize(Object object) { if (object == null) { return null; } @@ -53,8 +53,8 @@ public byte[] serialize(Object object) throws SerializationException { * @throws SerializationException Throws on deserialization failure. * Exception may contain inner exceptions detailing failure condition. */ - public Object deserialize(byte[] data) throws SerializationException { - return serializer.deserialize(new ByteArrayInputStream(data), Object.class); + public T deserialize(byte[] data, Class clazz) { + return serializer.deserialize(new ByteArrayInputStream(data), clazz).block(); } } From 4bfda0d24ae08bc6e46adc6d53a93dfe010cba27 Mon Sep 17 00:00:00 2001 From: Srikanta Date: Mon, 3 Aug 2020 17:03:57 -0700 Subject: [PATCH 11/17] Latest API view updates --- .../azure-data-schemaregistry-avro/pom.xml | 2 +- .../avro/AvroSchemaRegistryCodec.java | 14 +- .../SchemaRegistryAvroAsyncSerializer.java | 54 ------ .../avro/SchemaRegistryAvroSerializer.java | 92 +++++----- .../SchemaRegistryAvroSerializerBuilder.java | 28 +-- ...nt.java => SchemaRegistryAsyncClient.java} | 170 ++++++++--------- ...yClient.java => SchemaRegistryClient.java} | 25 +-- ....java => SchemaRegistryClientBuilder.java} | 87 ++++----- .../schemaregistry/SchemaRegistryCodec.java | 8 +- .../SchemaRegistrySerializer.java | 172 ++++++++---------- .../models/SchemaRegistryClientException.java | 26 --- .../models/SchemaRegistryObject.java | 21 +-- .../models/SerializationException.java | 26 --- .../models/SerializationType.java | 13 ++ .../SampleSchemaRegistryCodec.java | 14 +- ...ava => SchemaRegistryAsyncClientTest.java} | 52 +++--- .../SchemaRegistrySerializerTest.java | 51 +++--- .../schemaregistry/TestDummySerializer.java | 2 +- 18 files changed, 373 insertions(+), 484 deletions(-) delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroAsyncSerializer.java rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{CachedSchemaRegistryAsyncClient.java => SchemaRegistryAsyncClient.java} (65%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{CachedSchemaRegistryClient.java => SchemaRegistryClient.java} (73%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/{CachedSchemaRegistryClientBuilder.java => SchemaRegistryClientBuilder.java} (76%) delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryClientException.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SerializationException.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SerializationType.java rename sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/{CachedSchemaRegistryAsyncClientTest.java => SchemaRegistryAsyncClientTest.java} (85%) diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml index e9fcfd9db703c..94d9313f97c07 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml @@ -51,7 +51,7 @@ com.azure azure-core-experimental - 1.0.0-beta.1 + 1.0.0-beta.2 org.apache.avro diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java index f37b3c3f775b6..f9ebdd04c6323 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/AvroSchemaRegistryCodec.java @@ -5,7 +5,7 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.data.schemaregistry.SchemaRegistryCodec; -import com.azure.data.schemaregistry.models.SerializationException; +import com.azure.data.schemaregistry.models.SerializationType; import org.apache.avro.Schema; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericDatumWriter; @@ -43,8 +43,8 @@ public AvroSchemaRegistryCodec(Boolean avroSpecificReader) { } @Override - public String getSchemaType() { - return "avro"; + public SerializationType getSerializationType() { + return SerializationType.AVRO; } /** @@ -88,7 +88,6 @@ public String getSchemaGroup() { * 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 byte[] encode(Object object) { @@ -113,7 +112,7 @@ public byte[] encode(Object object) { } catch (IOException | RuntimeException e) { // Avro serialization can throw AvroRuntimeException, NullPointerException, ClassCastException, etc throw logger.logExceptionAsError( - new SerializationException("Error serializing Avro message", e)); + new IllegalStateException("Error serializing Avro message", e)); } } @@ -122,7 +121,6 @@ public byte[] encode(Object object) { * @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 */ @Override public Object decode(byte[] b, Object object) { @@ -130,7 +128,7 @@ public Object decode(byte[] b, Object object) { if (!(object instanceof Schema)) { throw logger.logExceptionAsError( - new SerializationException("Object must be an Avro schema.")); + new IllegalStateException("Object must be an Avro schema.")); } Schema schema = (Schema) object; @@ -150,7 +148,7 @@ public Object decode(byte[] b, Object object) { return result; } catch (IOException | RuntimeException e) { // avro deserialization may throw AvroRuntimeException, NullPointerException, etc - throw logger.logExceptionAsError(new SerializationException("Error deserializing Avro message.", e)); + throw logger.logExceptionAsError(new IllegalStateException("Error deserializing Avro message.", e)); } } 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 42b236069676a..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroAsyncSerializer.java +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.avro; - -import com.azure.core.experimental.serializer.ObjectSerializer; -import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.SchemaRegistrySerializer; -import com.azure.data.schemaregistry.models.SerializationException; -import com.azure.data.schemaregistry.CachedSchemaRegistryAsyncClient; -import reactor.core.publisher.Mono; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Collections; - -/** - * Asynchronous registry-based serializer implementation. - */ -public final class SchemaRegistryAvroAsyncSerializer extends SchemaRegistrySerializer implements ObjectSerializer { - private final ClientLogger logger = new ClientLogger(SchemaRegistryAvroAsyncSerializer.class); - - /** - * - * @param registryClient - * @param codec - * @param schemaGroup - * @param autoRegisterSchemas - */ - SchemaRegistryAvroAsyncSerializer(CachedSchemaRegistryAsyncClient registryClient, AvroSchemaRegistryCodec codec, - String schemaGroup, Boolean autoRegisterSchemas) { - super(registryClient, codec, Collections.singletonList(codec), autoRegisterSchemas, schemaGroup); - } - - @Override - public Mono serialize(S s, Object o) { - if (o == null) { - return Mono.empty(); - } - - return super.serialize(s, o); - } - - @Override - public Mono deserialize(InputStream stream, Class clazz) { - return this.deserialize(stream) - .map(o -> { - if (clazz.isInstance(o)) { - return clazz.cast(o); - } - throw logger.logExceptionAsError(new SerializationException("Deserialized object not of class %s")); - }); - } -} - 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 91a86a380a745..408b7885eba10 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,58 +3,68 @@ package com.azure.data.schemaregistry.avro; +import com.azure.core.experimental.serializer.ObjectSerializer; +import com.azure.core.experimental.serializer.TypeReference; +import com.azure.core.util.logging.ClientLogger; import com.azure.data.schemaregistry.SchemaRegistrySerializer; -import com.azure.data.schemaregistry.models.SerializationException; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; +import com.azure.data.schemaregistry.SchemaRegistryAsyncClient; +import reactor.core.publisher.Mono; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Collections; /** - * 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 SchemaRegistrySerializer See AbstractSchemaRegistrySerializer for internal serialization implementation + * Asynchronous registry-based serializer implementation. */ -public final class SchemaRegistryAvroSerializer { - private final SchemaRegistryAvroAsyncSerializer serializer; - SchemaRegistryAvroSerializer(SchemaRegistryAvroAsyncSerializer serializer) { - this.serializer = serializer; - } +public final class SchemaRegistryAvroSerializer extends SchemaRegistrySerializer implements ObjectSerializer { + private final ClientLogger logger = new ClientLogger(SchemaRegistryAvroSerializer.class); /** - * Serializes object into byte array payload using the configured byte encoder. - * @param object target of serialization - * @return byte array containing unique ID reference to schema, then the object serialized into bytes - * @throws SerializationException Throws on serialization failure. + * + * @param registryClient + * @param codec + * @param schemaGroup + * @param autoRegisterSchemas */ - public byte[] serialize(Object object) { - if (object == null) { - return null; - } + SchemaRegistryAvroSerializer(SchemaRegistryAsyncClient registryClient, AvroSchemaRegistryCodec codec, + String schemaGroup, Boolean autoRegisterSchemas) { + super(registryClient, codec, Collections.singletonList(codec), autoRegisterSchemas, schemaGroup); + } - ByteArrayOutputStream s = serializer.serialize(new ByteArrayOutputStream(), object).block(); - if (s != null){ - s.toByteArray(); - } + @Override + public T deserialize(InputStream stream, TypeReference typeReference) { + return null; + } - throw new SerializationException("Serialization failed, null output stream returned."); + @Override + public Mono deserializeAsync(InputStream stream, + TypeReference typeReference) { + return null; } - /** - * 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 T deserialize(byte[] data, Class clazz) { - return serializer.deserialize(new ByteArrayInputStream(data), clazz).block(); + @Override + public S serialize(S stream, Object value) { + return null; } + + @Override + public Mono serializeAsync(S stream, Object object) { + if (object == null) { + return Mono.empty(); + } + + return super.serializeAsync(stream, object); + } + +// @Override +// public Mono deserialize(InputStream stream, Class clazz) { +// return this.deserialize(stream) +// .map(o -> { +// if (clazz.isInstance(o)) { +// return clazz.cast(o); +// } +// throw logger.logExceptionAsError(new IllegalStateException("Deserialized object not of class %s")); +// }); +// } } 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 d13ab42207f94..785579fc90015 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 @@ -4,13 +4,13 @@ package com.azure.data.schemaregistry.avro; import com.azure.core.credential.TokenCredential; -import com.azure.data.schemaregistry.CachedSchemaRegistryAsyncClient; -import com.azure.data.schemaregistry.CachedSchemaRegistryClientBuilder; +import com.azure.data.schemaregistry.SchemaRegistryAsyncClient; +import com.azure.data.schemaregistry.SchemaRegistryClientBuilder; import java.util.Objects; /** - * Builder implemenation for building {@link SchemaRegistryAvroSerializer} and {@link SchemaRegistryAvroAsyncSerializer} + * Builder implemenation for building {@link SchemaRegistryAvroSerializer} and {@link SchemaRegistryAvroSerializer} */ public final class SchemaRegistryAvroSerializerBuilder { private String registryUrl; @@ -109,26 +109,16 @@ public SchemaRegistryAvroSerializerBuilder maxCacheSize(int maxCacheSize) { return this; } - /** - * Instantiates {@link SchemaRegistryAvroSerializer} - * @return {@link SchemaRegistryAvroSerializer} instance - * - * @throws NullPointerException if parameters are incorrectly set. - * @throws IllegalArgumentException if credential is not set. - */ - public SchemaRegistryAvroSerializer buildSerializer() { - return new SchemaRegistryAvroSerializer(this.buildAsyncSerializer()); - } /** * Instantiates SchemaRegistry - * @return {@link SchemaRegistryAvroAsyncSerializer} instance + * @return {@link SchemaRegistryAvroSerializer} instance * * @throws NullPointerException if parameters are incorrectly set. * @throws IllegalArgumentException if credential is not set. */ - public SchemaRegistryAvroAsyncSerializer buildAsyncSerializer() { - CachedSchemaRegistryClientBuilder builder = new CachedSchemaRegistryClientBuilder() + public SchemaRegistryAvroSerializer buildSerializer() { + SchemaRegistryClientBuilder builder = new SchemaRegistryClientBuilder() .endpoint(registryUrl) .credential(credential); @@ -138,11 +128,11 @@ public SchemaRegistryAvroAsyncSerializer buildAsyncSerializer() { AvroSchemaRegistryCodec codec = new AvroSchemaRegistryCodec(this.avroSpecificReader); - CachedSchemaRegistryAsyncClient client = builder - .addCodec(codec) + SchemaRegistryAsyncClient client = builder + .addSchemaRegistryCodec(codec) .buildAsyncClient(); - return new SchemaRegistryAvroAsyncSerializer(client, codec, this.schemaGroup, + return new SchemaRegistryAvroSerializer(client, codec, this.schemaGroup, this.autoRegisterSchemas); } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java similarity index 65% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClient.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java index 94e9b1f95aaf3..fa7a5456ea57f 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClient.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java @@ -6,17 +6,14 @@ import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; -import com.azure.core.exception.HttpResponseException; 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.implementation.AzureSchemaRegistryRestService; import com.azure.data.schemaregistry.implementation.models.SchemaId; -import com.azure.data.schemaregistry.models.SchemaRegistryClientException; import com.azure.data.schemaregistry.models.SchemaRegistryObject; -import reactor.core.publisher.Mono; - +import com.azure.data.schemaregistry.models.SerializationType; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Map; @@ -24,12 +21,13 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Function; +import reactor.core.publisher.Mono; /** * 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#maxCacheSize(int)}, otherwise {@code 1000} will be used as the + * using {@link SchemaRegistryClientBuilder#maxCacheSize(int)}, otherwise {@code 1000} will be used as the * default. *

    * Two maps are maintained. @@ -39,14 +37,14 @@ * *

    * - * @see CachedSchemaRegistryClientBuilder Follows builder pattern for object instantiation + * @see SchemaRegistryClientBuilder Follows builder pattern for object instantiation */ @ServiceClient( - builder = CachedSchemaRegistryClientBuilder.class, + builder = SchemaRegistryClientBuilder.class, serviceInterfaces = AzureSchemaRegistryRestService.class) -public final class CachedSchemaRegistryAsyncClient { +public final class SchemaRegistryAsyncClient { - private final ClientLogger logger = new ClientLogger(CachedSchemaRegistryAsyncClient.class); + 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; @@ -58,7 +56,7 @@ public final class CachedSchemaRegistryAsyncClient { private final Map idCache; private final Map schemaStringCache; - CachedSchemaRegistryAsyncClient( + SchemaRegistryAsyncClient( AzureSchemaRegistryRestService restService, int maxSchemaMapSize, ConcurrentSkipListMap> typeParserMap) { @@ -70,7 +68,7 @@ public final class CachedSchemaRegistryAsyncClient { } // testing - todo remove constructor and replace with mock - CachedSchemaRegistryAsyncClient( + SchemaRegistryAsyncClient( AzureSchemaRegistryRestService restService, Map idCache, Map schemaStringCache, @@ -84,66 +82,67 @@ public final class CachedSchemaRegistryAsyncClient { @ServiceMethod(returns = ReturnType.SINGLE) public Mono registerSchema( - String schemaGroup, String schemaName, String schemaString, String schemaType) { + 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, schemaType, schemaString); + schemaGroup, schemaName, serializationType, schemaString); return Mono.fromCallable( () -> schemaStringCache.get(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))); } - return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType) + return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType) .map(response -> response.getValue()); } @ServiceMethod(returns = ReturnType.SINGLE) public Mono> registerSchemaWithResponse(String schemaGroup, String schemaName, - String schemaString, String schemaType) { - return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE); + String schemaString, SerializationType serializationType) { + return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType, Context.NONE); } Mono> registerSchemaWithResponse(String schemaGroup, String schemaName, - String schemaString, String schemaType, Context context) { + String schemaString, SerializationType serializationType, Context context) { logger.verbose( "Registering schema. Group: '{}', name: '{}', serialization type: '{}', payload: '{}'", - schemaGroup, schemaName, schemaType, schemaString); - - return this.restService.createSchemaWithResponseAsync(schemaGroup, schemaName, schemaType, schemaString) - .onErrorMap(HttpResponseException.class, e -> logger.logExceptionAsError( - new SchemaRegistryClientException("Register operation failed, unexpected service response.", e))) - .handle((response, sink) -> { - if (response == null) { - sink.error(logger.logExceptionAsError( - new SchemaRegistryClientException("Client returned null response"))); - return; - } - - if (response.getStatusCode() == 400) { - sink.error(logger.logExceptionAsError( - new SchemaRegistryClientException("Invalid schema registration attempted"))); - return; - } - - SchemaId schemaId = response.getValue(); - - SchemaRegistryObject registered = new SchemaRegistryObject(schemaId.getId(), - schemaType, - schemaName, - schemaGroup, - schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), - getParseFunc(schemaType)); - - 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); - }); + schemaGroup, schemaName, serializationType, schemaString); + + return this.restService + .createSchemaWithResponseAsync(schemaGroup, schemaName, serializationType.toString(), schemaString) +// .onErrorMap(HttpResponseException.class, e -> logger.logExceptionAsError( +// new SchemaRegistryClientException("Register operation failed, unexpected service response.", e))) + .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(); + + SchemaRegistryObject registered = new SchemaRegistryObject(schemaId.getId(), + serializationType, + schemaName, + schemaGroup, + schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), + getParseFunc(serializationType)); + + 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); + }); } @ServiceMethod(returns = ReturnType.SINGLE) @@ -163,30 +162,31 @@ public Mono> getSchemaWithResponse(String schemaI Mono> getSchemaWithResponse(String schemaId, Context context) { Objects.requireNonNull(schemaId, "'schemaId' should not be null"); return this.restService.getSchemaByIdWithResponseAsync(schemaId) - .onErrorMap(HttpResponseException.class, - e -> logger.logExceptionAsError( - new SchemaRegistryClientException("Fetching schema failed, unexpected service response.", e))) +// .onErrorMap(HttpResponseException.class, +// e -> logger.logExceptionAsError( +// new SchemaRegistryClientException("Fetching schema failed, unexpected service response.", e))) .handle((response, sink) -> { if (response == null) { sink.error(logger.logExceptionAsError( - new SchemaRegistryClientException("Client returned null response"))); + new NullPointerException("Client returned null response"))); return; } if (response.getStatusCode() == 404) { sink.error(logger.logExceptionAsError( - new SchemaRegistryClientException(String.format("Schema does not exist, id %s", schemaId)))); + new IllegalStateException(String.format("Schema does not exist, id %s", schemaId)))); return; } - String schemaType = response.getDeserializedHeaders().getXSchemaType(); + SerializationType serializationType = + SerializationType.fromString(response.getDeserializedHeaders().getXSchemaType()); SchemaRegistryObject schemaObject = new SchemaRegistryObject(schemaId, - schemaType, + serializationType, null, null, response.getValue().getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), - getParseFunc(schemaType)); + getParseFunc(serializationType)); resetIfNeeded(); idCache.putIfAbsent(schemaId, schemaObject); @@ -200,41 +200,44 @@ Mono> getSchemaWithResponse(String schemaId, Cont @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) { + public Mono getSchemaId(String schemaGroup, String schemaName, String schemaString, + SerializationType serializationType) { if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { logger.verbose("Cache hit schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); return Mono.fromCallable(() -> schemaStringCache.get(schemaString).getSchemaId()); } - return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType) + return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, serializationType) .map(response -> response.getValue()); } @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, - String schemaType) { - return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE); + SerializationType serializationType) { + return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, serializationType, Context.NONE); } Mono> getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, - String schemaType, Context context) { - - return this.restService.getIdBySchemaContentWithResponseAsync(schemaGroup, schemaName, schemaType, schemaString) - .onErrorMap(HttpResponseException.class, e -> - logger.logExceptionAsError(new SchemaRegistryClientException(String.format( - "Failed to fetch ID for schema, unexpected service response. Group: '%s', name: '%s'", - schemaGroup, schemaName), e))) + SerializationType serializationType, Context context) { + + return this.restService + .getIdBySchemaContentWithResponseAsync(schemaGroup, schemaName, serializationType.toString(), + schemaString) +// .onErrorMap(HttpResponseException.class, e -> +// logger.logExceptionAsError(new SchemaRegistryClientException(String.format( +// "Failed to fetch ID for schema, unexpected service response. Group: '%s', name: '%s'", +// schemaGroup, schemaName), e))) .handle((response, sink) -> { if (response == null) { sink.error(logger.logExceptionAsError( - new SchemaRegistryClientException("Client returned null response"))); + new NullPointerException("Client returned null response"))); return; } if (response.getStatusCode() == 404) { - sink.error(logger.logExceptionAsError( - new SchemaRegistryClientException("Existing matching schema not found."))); + sink.error( + logger.logExceptionAsError(new IllegalStateException("Existing matching schema not found."))); return; } @@ -245,11 +248,11 @@ Mono> getSchemaIdWithResponse(String schemaGroup, String schema getSchemaStringCacheKey(schemaGroup, schemaName, schemaString), new SchemaRegistryObject( schemaId.getId(), - schemaType, + serializationType, schemaName, schemaGroup, schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), - getParseFunc(schemaType))); + getParseFunc(serializationType))); logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); SimpleResponse schemaIdResponse = new SimpleResponse<>( @@ -262,7 +265,7 @@ Mono> getSchemaIdWithResponse(String schemaGroup, String schema /** * Explicit call to clear all caches. */ - public void clearCache() { + void clearCache() { idCache.clear(); schemaStringCache.clear(); typeParserMap.clear(); @@ -288,17 +291,16 @@ private void resetIfNeeded() { /** * Return stored parse function for parsing schema payloads of specified schema type * - * @param schemaType schema type of payload to be deserialized + * @param serializationType schema type of payload to be deserialized * @return parse method for deserializing schema string */ - private Function getParseFunc(String schemaType) { - Function parseFunc = typeParserMap.get(schemaType); + private Function getParseFunc(SerializationType serializationType) { + Function parseFunc = typeParserMap.get(serializationType); if (parseFunc == null) { - throw logger.logExceptionAsError(new SchemaRegistryClientException( + throw logger.logExceptionAsError(new NullPointerException( String.format("Unexpected serialization type '%s' received. Currently loaded parsers: %s", - schemaType, - typeParserMap.keySet().toString()))); + serializationType, typeParserMap.keySet().toString()))); } return parseFunc; } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClient.java similarity index 73% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClient.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClient.java index c0c3a5c2f5f12..480c8c94ebb41 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClient.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClient.java @@ -7,27 +7,28 @@ import com.azure.core.util.Context; import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestService; import com.azure.data.schemaregistry.models.SchemaRegistryObject; +import com.azure.data.schemaregistry.models.SerializationType; @ServiceClient( - builder = CachedSchemaRegistryClientBuilder.class, + builder = SchemaRegistryClientBuilder.class, serviceInterfaces = AzureSchemaRegistryRestService.class) -public final class CachedSchemaRegistryClient { - private final CachedSchemaRegistryAsyncClient asyncClient; +public final class SchemaRegistryClient { + private final SchemaRegistryAsyncClient asyncClient; - CachedSchemaRegistryClient(CachedSchemaRegistryAsyncClient asyncClient) { + SchemaRegistryClient(SchemaRegistryAsyncClient asyncClient) { this.asyncClient = asyncClient; } @ServiceMethod(returns = ReturnType.SINGLE) public SchemaRegistryObject registerSchema(String schemaGroup, String schemaName, String schemaString, - String schemaType) { + SerializationType schemaType) { return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE).getValue(); } @ServiceMethod(returns = ReturnType.SINGLE) public Response registerSchemaWithResponse(String schemaGroup, String schemaName, - String schemaString, String schemaType, Context context) { - return this.asyncClient.registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType, + String schemaString, SerializationType serializationType, Context context) { + return this.asyncClient.registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType, context).block(); } @@ -42,18 +43,18 @@ public Response getSchemaWithResponse(String schemaId, Con } @ServiceMethod(returns = ReturnType.SINGLE) - public String getSchemaId(String schemaGroup, String schemaName, String schemaString, String schemaType) { - return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE).getValue(); + public String getSchemaId(String schemaGroup, String schemaName, String schemaString, SerializationType serializationType) { + return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, serializationType, Context.NONE).getValue(); } @ServiceMethod(returns = ReturnType.SINGLE) public Response getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, - String schemaType, Context context) { - return this.asyncClient.getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, schemaType, context) + SerializationType serializationType, Context context) { + return this.asyncClient.getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, serializationType, context) .block(); } - public void clearCache() { + void clearCache() { this.asyncClient.clearCache(); } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java similarity index 76% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java index b962ec53f8f98..9e9eb0afe814b 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/CachedSchemaRegistryClientBuilder.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java @@ -36,11 +36,11 @@ import java.util.function.Function; /** - * Builder implementation for {@link CachedSchemaRegistryAsyncClient}. + * Builder implementation for {@link SchemaRegistryAsyncClient}. */ -@ServiceClientBuilder(serviceClients = CachedSchemaRegistryAsyncClient.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"; @@ -65,7 +65,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; @@ -86,12 +86,12 @@ 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 { @@ -113,15 +113,15 @@ public CachedSchemaRegistryClientBuilder endpoint(String schemaRegistryUrl) { /** * Sets schema cache size limit. If limit is exceeded on any cache, all caches are recycled. * - * @param maxCacheSize max size for internal schema caches in {@link CachedSchemaRegistryAsyncClient} - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. + * @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 maxCacheSize(int maxCacheSize) { - if (maxCacheSize < CachedSchemaRegistryAsyncClient.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", - CachedSchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM))); + SchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_MINIMUM))); } this.maxSchemaMapSize = maxCacheSize; @@ -132,9 +132,9 @@ public CachedSchemaRegistryClientBuilder maxCacheSize(int maxCacheSize) { * 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; } @@ -142,12 +142,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 CachedSchemaRegistryAsyncClient}. + * 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."); } @@ -159,13 +159,13 @@ public CachedSchemaRegistryClientBuilder pipeline(HttpPipeline httpPipeline) { /** * Sets the {@link TokenCredential} to use when authenticating HTTP requests for this - * {@link CachedSchemaRegistryAsyncClient}. + * {@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; } @@ -176,9 +176,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; } @@ -186,12 +186,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 CachedSchemaRegistryAsyncClient} . + * 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; } @@ -200,10 +200,10 @@ 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; } @@ -219,34 +219,35 @@ public CachedSchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) { * The parseMethod argument should be a stateless, idempotent function. * * @param schemaRegistryCodec Codec class implementation - * @return The updated {@link CachedSchemaRegistryClientBuilder} object. + * @return The updated {@link SchemaRegistryClientBuilder} object. */ - public CachedSchemaRegistryClientBuilder addCodec(SchemaRegistryCodec schemaRegistryCodec) { + public SchemaRegistryClientBuilder addSchemaRegistryCodec(SchemaRegistryCodec schemaRegistryCodec) { Objects.requireNonNull(schemaRegistryCodec, "'codec' cannot be null."); - if (CoreUtils.isNullOrEmpty(schemaRegistryCodec.getSchemaType())) { + if (schemaRegistryCodec.getSerializationType() == null) { throw logger.logExceptionAsError( new IllegalArgumentException("Serialization type cannot be null or empty.")); } - if (this.typeParserMap.containsKey(schemaRegistryCodec.getSchemaType())) { + if (this.typeParserMap.containsKey(schemaRegistryCodec.getSerializationType())) { throw logger.logExceptionAsError( new IllegalArgumentException("Multiple parse methods for single serialization type may not be added.")); } - this.typeParserMap.put(schemaRegistryCodec.getSchemaType(), schemaRegistryCodec::parseSchemaString); + this.typeParserMap.put(schemaRegistryCodec.getSerializationType().toString(), + schemaRegistryCodec::parseSchemaString); return this; } /** - * Creates a {@link CachedSchemaRegistryAsyncClient} based on options set in the builder. - * Every time {@code buildClient()} is called a new instance of {@link CachedSchemaRegistryAsyncClient} 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 CachedSchemaRegistryAsyncClient client}. + * endpoint} are when creating the {@link SchemaRegistryAsyncClient client}. * - * @return A {@link CachedSchemaRegistryAsyncClient} 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 CachedSchemaRegistryAsyncClient buildAsyncClient() { + public SchemaRegistryAsyncClient buildAsyncClient() { // Authentications if (credential == null) { // Throw exception that credential and tokenCredential cannot be null @@ -290,18 +291,18 @@ public CachedSchemaRegistryAsyncClient buildAsyncClient() { this.maxSchemaMapSize = this.maxSchemaMapSize != null ? this.maxSchemaMapSize - : CachedSchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_DEFAULT; + : SchemaRegistryAsyncClient.MAX_SCHEMA_MAP_SIZE_DEFAULT; - return new CachedSchemaRegistryAsyncClient(restService, maxSchemaMapSize, typeParserMap); + return new SchemaRegistryAsyncClient(restService, maxSchemaMapSize, typeParserMap); } /** - * Creates synchronous {@link CachedSchemaRegistryClient} instance. + * Creates synchronous {@link SchemaRegistryClient} instance. * See async builder method for options validation. * - * @return {@link CachedSchemaRegistryClient} with the options set from the builder. + * @return {@link SchemaRegistryClient} with the options set from the builder. */ - public CachedSchemaRegistryClient buildClient() { - return new CachedSchemaRegistryClient(this.buildAsyncClient()); + public SchemaRegistryClient buildClient() { + return new SchemaRegistryClient(this.buildAsyncClient()); } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryCodec.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryCodec.java index ee4097bc20a3a..6abad206e9f8f 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryCodec.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryCodec.java @@ -3,7 +3,7 @@ package com.azure.data.schemaregistry; -import com.azure.data.schemaregistry.models.SerializationException; +import com.azure.data.schemaregistry.models.SerializationType; /** * An interface defining operations required for registry-based serialization and deserialization. @@ -15,7 +15,7 @@ public interface SchemaRegistryCodec { * Utilized by schema registry store and client as non-case-sensitive tags for * schemas of a specific type. */ - String getSchemaType(); + SerializationType getSerializationType(); /** * Parses string representation of schema into schema Object @@ -30,7 +30,6 @@ public interface SchemaRegistryCodec { * 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); @@ -41,7 +40,6 @@ public interface SchemaRegistryCodec { * * @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); @@ -49,7 +47,6 @@ public interface SchemaRegistryCodec { * 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 */ byte[] encode(Object object); @@ -58,7 +55,6 @@ public interface SchemaRegistryCodec { * @param encodedBytes payload to be decoded * @param schemaObject object used to decode the payload * @return deserialized object - * @throws SerializationException if decode operation fails */ Object decode(byte[] encodedBytes, Object schemaObject); } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java index 955ba5f69bdf2..852e03727b1d1 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java @@ -3,17 +3,15 @@ package com.azure.data.schemaregistry; -import com.azure.core.exception.HttpResponseException; +import static com.azure.core.util.FluxUtil.monoError; + import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.models.SchemaRegistryClientException; import com.azure.data.schemaregistry.models.SchemaRegistryObject; -import com.azure.data.schemaregistry.models.SerializationException; -import reactor.core.publisher.Mono; - +import com.azure.data.schemaregistry.models.SerializationType; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.nio.BufferUnderflowException; +import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -21,8 +19,7 @@ import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentSkipListMap; - -import static com.azure.core.util.FluxUtil.monoError; +import reactor.core.publisher.Mono; /** * Common implementation for all registry-based serializers. @@ -34,11 +31,11 @@ public abstract class SchemaRegistrySerializer { static final String SCHEMA_GROUP_DEFAULT = "$default"; static final int SCHEMA_ID_SIZE = 32; - CachedSchemaRegistryAsyncClient schemaRegistryClient; + SchemaRegistryAsyncClient schemaRegistryClient; private SchemaRegistryCodec serializerSchemaRegistryCodec; private final Map deserializerCodecMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); - private String schemaType; + private SerializationType serializationType; Boolean autoRegisterSchemas = SchemaRegistrySerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; String schemaGroup = SchemaRegistrySerializer.SCHEMA_GROUP_DEFAULT; @@ -50,12 +47,12 @@ public abstract class SchemaRegistrySerializer { * @param serializerSchemaRegistryCodec Codec to be used for serialization operations * @param deserializerSchemaRegistryCodecList list of Codecs to be used to deserialize incoming payloads */ - public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, + public SchemaRegistrySerializer(SchemaRegistryAsyncClient schemaRegistryClient, SchemaRegistryCodec serializerSchemaRegistryCodec, List deserializerSchemaRegistryCodecList) { this(schemaRegistryClient, serializerSchemaRegistryCodec, deserializerSchemaRegistryCodecList, null, null); } - public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryClient, + public SchemaRegistrySerializer(SchemaRegistryAsyncClient schemaRegistryClient, SchemaRegistryCodec serializerSchemaRegistryCodec, List deserializerSchemaRegistryCodecList, Boolean autoRegisterSchemas, String schemaGroup) { @@ -75,11 +72,11 @@ public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryCl this.schemaRegistryClient = schemaRegistryClient; this.serializerSchemaRegistryCodec = serializerSchemaRegistryCodec; for (SchemaRegistryCodec c : deserializerSchemaRegistryCodecList) { - if (this.deserializerCodecMap.containsKey(c.getSchemaType())) { + if (this.deserializerCodecMap.containsKey(c.getSerializationType())) { throw logger.logExceptionAsError( new IllegalArgumentException("Only on Codec can be provided per schema serialization type.")); } - this.deserializerCodecMap.put(c.getSchemaType(), c); + this.deserializerCodecMap.put(c.getSerializationType().toString(), c); } // send configurations only @@ -101,53 +98,52 @@ public SchemaRegistrySerializer(CachedSchemaRegistryAsyncClient schemaRegistryCl * @param object object to be serialized * @param Type of the output stream parameter. * @return byte array containing encoded bytes with prefixed schema ID - * @throws SerializationException if serialization operation fails during runtime. */ - protected Mono serialize(T s, Object object) { + protected Mono serializeAsync(S s, Object object) { if (object == null) { - return monoError(logger, new SerializationException( + return monoError(logger, new NullPointerException( "Null object, behavior should be defined in concrete serializer implementation.")); } if (serializerSchemaRegistryCodec == null) { - return monoError(logger, new SerializationException( + return monoError(logger, new NullPointerException( "Byte encoder null, serializer must be initialized with a byte encoder.")); } - if (schemaType == null) { - schemaType = serializerSchemaRegistryCodec.getSchemaType(); + if (serializationType == null) { + serializationType = serializerSchemaRegistryCodec.getSerializationType(); } String schemaString = serializerSchemaRegistryCodec.getSchemaString(object); String schemaName = serializerSchemaRegistryCodec.getSchemaName(object); - return this.maybeRegisterSchema(this.schemaGroup, schemaName, schemaString, this.schemaType) - .onErrorMap(e -> { - if (e instanceof SchemaRegistryClientException) { - StringBuilder builder = new StringBuilder(); - if (this.autoRegisterSchemas) { - builder.append(String.format("Error registering Avro schema. Group: %s, name: %s. ", - schemaGroup, schemaName)); - } else { - builder.append(String.format("Error retrieving Avro schema. Group: %s, name: %s. ", - schemaGroup, schemaName)); - } - - if (e.getCause() instanceof HttpResponseException) { - HttpResponseException httpException = (HttpResponseException) e.getCause(); - builder.append("HTTP ") - .append(httpException.getResponse().getStatusCode()) - .append(" ") - .append(httpException.getResponse().getBodyAsString()); - } else { - builder.append(e.getCause().getMessage()); - } - - return logger.logExceptionAsError(new SerializationException(builder.toString(), e)); - } else { - return logger.logExceptionAsError(new SerializationException(e.getMessage(), e)); - } - }) + return this.maybeRegisterSchema(this.schemaGroup, schemaName, schemaString, this.serializationType) +// .onErrorMap(e -> { +// if (e instanceof SchemaRegistryClientException) { +// StringBuilder builder = new StringBuilder(); +// if (this.autoRegisterSchemas) { +// builder.append(String.format("Error registering Avro schema. Group: %s, name: %s. ", +// schemaGroup, schemaName)); +// } else { +// builder.append(String.format("Error retrieving Avro schema. Group: %s, name: %s. ", +// schemaGroup, schemaName)); +// } +// +// if (e.getCause() instanceof HttpResponseException) { +// HttpResponseException httpException = (HttpResponseException) e.getCause(); +// builder.append("HTTP ") +// .append(httpException.getResponse().getStatusCode()) +// .append(" ") +// .append(httpException.getResponse().getBodyAsString()); +// } else { +// builder.append(e.getCause().getMessage()); +// } +// +// return logger.logExceptionAsError(new SerializationException(builder.toString(), e)); +// } else { +// return logger.logExceptionAsError(new SerializationException(e.getMessage(), e)); +// } +// }) .handle((id, sink) -> { ByteBuffer idBuffer = ByteBuffer.allocate(SchemaRegistrySerializer.SCHEMA_ID_SIZE) .put(id.getBytes(StandardCharsets.UTF_8)); @@ -155,7 +151,7 @@ protected Mono serialize(T s, Object object) { s.write(idBuffer.array()); s.write(serializerSchemaRegistryCodec.encode(object)); } catch (IOException e) { - sink.error(new SerializationException(e.getMessage(), e)); + sink.error(new UncheckedIOException(e.getMessage(), e)); } sink.next(s); }); @@ -168,9 +164,8 @@ protected Mono serialize(T s, Object object) { * * @param s InputStream containing bytes encoded by an Azure Schema Registry producer * @return object, deserialized with the prefixed schema - * @throws SerializationException if deserialization of registry schema or message payload fails. */ - protected Mono deserialize(InputStream s) { + protected Mono deserializeAsync(InputStream s) { if (s == null) { return Mono.empty(); } @@ -189,19 +184,17 @@ protected Mono deserialize(InputStream s) { String schemaId = getSchemaIdFromPayload(buffer); System.out.println(schemaId); - SchemaRegistryObject block = this.schemaRegistryClient.getSchema(schemaId).block(); - System.out.println(block); return this.schemaRegistryClient.getSchema(schemaId) - .onErrorMap(IOException.class, - e -> logger.logExceptionAsError(new SerializationException(e.getMessage(), e))) +// .onErrorMap(IOException.class, +// e -> logger.logExceptionAsError(new SerializationException(e.getMessage(), e))) .handle((registryObject, sink) -> { Object payloadSchema = registryObject.getSchema(); if (payloadSchema == null) { sink.error(logger.logExceptionAsError( - new SerializationException( + new NullPointerException( String.format("Payload schema returned as null. Schema type: %s, Schema ID: %s", - registryObject.getSchemaType(), registryObject.getSchemaId())))); + registryObject.getSerializationType(), registryObject.getSchemaId())))); return; } @@ -211,27 +204,27 @@ protected Mono deserialize(InputStream s) { SchemaRegistryCodec schemaRegistryCodec = getDeserializerCodec(registryObject); sink.next(schemaRegistryCodec.decode(b, payloadSchema)); - }) - .onErrorMap(e -> { - if (e instanceof SchemaRegistryClientException) { - StringBuilder builder = new StringBuilder( - String.format("Failed to retrieve schema for id %s", schemaId)); - - if (e.getCause() instanceof HttpResponseException) { - HttpResponseException httpException = (HttpResponseException) e.getCause(); - builder.append("HTTP ") - .append(httpException.getResponse().getStatusCode()) - .append(" ") - .append(httpException.getResponse().getBodyAsString()); - } else { - builder.append(e.getCause().getMessage()); - } - - return logger.logExceptionAsError(new SerializationException(builder.toString(), e)); - } else { - return logger.logExceptionAsError(new SerializationException(e.getMessage(), e)); - } }); +// .onErrorMap(e -> { +// if (e instanceof SchemaRegistryClientException) { +// StringBuilder builder = new StringBuilder( +// String.format("Failed to retrieve schema for id %s", schemaId)); +// +// if (e.getCause() instanceof HttpResponseException) { +// HttpResponseException httpException = (HttpResponseException) e.getCause(); +// builder.append("HTTP ") +// .append(httpException.getResponse().getStatusCode()) +// .append(" ") +// .append(httpException.getResponse().getBodyAsString()); +// } else { +// builder.append(e.getCause().getMessage()); +// } +// +// return logger.logExceptionAsError(new SerializationException(builder.toString(), e)); +// } else { +// return logger.logExceptionAsError(new SerializationException(e.getMessage(), e)); +// } +// }); }); } @@ -241,15 +234,14 @@ protected Mono deserialize(InputStream s) { * * @param registryObject object returned from CachedSchemaRegistryAsyncClient, contains schema type * @return Codec to be used to deserialize encoded payload bytes - * @throws SerializationException if decoder for the required schema type has not been loaded */ - private SchemaRegistryCodec getDeserializerCodec(SchemaRegistryObject registryObject) throws SerializationException { - SchemaRegistryCodec schemaRegistryCodec = deserializerCodecMap.get(registryObject.getSchemaType()); + private SchemaRegistryCodec getDeserializerCodec(SchemaRegistryObject registryObject) { + SchemaRegistryCodec schemaRegistryCodec = deserializerCodecMap.get(registryObject.getSerializationType()); if (schemaRegistryCodec == null) { throw logger.logExceptionAsError( - new SerializationException( + new NullPointerException( String.format("No deserializer codec class found for schema type '%s'.", - registryObject.getSchemaType()) + registryObject.getSerializationType()) )); } return schemaRegistryCodec; @@ -258,15 +250,10 @@ private SchemaRegistryCodec getDeserializerCodec(SchemaRegistryObject registryOb /** * @param buffer full payload bytes * @return String representation of schema ID - * @throws SerializationException if schema ID could not be extracted from payload */ - private String getSchemaIdFromPayload(ByteBuffer buffer) throws SerializationException { + private String getSchemaIdFromPayload(ByteBuffer buffer) { byte[] schemaGuidByteArray = new byte[SchemaRegistrySerializer.SCHEMA_ID_SIZE]; - try { - buffer.get(schemaGuidByteArray); - } catch (BufferUnderflowException e) { - throw logger.logExceptionAsError(new SerializationException("Payload too short, no readable guid.", e)); - } + buffer.get(schemaGuidByteArray); return new String(schemaGuidByteArray, StandardCharsets.UTF_8); } @@ -279,18 +266,17 @@ private String getSchemaIdFromPayload(ByteBuffer buffer) throws SerializationExc * @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 + * @param serializationType type of schema being stored, e.g. avro * @return string representation of schema ID - * @throws SchemaRegistryClientException upon registry client operation failure */ private Mono maybeRegisterSchema( - String schemaGroup, String schemaName, String schemaString, String schemaType) { + String schemaGroup, String schemaName, String schemaString, SerializationType serializationType) { if (this.autoRegisterSchemas) { - return this.schemaRegistryClient.registerSchema(schemaGroup, schemaName, schemaString, schemaType) + return this.schemaRegistryClient.registerSchema(schemaGroup, schemaName, schemaString, serializationType) .map(SchemaRegistryObject::getSchemaId); } else { return this.schemaRegistryClient.getSchemaId( - schemaGroup, schemaName, schemaString, schemaType); + schemaGroup, schemaName, schemaString, serializationType); } } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryClientException.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryClientException.java deleted file mode 100644 index 474c0f059996b..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/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.models; - -import com.azure.core.exception.AzureException; - -/** - * Runtime exception to be returned from CachedSchemaRegistryClient implementations. - */ -public class SchemaRegistryClientException extends AzureException { - /** - * @param s error message returned from schema registry client - */ - public SchemaRegistryClientException(String s) { - super(s); - } - - /** - * @param s error message returned from schema registry client - * @param cause Throwable cause of the exception - */ - public SchemaRegistryClientException(String s, Throwable cause) { - super(s, cause); - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryObject.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryObject.java index 97eeb5df19064..c049c14f7202e 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryObject.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryObject.java @@ -4,18 +4,17 @@ package com.azure.data.schemaregistry.models; import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.CachedSchemaRegistryAsyncClient; import java.nio.charset.StandardCharsets; import java.util.function.Function; /** * Stores all relevant information returned from CachedSchemaRegistryClient layer. */ -public class SchemaRegistryObject { +public final class SchemaRegistryObject { private final ClientLogger logger = new ClientLogger(SchemaRegistryObject.class); private final String schemaId; - private final String schemaType; + private final SerializationType serializationType; private final Function parseMethod; private final byte[] schemaBytes; private final String schemaName; @@ -27,19 +26,19 @@ public class SchemaRegistryObject { * Initializes SchemaRegistryObject instance. * * @param schemaId schema ID - * @param schemaType type of schema, e.g. avro, json + * @param serializationType 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, + SerializationType serializationType, String schemaName, String schemaGroup, byte[] schemaByteArray, Function parseMethod) { this.schemaId = schemaId; - this.schemaType = schemaType; + this.serializationType = serializationType; this.schemaBytes = schemaByteArray.clone(); this.deserialized = null; this.parseMethod = parseMethod; @@ -57,8 +56,8 @@ public String getSchemaId() { /** * @return schema type associated with the schema payload */ - public String getSchemaType() { - return schemaType; + public SerializationType getSerializationType() { + return serializationType; } public String getSchemaGroup() { @@ -82,11 +81,7 @@ public Object getSchema() { 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)); - } + this.deserialized = parseMethod.apply(schemaString); } return deserialized; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SerializationException.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SerializationException.java deleted file mode 100644 index 52f0aa20284d9..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/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.models; - -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 serialization/deserialization operation failure - */ - public SerializationException(String s) { - super(s); - } - - /** - * @param s error message explaining serialization/deserialization operation failure - * @param cause Throwable failure cause - */ - public SerializationException(String s, Throwable cause) { - super(s, cause); - } -} 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..392082268e07c --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SerializationType.java @@ -0,0 +1,13 @@ +package com.azure.data.schemaregistry.models; + +import com.azure.core.util.ExpandableStringEnum; + +public class SerializationType extends ExpandableStringEnum { + + public static final SerializationType AVRO = fromString("avro"); + public static final SerializationType JSON = fromString("json"); + + public static SerializationType fromString(String name) { + return fromString(name, SerializationType.class); + } +} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java index 6c823740d66f2..2ba4dc7dfbe76 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java @@ -3,7 +3,7 @@ package com.azure.data.schemaregistry; -import com.azure.data.schemaregistry.models.SerializationException; +import com.azure.data.schemaregistry.models.SerializationType; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -12,7 +12,7 @@ public class SampleSchemaRegistryCodec implements SchemaRegistryCodec { public SampleSchemaRegistryCodec() { } @Override - public String getSchemaName(Object object) throws SerializationException { + public String getSchemaName(Object object) { return "schema name"; } @@ -27,7 +27,7 @@ public String getSchemaString(Object object) { } @Override - public byte[] encode(Object object) throws SerializationException { + public byte[] encode(Object object) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { outputStream.write("sample payload".getBytes()); @@ -35,14 +35,14 @@ public byte[] encode(Object object) throws SerializationException { outputStream.close(); } catch (IOException e) { e.printStackTrace(); - throw new SerializationException("this should never happen", e); + throw new IllegalStateException("this should never happen", e); } return outputStream.toByteArray(); } @Override - public String getSchemaType() { - return "test"; + public SerializationType getSerializationType() { + return SerializationType.fromString("test"); } @Override @@ -53,7 +53,7 @@ public String parseSchemaString(String s) { public static final String CONSTANT_PAYLOAD = "sample payload!"; @Override - public Object decode(byte[] bytes, Object o) throws SerializationException { + public Object decode(byte[] bytes, Object o) { return CONSTANT_PAYLOAD; } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClientTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClientTest.java similarity index 85% rename from sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClientTest.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClientTest.java index c7e31a1f5ca21..90e2f809abf44 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/CachedSchemaRegistryAsyncClientTest.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClientTest.java @@ -3,36 +3,42 @@ package com.azure.data.schemaregistry; +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.Mockito.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; + +import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestService; import com.azure.data.schemaregistry.implementation.models.CreateSchemaResponse; import com.azure.data.schemaregistry.implementation.models.GetIdBySchemaContentResponse; import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdHeaders; import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdResponse; import com.azure.data.schemaregistry.implementation.models.SchemaId; -import com.azure.data.schemaregistry.models.SchemaRegistryClientException; import com.azure.data.schemaregistry.models.SchemaRegistryObject; -import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestService; +import com.azure.data.schemaregistry.models.SerializationType; +import java.util.HashMap; +import java.util.concurrent.ConcurrentSkipListMap; +import java.util.function.Function; 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 SchemaRegistryAsyncClientTest { -public class CachedSchemaRegistryAsyncClientTest { - private static final String MOCK_SERIALIZATION = "mock_serialization_type"; + private static final SerializationType MOCK_SERIALIZATION = 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 CachedSchemaRegistryAsyncClient client; + private SchemaRegistryAsyncClient client; private AzureSchemaRegistryRestService restService; private HashMap guidCache; private HashMap schemaStringCache; @@ -44,10 +50,10 @@ protected void setUp() { this.schemaStringCache = new HashMap(); this.typeParserDictionary = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); - this.typeParserDictionary.put(MOCK_SERIALIZATION, (s) -> s); + this.typeParserDictionary.put(MOCK_SERIALIZATION.toString(), (s) -> s); this.restService = mock(AzureSchemaRegistryRestService.class); - this.client = new CachedSchemaRegistryAsyncClient( + this.client = new SchemaRegistryAsyncClient( this.restService, this.guidCache, this.schemaStringCache, @@ -80,7 +86,7 @@ public void testRegisterThenSchemaCacheHit() throws Exception { client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); verify(restService, times(1)) - .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION, MOCK_AVRO_SCHEMA); + .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION.toString(), MOCK_AVRO_SCHEMA); } @Test @@ -109,7 +115,7 @@ public void testGetGuidThenSchemaCacheHit() throws Exception { public void testGetSchemaThenGuidCacheHit() throws Exception { String mockId = "mock-id---"; GetSchemaByIdHeaders mockHeaders = new GetSchemaByIdHeaders(); - mockHeaders.setXSchemaType(MOCK_SERIALIZATION); + mockHeaders.setXSchemaType(MOCK_SERIALIZATION.toString()); when(restService.getSchemaByIdWithResponseAsync(mockId)) .thenReturn( Mono.just(new GetSchemaByIdResponse( @@ -151,14 +157,14 @@ public void testClientReset() throws Exception { assertEquals(0, schemaStringCache.size()); assertEquals(0, this.typeParserDictionary.size()); - this.typeParserDictionary.put(MOCK_SERIALIZATION, (s) -> s); + 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(restService, times(2)) - .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION, MOCK_AVRO_SCHEMA); + .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION.toString(), MOCK_AVRO_SCHEMA); } @Test @@ -178,9 +184,9 @@ public void testBadRegisterRequestThenThrows() { "doesn't matter", "doesn't matter", "doesn't matter", - "doesn't matter").block(); + SerializationType.fromString("doesn't matter")).block(); fail("Should throw on 400 status code"); - } catch (SchemaRegistryClientException e) { + } catch (IllegalStateException e) { assert true; } @@ -206,9 +212,9 @@ public void testGetIdBySchemaContentNotFoundThenThrows() { "doesn't matter", "doesn't matter", "doesn't matter", - "doesn't matter").block(); + SerializationType.fromString("doesn't matter")).block(); fail("Should throw on 404 status code"); - } catch (SchemaRegistryClientException e) { + } catch (IllegalStateException e) { assert true; } @@ -231,7 +237,7 @@ public void testGetSchemaByIdNotFoundThenThrows() { try { client.getSchema(mockId).block(); fail("Should have thrown on 404 status code"); - } catch (SchemaRegistryClientException e) { + } catch (IllegalStateException e) { assert true; } catch (Exception e){ assert false; diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java index 0b5cd210676bc..a43eb08d9912b 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java @@ -3,9 +3,8 @@ package com.azure.data.schemaregistry; -import com.azure.data.schemaregistry.models.SchemaRegistryClientException; import com.azure.data.schemaregistry.models.SchemaRegistryObject; -import com.azure.data.schemaregistry.models.SerializationException; +import com.azure.data.schemaregistry.models.SerializationType; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericDatumWriter; @@ -25,6 +24,7 @@ import java.util.Arrays; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -39,7 +39,7 @@ public void testRegistryGuidPrefixedToPayload() { // manually add SchemaRegistryObject into mock registry client cache SampleSchemaRegistryCodec encoder = new SampleSchemaRegistryCodec(); SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, - encoder.getSchemaType(), + encoder.getSerializationType(), encoder.getSchemaName(null), encoder.getSchemaGroup(), encoder.getSchemaString(null).getBytes(), // always returns same schema string @@ -47,22 +47,19 @@ public void testRegistryGuidPrefixedToPayload() { assertEquals(encoder.getSchemaString(null), registered.getSchema()); - CachedSchemaRegistryAsyncClient mockRegistryClient = getMockClient(); - Mockito.when(mockRegistryClient.getSchemaId(anyString(), anyString(), anyString(), anyString())) + SchemaRegistryAsyncClient mockRegistryClient = getMockClient(); + Mockito.when(mockRegistryClient.getSchemaId(anyString(), anyString(), anyString(), + any(SerializationType.class))) .thenReturn(Mono.just(encoder.getSchemaString(null))); TestDummySerializer serializer = new TestDummySerializer( mockRegistryClient, false); try { - ByteArrayOutputStream payload = serializer.serialize(new ByteArrayOutputStream(), 1).block(); + ByteArrayOutputStream payload = serializer.serializeAsync(new ByteArrayOutputStream(), 1).block(); ByteBuffer buffer = ByteBuffer.wrap(payload.toByteArray()); byte[] schemaGuidByteArray = new byte[SchemaRegistrySerializer.SCHEMA_ID_SIZE]; - try { - buffer.get(schemaGuidByteArray); - } catch (BufferUnderflowException e) { - throw new SerializationException("Payload too short, no readable guid.", e); - } + buffer.get(schemaGuidByteArray); // guid should match preloaded SchemaRegistryObject guid assertEquals(MOCK_GUID, new String(schemaGuidByteArray)); @@ -71,7 +68,7 @@ public void testRegistryGuidPrefixedToPayload() { int length = buffer.limit() - SchemaRegistrySerializer.SCHEMA_ID_SIZE; byte[] encodedBytes = Arrays.copyOfRange(buffer.array(), start, start + length); assertTrue(Arrays.equals(encoder.encode(null), encodedBytes)); - } catch (SerializationException e) { + } catch (RuntimeException e) { e.printStackTrace(); fail(); } @@ -84,9 +81,9 @@ public void testNullPayloadThrowsSerializationException() { false); try { - serializer.serialize(new ByteArrayOutputStream(), null).block(); - fail("Serializing null payload failed to throw SerializationException"); - } catch (SerializationException e) { + serializer.serializeAsync(new ByteArrayOutputStream(), null).block(); + fail("Serializing null payload failed to throw NullPointerException"); + } catch (NullPointerException e) { assertTrue(true); } } @@ -106,13 +103,13 @@ public void testIfRegistryNullThenThrow() { } @Test - public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientException, SerializationException { + public void testAddDeserializerCodec() throws IOException { // add sample codec impl and test that it is used for decoding payload SampleSchemaRegistryCodec decoder = new SampleSchemaRegistryCodec(); // manually add SchemaRegistryObject to cache SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, - decoder.getSchemaType(), + decoder.getSerializationType(), decoder.getSchemaName(null), decoder.getSchemaGroup(), MOCK_AVRO_SCHEMA_STRING.getBytes(), @@ -120,7 +117,7 @@ public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientE assertTrue(registered.getSchema() != null); - CachedSchemaRegistryAsyncClient mockClient = getMockClient(); + SchemaRegistryAsyncClient mockClient = getMockClient(); Mockito.when(mockClient.getSchema(anyString())) .thenReturn(Mono.just(registered)); @@ -130,21 +127,21 @@ public void testAddDeserializerCodec() throws IOException, SchemaRegistryClientE assertEquals(MOCK_GUID, serializer.schemaRegistryClient.getSchema(MOCK_GUID).block().getSchemaId()); - serializer.deserialize(new ByteArrayInputStream(getPayload())) + serializer.deserializeAsync(new ByteArrayInputStream(getPayload())) .subscribe(unused -> { System.out.println(unused); }, ex -> System.out.println(ex)); assertEquals(SampleSchemaRegistryCodec.CONSTANT_PAYLOAD, - serializer.deserialize(new ByteArrayInputStream(getPayload())).block()); + serializer.deserializeAsync(new ByteArrayInputStream(getPayload())).block()); } @Test - public void testNullPayload() throws SchemaRegistryClientException, SerializationException { + public void testNullPayload() { TestDummySerializer deserializer = new TestDummySerializer( getMockClient(), true); - assertNull(deserializer.deserialize(null).block()); + assertNull(deserializer.deserializeAsync(null).block()); } @Test @@ -153,9 +150,9 @@ public void testIfTooShortPayloadThrow() { getMockClient(), true); try { - serializer.deserialize(new ByteArrayInputStream("bad payload".getBytes())).block(); - fail("Too short payload did not throw SerializationException"); - } catch (SerializationException e) { + serializer.deserializeAsync(new ByteArrayInputStream("bad payload".getBytes())).block(); + fail("Too short payload did not throw BufferUnderflowException"); + } catch (BufferUnderflowException e) { assertTrue(true); } } @@ -172,8 +169,8 @@ public void testIfRegistryClientNullOnBuildThrow() { } } - private CachedSchemaRegistryAsyncClient getMockClient() { - return mock(CachedSchemaRegistryAsyncClient.class); + private SchemaRegistryAsyncClient getMockClient() { + return mock(SchemaRegistryAsyncClient.class); } private byte[] getPayload() throws IOException { 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 index 1a293d63d8c01..86ad29a7e45bc 100644 --- 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 @@ -7,7 +7,7 @@ public class TestDummySerializer extends SchemaRegistrySerializer { TestDummySerializer( - CachedSchemaRegistryAsyncClient mockClient, + SchemaRegistryAsyncClient mockClient, boolean autoRegisterSchemas) { super(mockClient, new SampleSchemaRegistryCodec(), Collections.singletonList(new SampleSchemaRegistryCodec())); From 0c820c5ffadabdb7124e50834c9c24ae11abde9f Mon Sep 17 00:00:00 2001 From: Srikanta Date: Wed, 9 Sep 2020 15:43:37 -0700 Subject: [PATCH 12/17] Schema registry changes with new APIs --- .../checkstyle/checkstyle-suppressions.xml | 1 + ...odec.java => AvroSchemaRegistryUtils.java} | 67 ++--- .../avro/SchemaRegistryAvroSerializer.java | 148 +++++++-- .../SchemaRegistryAvroSerializerBuilder.java | 73 +---- .../SchemaRegistryAsyncClient.java | 206 ++++++------- .../schemaregistry/SchemaRegistryClient.java | 88 +++++- .../SchemaRegistryClientBuilder.java | 32 +- .../schemaregistry/SchemaRegistryCodec.java | 60 ---- .../SchemaRegistrySerializer.java | 282 ------------------ .../models/SchemaRegistryObject.java | 89 ------ .../models/SchemaRegistryProperties.java | 75 +++++ .../models/SerializationType.java | 13 +- .../data/schemaregistry/package-info.java | 2 +- .../SampleSchemaRegistryCodec.java | 59 ---- .../SchemaRegistryAsyncClientTest.java | 16 +- .../SchemaRegistrySerializerTest.java | 195 ------------ .../schemaregistry/TestDummySerializer.java | 17 -- 17 files changed, 431 insertions(+), 992 deletions(-) rename sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/{AvroSchemaRegistryCodec.java => AvroSchemaRegistryUtils.java} (72%) delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryCodec.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryObject.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryProperties.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummySerializer.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 b572d64f95b8c..14d3ade49f4b4 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 @@ -420,6 +420,7 @@ + T decode(byte[] b, byte[] schemaBytes) { + Objects.requireNonNull(schemaBytes, "Schema must not be null."); - if (!(object instanceof Schema)) { - throw logger.logExceptionAsError( - new IllegalStateException("Object must be an Avro schema.")); - } - Schema schema = (Schema) object; + String schemaString = new String(schemaBytes, StandardCharsets.UTF_8); + Schema schemaObject = parseSchemaString(schemaString); - if (schema.getType().equals(Schema.Type.BYTES)) { - return b; - } - - DatumReader reader = getDatumReader(schema); + DatumReader reader = getDatumReader(schemaObject); try { - Object result = reader.read(null, DECODER_FACTORY.binaryDecoder(b, null)); - - if (schema.getType().equals(Schema.Type.STRING)) { - return result.toString(); - } - + T result = reader.read(null, DECODER_FACTORY.binaryDecoder(b, null)); return result; } catch (IOException | RuntimeException e) { - // avro deserialization may throw AvroRuntimeException, NullPointerException, etc throw logger.logExceptionAsError(new IllegalStateException("Error deserializing Avro message.", e)); } } @@ -158,7 +141,7 @@ public Object decode(byte[] b, Object object) { * @param writerSchema Avro schema fetched from schema registry store * @return correct Avro DatumReader object given encoder configuration */ - private DatumReader getDatumReader(Schema writerSchema) { + private DatumReader getDatumReader(Schema writerSchema) { boolean writerSchemaIsPrimitive = AvroSchemaUtils.getPrimitiveSchemas().values().contains(writerSchema); // do not use SpecificDatumReader if writerSchema is a primitive if (avroSpecificReader && !writerSchemaIsPrimitive) { 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 408b7885eba10..0fc0ac0a43f50 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 @@ -6,65 +6,155 @@ import com.azure.core.experimental.serializer.ObjectSerializer; import com.azure.core.experimental.serializer.TypeReference; import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.SchemaRegistrySerializer; import com.azure.data.schemaregistry.SchemaRegistryAsyncClient; +import com.azure.data.schemaregistry.models.SchemaRegistryProperties; +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.util.Collections; +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; /** - * Asynchronous registry-based serializer implementation. + * Schema Registry-based serializer implementation for Avro data format. */ -public final class SchemaRegistryAvroSerializer extends SchemaRegistrySerializer implements ObjectSerializer { +public final class SchemaRegistryAvroSerializer implements ObjectSerializer { private final ClientLogger logger = new ClientLogger(SchemaRegistryAvroSerializer.class); - /** - * - * @param registryClient - * @param codec - * @param schemaGroup - * @param autoRegisterSchemas - */ - SchemaRegistryAvroSerializer(SchemaRegistryAsyncClient registryClient, AvroSchemaRegistryCodec codec, + static final int SCHEMA_ID_SIZE = 32; + private final SchemaRegistryAsyncClient schemaRegistryClient; + private final AvroSchemaRegistryUtils codec; + private final String schemaGroup; + private final Boolean autoRegisterSchemas; + + SchemaRegistryAvroSerializer(SchemaRegistryAsyncClient registryClient, AvroSchemaRegistryUtils codec, String schemaGroup, Boolean autoRegisterSchemas) { - super(registryClient, codec, Collections.singletonList(codec), autoRegisterSchemas, schemaGroup); + this.schemaRegistryClient = registryClient; + this.codec = codec; + this.schemaGroup = schemaGroup; + this.autoRegisterSchemas = autoRegisterSchemas; } @Override public T deserialize(InputStream stream, TypeReference typeReference) { - return null; + return deserializeAsync(stream, typeReference).block(); } @Override public Mono deserializeAsync(InputStream stream, TypeReference typeReference) { - return null; + + 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 S serialize(S stream, Object value) { - return null; + return serializeAsync(stream, value).block(); } @Override - public Mono serializeAsync(S stream, Object object) { + public Mono serializeAsync(S outputStream, Object object) { + if (object == null) { - return Mono.empty(); + return monoError(logger, new NullPointerException( + "Null object, behavior should be defined in concrete serializer implementation.")); } - return super.serializeAsync(stream, object); + 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)); + } catch (IOException e) { + sink.error(new UncheckedIOException(e.getMessage(), e)); + } + sink.next(outputStream); + }); } -// @Override -// public Mono deserialize(InputStream stream, Class clazz) { -// return this.deserialize(stream) -// .map(o -> { -// if (clazz.isInstance(o)) { -// return clazz.cast(o); -// } -// throw logger.logExceptionAsError(new IllegalStateException("Deserialized object not of class %s")); -// }); -// } + /** + * @param buffer full payload bytes + * @return String representation of schema ID + */ + 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(SchemaRegistryProperties::getSchemaId); + } else { + + return this.schemaRegistryClient.getSchemaId( + schemaGroup, schemaName, schemaString, SerializationType.AVRO); + } + } } 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 785579fc90015..9aed8f97d529f 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,49 +3,26 @@ 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 java.util.Objects; /** - * Builder implemenation for building {@link SchemaRegistryAvroSerializer} and {@link SchemaRegistryAvroSerializer} + * Builder implementation for building {@link SchemaRegistryAvroSerializer} and {@link SchemaRegistryAvroSerializer} */ public final class SchemaRegistryAvroSerializerBuilder { - private String registryUrl; - private TokenCredential credential; private Boolean autoRegisterSchemas; - private String schemaGroup; - private Integer maxCacheSize; private Boolean avroSpecificReader; + private SchemaRegistryAsyncClient schemaRegistryAsyncClient; + private String schemaGroup; /** * Instantiates instance of Builder class. * Supplies client defaults. */ public SchemaRegistryAvroSerializerBuilder() { - this.registryUrl = null; - this.credential = null; this.autoRegisterSchemas = null; - this.schemaGroup = null; - this.maxCacheSize = null; this.avroSpecificReader = false; } - /** - * 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; - } - /** * Specifies schema group for interacting with Azure Schema Registry service. * @@ -60,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. @@ -97,42 +64,28 @@ public SchemaRegistryAvroSerializerBuilder avroSpecificReader(boolean avroSpecif return this; } + /** - * Specifies maximum schema object cache size for underlying CachedSchemaRegistryAsyncClient. If specified cache - * size is exceeded, all caches are recycled. - * - * @param maxCacheSize maximum number of schemas per cache - * @return updated {@link SchemaRegistryAvroSerializerBuilder} instance + * The {@link SchemaRegistryAsyncClient} to use to interact with the Schema Registry service. + * @param schemaRegistryAsyncClient The {@link SchemaRegistryAsyncClient}. + * @return updated {@link SchemaRegistryAvroSerializerBuilder} instance. */ - public SchemaRegistryAvroSerializerBuilder maxCacheSize(int maxCacheSize) { - this.maxCacheSize = maxCacheSize; + public SchemaRegistryAvroSerializerBuilder schemaRegistryAsyncClient( + SchemaRegistryAsyncClient schemaRegistryAsyncClient) { + this.schemaRegistryAsyncClient = schemaRegistryAsyncClient; return this; } - /** - * Instantiates SchemaRegistry + * Instantiates SchemaRegistry avro serializer. * @return {@link SchemaRegistryAvroSerializer} instance * * @throws NullPointerException if parameters are incorrectly set. * @throws IllegalArgumentException if credential is not set. */ public SchemaRegistryAvroSerializer buildSerializer() { - SchemaRegistryClientBuilder builder = new SchemaRegistryClientBuilder() - .endpoint(registryUrl) - .credential(credential); - - if (maxCacheSize != null) { - builder.maxCacheSize(maxCacheSize); - } - - AvroSchemaRegistryCodec codec = new AvroSchemaRegistryCodec(this.avroSpecificReader); - - SchemaRegistryAsyncClient client = builder - .addSchemaRegistryCodec(codec) - .buildAsyncClient(); - - return new SchemaRegistryAvroSerializer(client, codec, this.schemaGroup, + AvroSchemaRegistryUtils codec = new AvroSchemaRegistryUtils(this.avroSpecificReader); + return new SchemaRegistryAvroSerializer(schemaRegistryAsyncClient, codec, this.schemaGroup, this.autoRegisterSchemas); } } 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 index fa7a5456ea57f..2242e9a054527 100644 --- 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 @@ -12,8 +12,9 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestService; import com.azure.data.schemaregistry.implementation.models.SchemaId; -import com.azure.data.schemaregistry.models.SchemaRegistryObject; +import com.azure.data.schemaregistry.models.SchemaRegistryProperties; import com.azure.data.schemaregistry.models.SerializationType; + import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Map; @@ -21,27 +22,14 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Function; + import reactor.core.publisher.Mono; /** * 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 SchemaRegistryClientBuilder#maxCacheSize(int)}, 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 SchemaRegistryClientBuilder Follows builder pattern for object instantiation */ -@ServiceClient( - builder = SchemaRegistryClientBuilder.class, - serviceInterfaces = AzureSchemaRegistryRestService.class) +@ServiceClient(builder = SchemaRegistryClientBuilder.class, isAsync = true) public final class SchemaRegistryAsyncClient { private final ClientLogger logger = new ClientLogger(SchemaRegistryAsyncClient.class); @@ -53,8 +41,8 @@ public final class SchemaRegistryAsyncClient { private final AzureSchemaRegistryRestService restService; private final Integer maxSchemaMapSize; private final ConcurrentSkipListMap> typeParserMap; - private final Map idCache; - private final Map schemaStringCache; + private final Map idCache; + private final Map schemaStringCache; SchemaRegistryAsyncClient( AzureSchemaRegistryRestService restService, @@ -70,8 +58,8 @@ public final class SchemaRegistryAsyncClient { // testing - todo remove constructor and replace with mock SchemaRegistryAsyncClient( AzureSchemaRegistryRestService restService, - Map idCache, - Map schemaStringCache, + Map idCache, + Map schemaStringCache, ConcurrentSkipListMap> typeParserMap) { this.restService = restService; // mockable this.idCache = idCache; @@ -80,8 +68,17 @@ public final class SchemaRegistryAsyncClient { 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 SchemaRegistryProperties} of a successfully registered schema. + */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono registerSchema( + public Mono registerSchema( String schemaGroup, String schemaName, String schemaString, SerializationType serializationType) { if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { @@ -96,57 +93,67 @@ public Mono registerSchema( .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) { + 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) { + 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 - .createSchemaWithResponseAsync(schemaGroup, schemaName, serializationType.toString(), schemaString) -// .onErrorMap(HttpResponseException.class, e -> logger.logExceptionAsError( -// new SchemaRegistryClientException("Register operation failed, unexpected service response.", e))) - .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(); - - SchemaRegistryObject registered = new SchemaRegistryObject(schemaId.getId(), - serializationType, - schemaName, - schemaGroup, - schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), - getParseFunc(serializationType)); - - 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); - }); + return this.restService + .createSchemaWithResponseAsync(schemaGroup, schemaName, serializationType.toString(), 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(); + + SchemaRegistryProperties registered = new SchemaRegistryProperties(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 SchemaRegistryProperties} associated with the given {@code schemaId}. + */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchema(String schemaId) { + public Mono getSchema(String schemaId) { if (idCache.containsKey(schemaId)) { logger.verbose("Cache hit for schema id '{}'", schemaId); return Mono.fromCallable(() -> idCache.get(schemaId)); @@ -154,17 +161,21 @@ public Mono getSchema(String 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 SchemaRegistryProperties} associated with the given {@code schemaId} along with the HTTP + * response. + */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSchemaWithResponse(String schemaId) { + public Mono> getSchemaWithResponse(String schemaId) { return getSchemaWithResponse(schemaId, Context.NONE); } - Mono> getSchemaWithResponse(String schemaId, Context context) { + Mono> getSchemaWithResponse(String schemaId, Context context) { Objects.requireNonNull(schemaId, "'schemaId' should not be null"); return this.restService.getSchemaByIdWithResponseAsync(schemaId) -// .onErrorMap(HttpResponseException.class, -// e -> logger.logExceptionAsError( -// new SchemaRegistryClientException("Fetching schema failed, unexpected service response.", e))) .handle((response, sink) -> { if (response == null) { sink.error(logger.logExceptionAsError( @@ -181,53 +192,63 @@ Mono> getSchemaWithResponse(String schemaId, Cont SerializationType serializationType = SerializationType.fromString(response.getDeserializedHeaders().getXSchemaType()); - SchemaRegistryObject schemaObject = new SchemaRegistryObject(schemaId, + SchemaRegistryProperties schemaObject = new SchemaRegistryProperties(schemaId, serializationType, null, - null, - response.getValue().getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), - getParseFunc(serializationType)); + response.getValue().getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING)); resetIfNeeded(); idCache.putIfAbsent(schemaId, schemaObject); logger.verbose("Cached schema object. Path: '{}'", schemaId); - SimpleResponse schemaRegistryObjectSimpleResponse = new SimpleResponse<>( + 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) { + SerializationType serializationType) { - if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { + 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(schemaString).getSchemaId()); + 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) { + SerializationType serializationType) { return getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, serializationType, Context.NONE); } Mono> getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, - SerializationType serializationType, Context context) { + SerializationType serializationType, Context context) { return this.restService .getIdBySchemaContentWithResponseAsync(schemaGroup, schemaName, serializationType.toString(), schemaString) -// .onErrorMap(HttpResponseException.class, e -> -// logger.logExceptionAsError(new SchemaRegistryClientException(String.format( -// "Failed to fetch ID for schema, unexpected service response. Group: '%s', name: '%s'", -// schemaGroup, schemaName), e))) .handle((response, sink) -> { if (response == null) { sink.error(logger.logExceptionAsError( @@ -246,13 +267,11 @@ Mono> getSchemaIdWithResponse(String schemaGroup, String schema resetIfNeeded(); schemaStringCache.putIfAbsent( getSchemaStringCacheKey(schemaGroup, schemaName, schemaString), - new SchemaRegistryObject( + new SchemaRegistryProperties( schemaId.getId(), serializationType, schemaName, - schemaGroup, - schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING), - getParseFunc(serializationType))); + schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING))); logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); SimpleResponse schemaIdResponse = new SimpleResponse<>( @@ -288,23 +307,6 @@ private void resetIfNeeded() { } } - /** - * Return stored parse function for parsing schema payloads of specified schema type - * - * @param serializationType schema type of payload to be deserialized - * @return parse method for deserializing schema string - */ - private Function getParseFunc(SerializationType serializationType) { - Function parseFunc = typeParserMap.get(serializationType); - - if (parseFunc == null) { - throw logger.logExceptionAsError(new NullPointerException( - String.format("Unexpected serialization type '%s' received. Currently loaded parsers: %s", - serializationType, typeParserMap.keySet().toString()))); - } - return parseFunc; - } - 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 index 480c8c94ebb41..e831d1d7d04ab 100644 --- 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 @@ -1,3 +1,6 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + package com.azure.data.schemaregistry; import com.azure.core.annotation.ReturnType; @@ -5,13 +8,15 @@ import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; -import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestService; -import com.azure.data.schemaregistry.models.SchemaRegistryObject; +import com.azure.data.schemaregistry.models.SchemaRegistryProperties; import com.azure.data.schemaregistry.models.SerializationType; -@ServiceClient( - builder = SchemaRegistryClientBuilder.class, - serviceInterfaces = AzureSchemaRegistryRestService.class) +/** + * 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; @@ -19,39 +24,90 @@ public final class SchemaRegistryClient { 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 SchemaRegistryObject registerSchema(String schemaGroup, String schemaName, String schemaString, - SerializationType schemaType) { - return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, schemaType, Context.NONE).getValue(); + public SchemaRegistryProperties 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) { + 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 SchemaRegistryProperties} associated with the given {@code schemaId}. + */ @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaRegistryObject getSchema(String schemaId) { + public SchemaRegistryProperties 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 SchemaRegistryProperties} associated with the given {@code schemaId} along with the HTTP + * response. + */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSchemaWithResponse(String schemaId, Context context) { + 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(); + 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(); + return this.asyncClient + .getSchemaIdWithResponse(schemaGroup, schemaName, schemaString, serializationType, context).block(); } void clearCache() { diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java index 9e9eb0afe814b..8a178e9fe0f2b 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java @@ -208,34 +208,6 @@ public SchemaRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) { 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.Codec 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 schemaRegistryCodec Codec class implementation - * @return The updated {@link SchemaRegistryClientBuilder} object. - */ - public SchemaRegistryClientBuilder addSchemaRegistryCodec(SchemaRegistryCodec schemaRegistryCodec) { - Objects.requireNonNull(schemaRegistryCodec, "'codec' cannot be null."); - if (schemaRegistryCodec.getSerializationType() == null) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Serialization type cannot be null or empty.")); - } - if (this.typeParserMap.containsKey(schemaRegistryCodec.getSerializationType())) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Multiple parse methods for single serialization type may not be added.")); - } - this.typeParserMap.put(schemaRegistryCodec.getSerializationType().toString(), - schemaRegistryCodec::parseSchemaString); - return this; - } - /** * 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. @@ -302,7 +274,7 @@ public SchemaRegistryAsyncClient buildAsyncClient() { * * @return {@link SchemaRegistryClient} with the options set from the builder. */ - public SchemaRegistryClient buildClient() { + public SchemaRegistryClient buildClient() { return new SchemaRegistryClient(this.buildAsyncClient()); - } + } } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryCodec.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryCodec.java deleted file mode 100644 index 6abad206e9f8f..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryCodec.java +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.data.schemaregistry.models.SerializationType; - -/** - * An interface defining operations required for registry-based serialization and deserialization. - */ -public interface SchemaRegistryCodec { - /** - * @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. - */ - SerializationType getSerializationType(); - - /** - * 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); - - /** - * 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 - */ - String getSchemaName(Object object); - - String getSchemaGroup(); - - /** - * 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 - */ - String getSchemaString(Object object); - - /** - * 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 - */ - byte[] encode(Object object); - - /** - * 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 - */ - Object decode(byte[] encodedBytes, Object schemaObject); -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java deleted file mode 100644 index 852e03727b1d1..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistrySerializer.java +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import static com.azure.core.util.FluxUtil.monoError; - -import com.azure.core.util.logging.ClientLogger; -import com.azure.data.schemaregistry.models.SchemaRegistryObject; -import com.azure.data.schemaregistry.models.SerializationType; -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 java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentSkipListMap; -import reactor.core.publisher.Mono; - -/** - * Common implementation for all registry-based serializers. - */ -public abstract class SchemaRegistrySerializer { - private final ClientLogger logger = new ClientLogger(SchemaRegistrySerializer.class); - - static final Boolean AUTO_REGISTER_SCHEMAS_DEFAULT = false; - static final String SCHEMA_GROUP_DEFAULT = "$default"; - static final int SCHEMA_ID_SIZE = 32; - - SchemaRegistryAsyncClient schemaRegistryClient; - - private SchemaRegistryCodec serializerSchemaRegistryCodec; - private final Map deserializerCodecMap = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); - private SerializationType serializationType; - - Boolean autoRegisterSchemas = SchemaRegistrySerializer.AUTO_REGISTER_SCHEMAS_DEFAULT; - String schemaGroup = SchemaRegistrySerializer.SCHEMA_GROUP_DEFAULT; - - /** - * Constructor for AbstractSchemaRegistrySerializer implementations. - * - * @param schemaRegistryClient client to be used for interfacing with Schema Registry service - * @param serializerSchemaRegistryCodec Codec to be used for serialization operations - * @param deserializerSchemaRegistryCodecList list of Codecs to be used to deserialize incoming payloads - */ - public SchemaRegistrySerializer(SchemaRegistryAsyncClient schemaRegistryClient, - SchemaRegistryCodec serializerSchemaRegistryCodec, List deserializerSchemaRegistryCodecList) { - this(schemaRegistryClient, serializerSchemaRegistryCodec, deserializerSchemaRegistryCodecList, null, null); - } - - public SchemaRegistrySerializer(SchemaRegistryAsyncClient schemaRegistryClient, - SchemaRegistryCodec serializerSchemaRegistryCodec, List deserializerSchemaRegistryCodecList, Boolean autoRegisterSchemas, - String schemaGroup) { - - Objects.requireNonNull(serializerSchemaRegistryCodec); - Objects.requireNonNull(deserializerSchemaRegistryCodecList); - - if (schemaRegistryClient == null) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Schema registry client must be initialized and passed into builder.")); - } - - if (deserializerSchemaRegistryCodecList.size() == 0) { - throw logger.logExceptionAsError( - new IllegalArgumentException("At least one Codec must be provided for deserialization.")); - } - - this.schemaRegistryClient = schemaRegistryClient; - this.serializerSchemaRegistryCodec = serializerSchemaRegistryCodec; - for (SchemaRegistryCodec c : deserializerSchemaRegistryCodecList) { - if (this.deserializerCodecMap.containsKey(c.getSerializationType())) { - throw logger.logExceptionAsError( - new IllegalArgumentException("Only on Codec can be provided per schema serialization type.")); - } - this.deserializerCodecMap.put(c.getSerializationType().toString(), c); - } - - // send configurations only - if (autoRegisterSchemas != null) { - this.autoRegisterSchemas = autoRegisterSchemas; - } - - if (schemaGroup != null) { - this.schemaGroup = schemaGroup; - } - } - - /** - * 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 s Output stream destination for encoded bytes - * @param object object to be serialized - * @param Type of the output stream parameter. - * @return byte array containing encoded bytes with prefixed schema ID - */ - protected Mono serializeAsync(S s, Object object) { - if (object == null) { - return monoError(logger, new NullPointerException( - "Null object, behavior should be defined in concrete serializer implementation.")); - } - - if (serializerSchemaRegistryCodec == null) { - return monoError(logger, new NullPointerException( - "Byte encoder null, serializer must be initialized with a byte encoder.")); - } - - if (serializationType == null) { - serializationType = serializerSchemaRegistryCodec.getSerializationType(); - } - - String schemaString = serializerSchemaRegistryCodec.getSchemaString(object); - String schemaName = serializerSchemaRegistryCodec.getSchemaName(object); - - return this.maybeRegisterSchema(this.schemaGroup, schemaName, schemaString, this.serializationType) -// .onErrorMap(e -> { -// if (e instanceof SchemaRegistryClientException) { -// StringBuilder builder = new StringBuilder(); -// if (this.autoRegisterSchemas) { -// builder.append(String.format("Error registering Avro schema. Group: %s, name: %s. ", -// schemaGroup, schemaName)); -// } else { -// builder.append(String.format("Error retrieving Avro schema. Group: %s, name: %s. ", -// schemaGroup, schemaName)); -// } -// -// if (e.getCause() instanceof HttpResponseException) { -// HttpResponseException httpException = (HttpResponseException) e.getCause(); -// builder.append("HTTP ") -// .append(httpException.getResponse().getStatusCode()) -// .append(" ") -// .append(httpException.getResponse().getBodyAsString()); -// } else { -// builder.append(e.getCause().getMessage()); -// } -// -// return logger.logExceptionAsError(new SerializationException(builder.toString(), e)); -// } else { -// return logger.logExceptionAsError(new SerializationException(e.getMessage(), e)); -// } -// }) - .handle((id, sink) -> { - ByteBuffer idBuffer = ByteBuffer.allocate(SchemaRegistrySerializer.SCHEMA_ID_SIZE) - .put(id.getBytes(StandardCharsets.UTF_8)); - try { - s.write(idBuffer.array()); - s.write(serializerSchemaRegistryCodec.encode(object)); - } catch (IOException e) { - sink.error(new UncheckedIOException(e.getMessage(), e)); - } - sink.next(s); - }); - } - - - /** - * Core implementation for registry-based deserialization. - * Fetches schema referenced by prefixed ID and deserializes the subsequent payload into Java object. - * - * @param s InputStream containing bytes encoded by an Azure Schema Registry producer - * @return object, deserialized with the prefixed schema - */ - protected Mono deserializeAsync(InputStream s) { - if (s == null) { - return Mono.empty(); - } - - return Mono.fromCallable(() -> { - byte[] payload = new byte[s.available()]; - while (s.read(payload) != -1) {} - return payload; - }) - .flatMap(payload -> { - if (payload == null || payload.length == 0) { - return Mono.empty(); - } - - ByteBuffer buffer = ByteBuffer.wrap(payload); - String schemaId = getSchemaIdFromPayload(buffer); - System.out.println(schemaId); - - return this.schemaRegistryClient.getSchema(schemaId) -// .onErrorMap(IOException.class, -// e -> logger.logExceptionAsError(new SerializationException(e.getMessage(), e))) - .handle((registryObject, sink) -> { - Object 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() - SchemaRegistrySerializer.SCHEMA_ID_SIZE; - byte[] b = Arrays.copyOfRange(buffer.array(), start, start + length); - - SchemaRegistryCodec schemaRegistryCodec = getDeserializerCodec(registryObject); - sink.next(schemaRegistryCodec.decode(b, payloadSchema)); - }); -// .onErrorMap(e -> { -// if (e instanceof SchemaRegistryClientException) { -// StringBuilder builder = new StringBuilder( -// String.format("Failed to retrieve schema for id %s", schemaId)); -// -// if (e.getCause() instanceof HttpResponseException) { -// HttpResponseException httpException = (HttpResponseException) e.getCause(); -// builder.append("HTTP ") -// .append(httpException.getResponse().getStatusCode()) -// .append(" ") -// .append(httpException.getResponse().getBodyAsString()); -// } else { -// builder.append(e.getCause().getMessage()); -// } -// -// return logger.logExceptionAsError(new SerializationException(builder.toString(), e)); -// } else { -// return logger.logExceptionAsError(new SerializationException(e.getMessage(), e)); -// } -// }); - }); - } - - - /** - * Fetches the correct Codec based on schema type of the message. - * - * @param registryObject object returned from CachedSchemaRegistryAsyncClient, contains schema type - * @return Codec to be used to deserialize encoded payload bytes - */ - private SchemaRegistryCodec getDeserializerCodec(SchemaRegistryObject registryObject) { - SchemaRegistryCodec schemaRegistryCodec = deserializerCodecMap.get(registryObject.getSerializationType()); - if (schemaRegistryCodec == null) { - throw logger.logExceptionAsError( - new NullPointerException( - String.format("No deserializer codec class found for schema type '%s'.", - registryObject.getSerializationType()) - )); - } - return schemaRegistryCodec; - } - - /** - * @param buffer full payload bytes - * @return String representation of schema ID - */ - private String getSchemaIdFromPayload(ByteBuffer buffer) { - byte[] schemaGuidByteArray = new byte[SchemaRegistrySerializer.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 - * @param serializationType type of schema being stored, e.g. avro - * @return string representation of schema ID - */ - private Mono maybeRegisterSchema( - String schemaGroup, String schemaName, String schemaString, SerializationType serializationType) { - if (this.autoRegisterSchemas) { - return this.schemaRegistryClient.registerSchema(schemaGroup, schemaName, schemaString, serializationType) - .map(SchemaRegistryObject::getSchemaId); - } else { - return this.schemaRegistryClient.getSchemaId( - schemaGroup, schemaName, schemaString, serializationType); - } - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryObject.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryObject.java deleted file mode 100644 index c049c14f7202e..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryObject.java +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry.models; - -import com.azure.core.util.logging.ClientLogger; -import java.nio.charset.StandardCharsets; -import java.util.function.Function; - -/** - * Stores all relevant information returned from CachedSchemaRegistryClient layer. - */ -public final class SchemaRegistryObject { - private final ClientLogger logger = new ClientLogger(SchemaRegistryObject.class); - - private final String schemaId; - private final SerializationType serializationType; - private final Function parseMethod; - private final byte[] schemaBytes; - private final String schemaName; - private final String schemaGroup; - - private Object deserialized; - - /** - * Initializes SchemaRegistryObject instance. - * - * @param schemaId schema ID - * @param serializationType 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, - SerializationType serializationType, - String schemaName, - String schemaGroup, - byte[] schemaByteArray, - Function parseMethod) { - this.schemaId = schemaId; - this.serializationType = serializationType; - this.schemaBytes = schemaByteArray.clone(); - this.deserialized = null; - this.parseMethod = parseMethod; - this.schemaGroup = schemaGroup; - this.schemaName = schemaName; - } - - /** - * @return schema ID - */ - public String getSchemaId() { - return schemaId; - } - - /** - * @return schema type associated with the schema payload - */ - public SerializationType getSerializationType() { - return serializationType; - } - - public String getSchemaGroup() { - return null; - } - - public String getSchemaName() { - return null; - } - - /** - * 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 getSchema() { - if (this.deserialized == null) { - String schemaString = new String( - this.schemaBytes, StandardCharsets.UTF_8); - - logger.verbose("Deserializing schema, id: '{}', schema string '{}'", this.schemaId, schemaString); - - this.deserialized = parseMethod.apply(schemaString); - - } - return deserialized; - } -} diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryProperties.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryProperties.java new file mode 100644 index 0000000000000..0248c98adc890 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryProperties.java @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.data.schemaregistry.models; + +import java.util.Arrays; + +/** + * Stores all relevant information returned from CachedSchemaRegistryClient layer. + */ +public final class SchemaRegistryProperties { + + 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 SchemaRegistryProperties( + 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 index 392082268e07c..c3d3193208a56 100644 --- 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 @@ -1,12 +1,21 @@ +// 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"); - public static final SerializationType JSON = fromString("json"); + /** + * 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/package-info.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/package-info.java index f0a21847c2ffd..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 @@ -2,6 +2,6 @@ // 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/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java deleted file mode 100644 index 2ba4dc7dfbe76..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SampleSchemaRegistryCodec.java +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.data.schemaregistry.models.SerializationType; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -public class SampleSchemaRegistryCodec implements SchemaRegistryCodec { - - public SampleSchemaRegistryCodec() { } - - @Override - public String getSchemaName(Object object) { - return "schema name"; - } - - @Override - public String getSchemaGroup() { - return "schema group"; - } - - @Override - public String getSchemaString(Object object) { - return "string representation of schema"; - } - - @Override - public byte[] encode(Object object) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try { - outputStream.write("sample payload".getBytes()); - outputStream.flush(); - outputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - throw new IllegalStateException("this should never happen", e); - } - return outputStream.toByteArray(); - } - - @Override - public SerializationType getSerializationType() { - return SerializationType.fromString("test"); - } - - @Override - public String parseSchemaString(String s) { - return s; - } - - public static final String CONSTANT_PAYLOAD = "sample payload!"; - - @Override - public Object decode(byte[] bytes, Object o) { - return CONSTANT_PAYLOAD; - } -} 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 index 90e2f809abf44..9c53561e6dbea 100644 --- 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 @@ -19,7 +19,7 @@ import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdHeaders; import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdResponse; import com.azure.data.schemaregistry.implementation.models.SchemaId; -import com.azure.data.schemaregistry.models.SchemaRegistryObject; +import com.azure.data.schemaregistry.models.SchemaRegistryProperties; import com.azure.data.schemaregistry.models.SerializationType; import java.util.HashMap; import java.util.concurrent.ConcurrentSkipListMap; @@ -40,14 +40,14 @@ public class SchemaRegistryAsyncClientTest { private SchemaRegistryAsyncClient client; private AzureSchemaRegistryRestService restService; - private HashMap guidCache; - private HashMap schemaStringCache; + private HashMap guidCache; + private HashMap schemaStringCache; private ConcurrentSkipListMap> typeParserDictionary; @BeforeEach protected void setUp() { - this.guidCache = new HashMap(); - this.schemaStringCache = new HashMap(); + this.guidCache = new HashMap(); + this.schemaStringCache = new HashMap(); this.typeParserDictionary = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); this.typeParserDictionary.put(MOCK_SERIALIZATION.toString(), (s) -> s); @@ -125,8 +125,8 @@ public void testGetSchemaThenGuidCacheHit() throws Exception { MOCK_AVRO_SCHEMA, mockHeaders))); - SchemaRegistryObject first = client.getSchema(mockId.toString()).block(); - SchemaRegistryObject second = client.getSchema(mockId.toString()).block(); + SchemaRegistryProperties first = client.getSchema(mockId.toString()).block(); + SchemaRegistryProperties second = client.getSchema(mockId.toString()).block(); assertTrue(first.equals(second)); assertEquals(mockId.toString(), first.getSchemaId()); @@ -239,7 +239,7 @@ public void testGetSchemaByIdNotFoundThenThrows() { fail("Should have thrown on 404 status code"); } catch (IllegalStateException e) { assert true; - } catch (Exception e){ + } catch (Exception e) { assert false; } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java deleted file mode 100644 index a43eb08d9912b..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/SchemaRegistrySerializerTest.java +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import com.azure.data.schemaregistry.models.SchemaRegistryObject; -import com.azure.data.schemaregistry.models.SerializationType; -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 org.mockito.Mockito; -import reactor.core.publisher.Mono; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; - -public class SchemaRegistrySerializerTest { - private static final String MOCK_GUID = new String(new char[SchemaRegistrySerializer.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 testRegistryGuidPrefixedToPayload() { - // manually add SchemaRegistryObject into mock registry client cache - SampleSchemaRegistryCodec encoder = new SampleSchemaRegistryCodec(); - SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, - encoder.getSerializationType(), - encoder.getSchemaName(null), - encoder.getSchemaGroup(), - encoder.getSchemaString(null).getBytes(), // always returns same schema string - encoder::parseSchemaString); - - assertEquals(encoder.getSchemaString(null), registered.getSchema()); - - SchemaRegistryAsyncClient mockRegistryClient = getMockClient(); - Mockito.when(mockRegistryClient.getSchemaId(anyString(), anyString(), anyString(), - any(SerializationType.class))) - .thenReturn(Mono.just(encoder.getSchemaString(null))); - - TestDummySerializer serializer = new TestDummySerializer( - mockRegistryClient, false); - - try { - ByteArrayOutputStream payload = serializer.serializeAsync(new ByteArrayOutputStream(), 1).block(); - ByteBuffer buffer = ByteBuffer.wrap(payload.toByteArray()); - byte[] schemaGuidByteArray = new byte[SchemaRegistrySerializer.SCHEMA_ID_SIZE]; - buffer.get(schemaGuidByteArray); - - // guid should match preloaded SchemaRegistryObject guid - assertEquals(MOCK_GUID, new String(schemaGuidByteArray)); - - int start = buffer.position() + buffer.arrayOffset(); - int length = buffer.limit() - SchemaRegistrySerializer.SCHEMA_ID_SIZE; - byte[] encodedBytes = Arrays.copyOfRange(buffer.array(), start, start + length); - assertTrue(Arrays.equals(encoder.encode(null), encodedBytes)); - } catch (RuntimeException e) { - e.printStackTrace(); - fail(); - } - } - - @Test - public void testNullPayloadThrowsSerializationException() { - TestDummySerializer serializer = new TestDummySerializer( - getMockClient(), - false); - - try { - serializer.serializeAsync(new ByteArrayOutputStream(), null).block(); - fail("Serializing null payload failed to throw NullPointerException"); - } catch (NullPointerException e) { - assertTrue(true); - } - } - - - @Test - public void testIfRegistryNullThenThrow() { - try { - TestDummySerializer serializer = new TestDummySerializer( - null, 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 testAddDeserializerCodec() throws IOException { - // add sample codec impl and test that it is used for decoding payload - SampleSchemaRegistryCodec decoder = new SampleSchemaRegistryCodec(); - - // manually add SchemaRegistryObject to cache - SchemaRegistryObject registered = new SchemaRegistryObject(MOCK_GUID, - decoder.getSerializationType(), - decoder.getSchemaName(null), - decoder.getSchemaGroup(), - MOCK_AVRO_SCHEMA_STRING.getBytes(), - decoder::parseSchemaString); - - assertTrue(registered.getSchema() != null); - - SchemaRegistryAsyncClient mockClient = getMockClient(); - Mockito.when(mockClient.getSchema(anyString())) - .thenReturn(Mono.just(registered)); - - // constructor loads deserializer codec - TestDummySerializer serializer = new TestDummySerializer(mockClient, true); - - assertEquals(MOCK_GUID, - serializer.schemaRegistryClient.getSchema(MOCK_GUID).block().getSchemaId()); - - serializer.deserializeAsync(new ByteArrayInputStream(getPayload())) - .subscribe(unused -> { - System.out.println(unused); - }, - ex -> System.out.println(ex)); - - assertEquals(SampleSchemaRegistryCodec.CONSTANT_PAYLOAD, - serializer.deserializeAsync(new ByteArrayInputStream(getPayload())).block()); - } - - @Test - public void testNullPayload() { - TestDummySerializer deserializer = new TestDummySerializer( - getMockClient(), true); - assertNull(deserializer.deserializeAsync(null).block()); - } - - @Test - public void testIfTooShortPayloadThrow() { - TestDummySerializer serializer = new TestDummySerializer( - getMockClient(), true); - - try { - serializer.deserializeAsync(new ByteArrayInputStream("bad payload".getBytes())).block(); - fail("Too short payload did not throw BufferUnderflowException"); - } catch (BufferUnderflowException e) { - assertTrue(true); - } - } - - // TODO: add for non-existing guid - - @Test - public void testIfRegistryClientNullOnBuildThrow() { - try { - TestDummySerializer deserializer = new TestDummySerializer(null, true); - fail("should not get here."); - } catch (IllegalArgumentException e) { - // good - } - } - - private SchemaRegistryAsyncClient getMockClient() { - return mock(SchemaRegistryAsyncClient.class); - } - - private byte[] getPayload() throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(ByteBuffer.allocate(SchemaRegistrySerializer.SCHEMA_ID_SIZE) - .put(MOCK_GUID.getBytes(StandardCharsets.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(); - return out.toByteArray(); - } - - 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/TestDummySerializer.java b/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummySerializer.java deleted file mode 100644 index 86ad29a7e45bc..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/test/java/com/azure/data/schemaregistry/TestDummySerializer.java +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.data.schemaregistry; - -import java.util.Collections; - -public class TestDummySerializer extends SchemaRegistrySerializer { - TestDummySerializer( - SchemaRegistryAsyncClient mockClient, - boolean autoRegisterSchemas) { - super(mockClient, new SampleSchemaRegistryCodec(), Collections.singletonList(new SampleSchemaRegistryCodec())); - - // allows simulating improperly written serializer constructor that does not initialize byte encoder - this.autoRegisterSchemas = autoRegisterSchemas; - } -} From 361972ac3e88d1890164c51d7560854f4513632d Mon Sep 17 00:00:00 2001 From: Mitch Denny Date: Thu, 10 Sep 2020 12:48:27 +1000 Subject: [PATCH 13/17] Update pom.xml Whitespace change to try and reboot PR builds. --- sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml index 94d9313f97c07..c12d075f651ca 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml @@ -9,6 +9,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.azure azure-client-sdk-parent From 580f14c32a288477616f6ee823cdcb9b2f1dbb2f Mon Sep 17 00:00:00 2001 From: Srikanta Date: Wed, 9 Sep 2020 20:17:43 -0700 Subject: [PATCH 14/17] Samples readme --- .../CHANGELOG.md | 8 +- .../azure-data-schemaregistry-avro/pom.xml | 32 +- .../avro/SchemaRegistryAvroSerializer.java | 16 +- .../src/samples/README.md | 46 ++ ...chemaRegistryAvroDeserilizationSample.java | 61 +++ ...SchemaRegistryAvroSerializationSample.java | 52 ++ .../generatedtestsources/HandOfCards.java | 354 +++++++++++++ .../generatedtestsources/PlayingCard.java | 469 ++++++++++++++++++ .../generatedtestsources/PlayingCardSuit.java | 13 + .../samples/resources/avro/HandOfCards.avro | 29 ++ .../azure-data-schemaregistry/CHANGELOG.md | 6 +- .../SchemaRegistryAsyncClient.java | 42 +- .../schemaregistry/SchemaRegistryClient.java | 18 +- ...yProperties.java => SchemaProperties.java} | 9 +- .../SchemaRegistryAsyncClientTest.java | 14 +- 15 files changed, 1112 insertions(+), 57 deletions(-) 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 rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/{SchemaRegistryProperties.java => SchemaProperties.java} (85%) diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/CHANGELOG.md b/sdk/schemaregistry/azure-data-schemaregistry-avro/CHANGELOG.md index bc085f7353901..e35045635c234 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/CHANGELOG.md +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/CHANGELOG.md @@ -1,9 +1,13 @@ # Release History -## 1.0.0-beta.3 (Unreleased) +## 1.0.0-beta.3 (2020-09-10) +- Updated to use `azure-core` for `ObjectSerializer`. +- Removed `AvroSchemaRegistrySerializer` and `AvroSchemaRegistryCodec` +- `SchemaRegistryAvroSerializerBuilder` now takes `SchemaRegistryAsyncClient` as input to build the + `SchemaRegistryAvroSerializer` instance ## 1.0.0-beta.2 (2020-06-19) - Fix null max schema map size parameter behavior ## 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-avro/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml index c12d075f651ca..6e08ef53d9329 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml @@ -49,11 +49,6 @@ azure-data-schemaregistry 1.0.0-beta.3 - - com.azure - azure-core-experimental - 1.0.0-beta.2 - org.apache.avro avro @@ -79,6 +74,12 @@ 5.6.2 test + + com.azure + azure-identity + 1.1.0 + test + @@ -97,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/SchemaRegistryAvroSerializer.java b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/main/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializer.java index 0fc0ac0a43f50..781ff2ffd771f 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,11 +3,11 @@ package com.azure.data.schemaregistry.avro; -import com.azure.core.experimental.serializer.ObjectSerializer; -import com.azure.core.experimental.serializer.TypeReference; 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.SchemaRegistryProperties; +import com.azure.data.schemaregistry.models.SchemaProperties; import com.azure.data.schemaregistry.models.SerializationType; import reactor.core.publisher.Mono; @@ -94,12 +94,12 @@ public Mono deserializeAsync(InputStream stream, } @Override - public S serialize(S stream, Object value) { - return serializeAsync(stream, value).block(); + public void serialize(OutputStream outputStream, Object value) { + serializeAsync(outputStream, value).block(); } @Override - public Mono serializeAsync(S outputStream, Object object) { + public Mono serializeAsync(OutputStream outputStream, Object object) { if (object == null) { return monoError(logger, new NullPointerException( @@ -116,10 +116,10 @@ public Mono serializeAsync(S outputStream, Object ob try { outputStream.write(idBuffer.array()); outputStream.write(codec.encode(object)); + sink.complete(); } catch (IOException e) { sink.error(new UncheckedIOException(e.getMessage(), e)); } - sink.next(outputStream); }); } @@ -149,7 +149,7 @@ private Mono maybeRegisterSchema( if (this.autoRegisterSchemas) { return this.schemaRegistryClient .registerSchema(schemaGroup, schemaName, schemaString, SerializationType.AVRO) - .map(SchemaRegistryProperties::getSchemaId); + .map(SchemaProperties::getSchemaId); } else { return this.schemaRegistryClient.getSchemaId( 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..04a6cee148067 --- /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.java +[sample_avro_deserialization]: ./java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializationSample.java.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-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..985690c78c7d1 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializationSample.java @@ -0,0 +1,52 @@ +// 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) + .autoRegisterSchema(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/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/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java index 2242e9a054527..d1fb52a082155 100644 --- 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 @@ -12,7 +12,7 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestService; import com.azure.data.schemaregistry.implementation.models.SchemaId; -import com.azure.data.schemaregistry.models.SchemaRegistryProperties; +import com.azure.data.schemaregistry.models.SchemaProperties; import com.azure.data.schemaregistry.models.SerializationType; import java.nio.charset.Charset; @@ -41,8 +41,8 @@ public final class SchemaRegistryAsyncClient { private final AzureSchemaRegistryRestService restService; private final Integer maxSchemaMapSize; private final ConcurrentSkipListMap> typeParserMap; - private final Map idCache; - private final Map schemaStringCache; + private final Map idCache; + private final Map schemaStringCache; SchemaRegistryAsyncClient( AzureSchemaRegistryRestService restService, @@ -58,8 +58,8 @@ public final class SchemaRegistryAsyncClient { // testing - todo remove constructor and replace with mock SchemaRegistryAsyncClient( AzureSchemaRegistryRestService restService, - Map idCache, - Map schemaStringCache, + Map idCache, + Map schemaStringCache, ConcurrentSkipListMap> typeParserMap) { this.restService = restService; // mockable this.idCache = idCache; @@ -75,10 +75,10 @@ public final class SchemaRegistryAsyncClient { * @param schemaString The string representation of the schema. * @param serializationType The serialization type of this schema. * - * @return The {@link SchemaRegistryProperties} of a successfully registered schema. + * @return The {@link SchemaProperties} of a successfully registered schema. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono registerSchema( + public Mono registerSchema( String schemaGroup, String schemaName, String schemaString, SerializationType serializationType) { if (schemaStringCache.containsKey(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString))) { @@ -102,13 +102,13 @@ public Mono registerSchema( * @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) { + 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) { + 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); @@ -130,7 +130,7 @@ Mono> registerSchemaWithResponse(String schem SchemaId schemaId = response.getValue(); - SchemaRegistryProperties registered = new SchemaRegistryProperties(schemaId.getId(), + SchemaProperties registered = new SchemaProperties(schemaId.getId(), serializationType, schemaName, schemaString.getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING)); @@ -139,7 +139,7 @@ Mono> registerSchemaWithResponse(String schem schemaStringCache .putIfAbsent(getSchemaStringCacheKey(schemaGroup, schemaName, schemaString), registered); logger.verbose("Cached schema string. Group: '{}', name: '{}'", schemaGroup, schemaName); - SimpleResponse schemaRegistryObjectSimpleResponse = new SimpleResponse<>( + SimpleResponse schemaRegistryObjectSimpleResponse = new SimpleResponse<>( response.getRequest(), response.getStatusCode(), response.getHeaders(), registered); sink.next(schemaRegistryObjectSimpleResponse); @@ -150,10 +150,10 @@ Mono> registerSchemaWithResponse(String schem * Gets the schema properties of the schema associated with the unique schemaId. * @param schemaId The unique identifier of the schema. * - * @return The {@link SchemaRegistryProperties} associated with the given {@code schemaId}. + * @return The {@link SchemaProperties} associated with the given {@code schemaId}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSchema(String schemaId) { + public Mono getSchema(String schemaId) { if (idCache.containsKey(schemaId)) { logger.verbose("Cache hit for schema id '{}'", schemaId); return Mono.fromCallable(() -> idCache.get(schemaId)); @@ -165,15 +165,15 @@ public Mono getSchema(String schemaId) { * Gets the schema properties of the schema associated with the unique schemaId. * @param schemaId The unique identifier of the schema. * - * @return The {@link SchemaRegistryProperties} associated with the given {@code schemaId} along with the HTTP + * @return The {@link SchemaProperties} associated with the given {@code schemaId} along with the HTTP * response. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSchemaWithResponse(String schemaId) { + public Mono> getSchemaWithResponse(String schemaId) { return getSchemaWithResponse(schemaId, Context.NONE); } - Mono> getSchemaWithResponse(String schemaId, Context context) { + Mono> getSchemaWithResponse(String schemaId, Context context) { Objects.requireNonNull(schemaId, "'schemaId' should not be null"); return this.restService.getSchemaByIdWithResponseAsync(schemaId) .handle((response, sink) -> { @@ -192,7 +192,7 @@ Mono> getSchemaWithResponse(String schemaId, SerializationType serializationType = SerializationType.fromString(response.getDeserializedHeaders().getXSchemaType()); - SchemaRegistryProperties schemaObject = new SchemaRegistryProperties(schemaId, + SchemaProperties schemaObject = new SchemaProperties(schemaId, serializationType, null, response.getValue().getBytes(SCHEMA_REGISTRY_SERVICE_ENCODING)); @@ -200,7 +200,7 @@ Mono> getSchemaWithResponse(String schemaId, resetIfNeeded(); idCache.putIfAbsent(schemaId, schemaObject); logger.verbose("Cached schema object. Path: '{}'", schemaId); - SimpleResponse schemaRegistryObjectSimpleResponse = new SimpleResponse<>( + SimpleResponse schemaRegistryObjectSimpleResponse = new SimpleResponse<>( response.getRequest(), response.getStatusCode(), response.getHeaders(), schemaObject); sink.next(schemaRegistryObjectSimpleResponse); @@ -267,7 +267,7 @@ Mono> getSchemaIdWithResponse(String schemaGroup, String schema resetIfNeeded(); schemaStringCache.putIfAbsent( getSchemaStringCacheKey(schemaGroup, schemaName, schemaString), - new SchemaRegistryProperties( + new SchemaProperties( schemaId.getId(), serializationType, schemaName, 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 index e831d1d7d04ab..7961a23941384 100644 --- 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 @@ -8,7 +8,7 @@ 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.SchemaRegistryProperties; +import com.azure.data.schemaregistry.models.SchemaProperties; import com.azure.data.schemaregistry.models.SerializationType; /** @@ -33,8 +33,8 @@ public final class SchemaRegistryClient { * @return The schema properties on successful registration of the schema. */ @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaRegistryProperties registerSchema(String schemaGroup, String schemaName, String schemaString, - SerializationType serializationType) { + public SchemaProperties registerSchema(String schemaGroup, String schemaName, String schemaString, + SerializationType serializationType) { return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType, Context.NONE) .getValue(); } @@ -49,8 +49,8 @@ public SchemaRegistryProperties registerSchema(String schemaGroup, String schema * @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) { + public Response registerSchemaWithResponse(String schemaGroup, String schemaName, + String schemaString, SerializationType serializationType, Context context) { return this.asyncClient.registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType, context).block(); } @@ -59,10 +59,10 @@ public Response registerSchemaWithResponse(String sche * Gets the schema properties of the schema associated with the unique schemaId. * @param schemaId The unique identifier of the schema. * - * @return The {@link SchemaRegistryProperties} associated with the given {@code schemaId}. + * @return The {@link SchemaProperties} associated with the given {@code schemaId}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public SchemaRegistryProperties getSchema(String schemaId) { + public SchemaProperties getSchema(String schemaId) { return getSchemaWithResponse(schemaId, Context.NONE).getValue(); } @@ -70,11 +70,11 @@ public SchemaRegistryProperties getSchema(String schemaId) { * 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 SchemaRegistryProperties} associated with the given {@code schemaId} along with the HTTP + * @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) { + public Response getSchemaWithResponse(String schemaId, Context context) { return this.asyncClient.getSchemaWithResponse(schemaId).block(); } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryProperties.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaProperties.java similarity index 85% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryProperties.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaProperties.java index 0248c98adc890..9e9dbffcf86fe 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaRegistryProperties.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/models/SchemaProperties.java @@ -3,12 +3,15 @@ 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 CachedSchemaRegistryClient layer. + * Stores all relevant information returned from {@link SchemaRegistryClient}/{@link SchemaRegistryAsyncClient} layer. */ -public final class SchemaRegistryProperties { +public final class SchemaProperties { private final String schemaId; private final SerializationType serializationType; @@ -23,7 +26,7 @@ public final class SchemaRegistryProperties { * @param schemaName name of the schema. * @param schemaByteArray byte payload representing schema, returned from Azure Schema Registry */ - public SchemaRegistryProperties( + public SchemaProperties( String schemaId, SerializationType serializationType, String schemaName, 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 index 9c53561e6dbea..6275fc3f7577d 100644 --- 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 @@ -19,7 +19,7 @@ import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdHeaders; import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdResponse; import com.azure.data.schemaregistry.implementation.models.SchemaId; -import com.azure.data.schemaregistry.models.SchemaRegistryProperties; +import com.azure.data.schemaregistry.models.SchemaProperties; import com.azure.data.schemaregistry.models.SerializationType; import java.util.HashMap; import java.util.concurrent.ConcurrentSkipListMap; @@ -40,14 +40,14 @@ public class SchemaRegistryAsyncClientTest { private SchemaRegistryAsyncClient client; private AzureSchemaRegistryRestService restService; - private HashMap guidCache; - private HashMap schemaStringCache; + private HashMap guidCache; + private HashMap schemaStringCache; private ConcurrentSkipListMap> typeParserDictionary; @BeforeEach protected void setUp() { - this.guidCache = new HashMap(); - this.schemaStringCache = new HashMap(); + this.guidCache = new HashMap(); + this.schemaStringCache = new HashMap(); this.typeParserDictionary = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); this.typeParserDictionary.put(MOCK_SERIALIZATION.toString(), (s) -> s); @@ -125,8 +125,8 @@ public void testGetSchemaThenGuidCacheHit() throws Exception { MOCK_AVRO_SCHEMA, mockHeaders))); - SchemaRegistryProperties first = client.getSchema(mockId.toString()).block(); - SchemaRegistryProperties second = client.getSchema(mockId.toString()).block(); + SchemaProperties first = client.getSchema(mockId.toString()).block(); + SchemaProperties second = client.getSchema(mockId.toString()).block(); assertTrue(first.equals(second)); assertEquals(mockId.toString(), first.getSchemaId()); From 58d6ee0beb13b8240f505244862710746ff3aa34 Mon Sep 17 00:00:00 2001 From: Srikanta Date: Wed, 9 Sep 2020 20:50:54 -0700 Subject: [PATCH 15/17] update identity version --- sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml b/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml index 6e08ef53d9329..8e300edfa0cf8 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/pom.xml @@ -77,7 +77,7 @@ com.azure azure-identity - 1.1.0 + 1.1.2 test From 25215b0aa9ccb869318f545cb6d82d239b85ec37 Mon Sep 17 00:00:00 2001 From: Srikanta Date: Wed, 9 Sep 2020 23:11:58 -0700 Subject: [PATCH 16/17] More samples --- .../src/samples/README.md | 6 +- .../azure-data-schemaregistry/README.md | 192 +++++++++++++++++- .../azure-data-schemaregistry/pom.xml | 6 + .../src/samples/README.md | 47 +++++ .../schemaregistry/GetSchemaIdSample.java | 45 ++++ .../data/schemaregistry/GetSchemaSample.java | 42 ++++ .../data/schemaregistry/ReadmeSamples.java | 116 +++++++++++ .../schemaregistry/RegisterSchemaSample.java | 43 ++++ 8 files changed, 490 insertions(+), 7 deletions(-) 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 diff --git a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/README.md b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/README.md index 04a6cee148067..d31ddf33daa29 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/README.md +++ b/sdk/schemaregistry/azure-data-schemaregistry-avro/src/samples/README.md @@ -40,7 +40,7 @@ This project welcomes contributions and suggestions. See [Contributing][sdk_read [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.java -[sample_avro_deserialization]: ./java/com/azure/data/schemaregistry/avro/SchemaRegistryAvroSerializationSample.java.java +[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%2Fsrc%2Fsamples%2README.png) +![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/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/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..1d7a804232a4a --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaIdSample.java @@ -0,0 +1,45 @@ +// 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(); + }, ex -> { + System.out.println("Failed to get schema id: " + ex.getMessage()); + 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..6442ffcfeb367 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaSample.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.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(); + }, ex -> { + System.out.println("Failed to get schema: " + ex.getMessage()); + 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..e530088d96748 --- /dev/null +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/RegisterSchemaSample.java @@ -0,0 +1,43 @@ +// 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(); + }, ex -> { + System.out.println("Failed to register schema: " + ex.getMessage()); + countDownLatch.countDown(); + }); + + // wait for the async task to complete + countDownLatch.await(); + } +} From 003f0a5b3514414809ea286743a5dd83101e0cd8 Mon Sep 17 00:00:00 2001 From: Srikanta Date: Thu, 10 Sep 2020 03:14:23 -0700 Subject: [PATCH 17/17] Codegen from updated swagger --- .../checkstyle/checkstyle-suppressions.xml | 2 +- .../avro/SchemaRegistryAvroSerializer.java | 1 - .../SchemaRegistryAvroSerializerBuilder.java | 2 +- ...SchemaRegistryAvroSerializationSample.java | 3 +- .../SchemaRegistryAsyncClient.java | 25 +- .../schemaregistry/SchemaRegistryClient.java | 2 +- .../SchemaRegistryClientBuilder.java | 14 +- .../implementation/AzureSchemaRegistry.java | 108 + .../AzureSchemaRegistryBuilder.java | 210 ++ .../AzureSchemaRegistryRestService.java | 1922 ----------------- ...chemaRegistryRestServiceClientBuilder.java | 67 - .../implementation/Schemas.java | 338 +++ .../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/SchemaId.java | 8 +- ...eaders.java => SchemasGetByIdHeaders.java} | 31 +- ...ponse.java => SchemasGetByIdResponse.java} | 12 +- ...va => SchemasQueryIdByContentHeaders.java} | 31 +- ...a => SchemasQueryIdByContentResponse.java} | 16 +- ...aders.java => SchemasRegisterHeaders.java} | 31 +- ...onse.java => SchemasRegisterResponse.java} | 12 +- .../models/SerializationType.java | 30 + .../models/ServiceErrorResponse.java | 44 + .../models/ServiceErrorResponseException.java | 36 + .../implementation/models/package-info.java | 8 +- .../implementation/package-info.java | 8 +- .../schemaregistry/GetSchemaIdSample.java | 3 - .../data/schemaregistry/GetSchemaSample.java | 3 - .../schemaregistry/RegisterSchemaSample.java | 3 - .../SchemaRegistryAsyncClientTest.java | 131 +- 39 files changed, 952 insertions(+), 2914 deletions(-) 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 delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistryRestService.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistryRestServiceClientBuilder.java create mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/Schemas.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateGroupHeaders.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateGroupResponse.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateSchemaResponse.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetIdBySchemaContentHeaders.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetLatestSchemaResponse.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionHeaders.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionsHeaders.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionsResponse.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemasByGroupHeaders.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemasByGroupResponse.java delete mode 100644 sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemaGroup.java rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/{CreateSchemaHeaders.java => SchemasGetByIdHeaders.java} (78%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/{GetSchemaByIdResponse.java => SchemasGetByIdResponse.java} (68%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/{GetSchemaByIdHeaders.java => SchemasQueryIdByContentHeaders.java} (76%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/{GetSchemaVersionResponse.java => SchemasQueryIdByContentResponse.java} (63%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/{GetLatestSchemaHeaders.java => SchemasRegisterHeaders.java} (78%) rename sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/{GetIdBySchemaContentResponse.java => SchemasRegisterResponse.java} (68%) 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 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 2f73afd0e2370..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 @@ - + 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 781ff2ffd771f..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 @@ -151,7 +151,6 @@ private Mono maybeRegisterSchema( .registerSchema(schemaGroup, schemaName, schemaString, SerializationType.AVRO) .map(SchemaProperties::getSchemaId); } else { - return this.schemaRegistryClient.getSchemaId( schemaGroup, schemaName, schemaString, SerializationType.AVRO); } 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 9aed8f97d529f..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 @@ -19,7 +19,7 @@ public final class SchemaRegistryAvroSerializerBuilder { * Supplies client defaults. */ public SchemaRegistryAvroSerializerBuilder() { - this.autoRegisterSchemas = null; + this.autoRegisterSchemas = false; this.avroSpecificReader = false; } 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 index 985690c78c7d1..5d5070959fe3b 100644 --- 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 @@ -25,6 +25,7 @@ public class SchemaRegistryAvroSerializationSample { 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) @@ -37,7 +38,6 @@ public static void main(String[] args) { .schemaRegistryAsyncClient(schemaRegistryAsyncClient) .schemaGroup("{schema-group}") .avroSpecificReader(true) - .autoRegisterSchema(true) .buildSerializer(); PlayingCard playingCard = new PlayingCard(); @@ -46,6 +46,7 @@ public static void main(String[] args) { 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/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryAsyncClient.java index d1fb52a082155..5f305c980d78b 100644 --- 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 @@ -10,8 +10,6 @@ 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.implementation.AzureSchemaRegistryRestService; -import com.azure.data.schemaregistry.implementation.models.SchemaId; import com.azure.data.schemaregistry.models.SchemaProperties; import com.azure.data.schemaregistry.models.SerializationType; @@ -23,6 +21,8 @@ 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; /** @@ -38,14 +38,14 @@ public final class SchemaRegistryAsyncClient { static final int MAX_SCHEMA_MAP_SIZE_DEFAULT = 1000; static final int MAX_SCHEMA_MAP_SIZE_MINIMUM = 10; - private final AzureSchemaRegistryRestService restService; + private final AzureSchemaRegistry restService; private final Integer maxSchemaMapSize; private final ConcurrentSkipListMap> typeParserMap; private final Map idCache; private final Map schemaStringCache; SchemaRegistryAsyncClient( - AzureSchemaRegistryRestService restService, + AzureSchemaRegistry restService, int maxSchemaMapSize, ConcurrentSkipListMap> typeParserMap) { this.restService = restService; @@ -57,7 +57,7 @@ public final class SchemaRegistryAsyncClient { // testing - todo remove constructor and replace with mock SchemaRegistryAsyncClient( - AzureSchemaRegistryRestService restService, + AzureSchemaRegistry restService, Map idCache, Map schemaStringCache, ConcurrentSkipListMap> typeParserMap) { @@ -103,18 +103,19 @@ public Mono registerSchema( */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> registerSchemaWithResponse(String schemaGroup, String schemaName, - String schemaString, SerializationType serializationType) { + String schemaString, SerializationType serializationType) { return registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType, Context.NONE); } Mono> registerSchemaWithResponse(String schemaGroup, String schemaName, - String schemaString, SerializationType serializationType, Context context) { + String schemaString, SerializationType serializationType, Context context) { logger.verbose( "Registering schema. Group: '{}', name: '{}', serialization type: '{}', payload: '{}'", schemaGroup, schemaName, serializationType, schemaString); return this.restService - .createSchemaWithResponseAsync(schemaGroup, schemaName, serializationType.toString(), schemaString) + .getSchemas().registerWithResponseAsync(schemaGroup, schemaName, + com.azure.data.schemaregistry.implementation.models.SerializationType.AVRO, schemaString) .handle((response, sink) -> { if (response == null) { sink.error(logger.logExceptionAsError( @@ -175,7 +176,7 @@ public Mono> getSchemaWithResponse(String schemaId) { Mono> getSchemaWithResponse(String schemaId, Context context) { Objects.requireNonNull(schemaId, "'schemaId' should not be null"); - return this.restService.getSchemaByIdWithResponseAsync(schemaId) + return this.restService.getSchemas().getByIdWithResponseAsync(schemaId) .handle((response, sink) -> { if (response == null) { sink.error(logger.logExceptionAsError( @@ -246,9 +247,9 @@ public Mono> getSchemaIdWithResponse(String schemaGroup, String Mono> getSchemaIdWithResponse(String schemaGroup, String schemaName, String schemaString, SerializationType serializationType, Context context) { - return this.restService - .getIdBySchemaContentWithResponseAsync(schemaGroup, schemaName, serializationType.toString(), - schemaString) + 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( 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 index 7961a23941384..39f2c8e7be137 100644 --- 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 @@ -50,7 +50,7 @@ public SchemaProperties registerSchema(String schemaGroup, String schemaName, St */ @ServiceMethod(returns = ReturnType.SINGLE) public Response registerSchemaWithResponse(String schemaGroup, String schemaName, - String schemaString, SerializationType serializationType, Context context) { + String schemaString, SerializationType serializationType, Context context) { return this.asyncClient.registerSchemaWithResponse(schemaGroup, schemaName, schemaString, serializationType, context).block(); } diff --git a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java index 8a178e9fe0f2b..eb54892a66830 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/SchemaRegistryClientBuilder.java @@ -23,8 +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.implementation.AzureSchemaRegistryRestService; -import com.azure.data.schemaregistry.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; @@ -55,6 +55,7 @@ public class SchemaRegistryClientBuilder { private final String clientVersion; private String schemaRegistryUrl; + private String host; private HttpClient httpClient; private Integer maxSchemaMapSize; private TokenCredential credential; @@ -75,7 +76,7 @@ public SchemaRegistryClientBuilder() { 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); @@ -95,7 +96,8 @@ 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)); @@ -256,8 +258,8 @@ public SchemaRegistryAsyncClient buildAsyncClient() { .build(); } - AzureSchemaRegistryRestService restService = new AzureSchemaRegistryRestServiceClientBuilder() - .host(this.schemaRegistryUrl) + AzureSchemaRegistry restService = new AzureSchemaRegistryBuilder() + .endpoint(host) .pipeline(pipeline) .buildClient(); 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/AzureSchemaRegistryRestService.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistryRestService.java deleted file mode 100644 index 3c8be332324b4..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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.implementation.models.CreateGroupResponse; -import com.azure.data.schemaregistry.implementation.models.CreateSchemaResponse; -import com.azure.data.schemaregistry.implementation.models.GetIdBySchemaContentResponse; -import com.azure.data.schemaregistry.implementation.models.GetLatestSchemaResponse; -import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdResponse; -import com.azure.data.schemaregistry.implementation.models.GetSchemaVersionResponse; -import com.azure.data.schemaregistry.implementation.models.GetSchemaVersionsResponse; -import com.azure.data.schemaregistry.implementation.models.GetSchemasByGroupResponse; -import com.azure.data.schemaregistry.implementation.models.SchemaGroup; -import com.azure.data.schemaregistry.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/implementation/AzureSchemaRegistryRestServiceClientBuilder.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/AzureSchemaRegistryRestServiceClientBuilder.java deleted file mode 100644 index 4aea3ea89ef52..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/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/implementation/models/CreateGroupHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateGroupHeaders.java deleted file mode 100644 index c3db80e8040cd..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/CreateGroupResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateGroupResponse.java deleted file mode 100644 index bc20e0ac954e1..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/CreateSchemaResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateSchemaResponse.java deleted file mode 100644 index cd37671a2514f..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/GetIdBySchemaContentHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetIdBySchemaContentHeaders.java deleted file mode 100644 index b825d8118cd7f..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/GetLatestSchemaResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetLatestSchemaResponse.java deleted file mode 100644 index 2e4e65822c924..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/GetSchemaVersionHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionHeaders.java deleted file mode 100644 index 014da2ac0bd08..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/GetSchemaVersionsHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionsHeaders.java deleted file mode 100644 index 4902359c6f4b8..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/GetSchemaVersionsResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionsResponse.java deleted file mode 100644 index 4da3f44617cd0..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/GetSchemasByGroupHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemasByGroupHeaders.java deleted file mode 100644 index 7597a0a0a03c6..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/GetSchemasByGroupResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemasByGroupResponse.java deleted file mode 100644 index 0c29e36fc7580..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/SchemaGroup.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemaGroup.java deleted file mode 100644 index fc416152e6297..0000000000000 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/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.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/implementation/models/SchemaId.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemaId.java index 80e6b35775ff6..992882faa2808 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemaId.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemaId.java @@ -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/implementation/models/CreateSchemaHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdHeaders.java similarity index 78% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateSchemaHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdHeaders.java index d2f470271d9c1..6dc170e592835 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/CreateSchemaHeaders.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdHeaders.java @@ -5,11 +5,10 @@ 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/implementation/models/GetSchemaByIdResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdResponse.java similarity index 68% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaByIdResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdResponse.java index 5a0c67a8c9926..548619675165d 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaByIdResponse.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasGetByIdResponse.java @@ -7,19 +7,19 @@ 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/implementation/models/GetSchemaByIdHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentHeaders.java similarity index 76% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaByIdHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentHeaders.java index d31de2971a2ee..1ea51172bc5bd 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaByIdHeaders.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentHeaders.java @@ -5,11 +5,10 @@ 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/implementation/models/GetSchemaVersionResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentResponse.java similarity index 63% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentResponse.java index fe2d718d28dd9..84351f4b293f1 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetSchemaVersionResponse.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentResponse.java @@ -7,29 +7,29 @@ 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/implementation/models/GetLatestSchemaHeaders.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterHeaders.java similarity index 78% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetLatestSchemaHeaders.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterHeaders.java index 646bffe9411d7..7acb1bffe084a 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetLatestSchemaHeaders.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterHeaders.java @@ -5,11 +5,10 @@ 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/implementation/models/GetIdBySchemaContentResponse.java b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterResponse.java similarity index 68% rename from sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetIdBySchemaContentResponse.java rename to sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterResponse.java index cf780ffaad79a..08dde0ba56c74 100644 --- a/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/GetIdBySchemaContentResponse.java +++ b/sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasRegisterResponse.java @@ -7,23 +7,23 @@ 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 index bdeef3522a149..69bc98649c18c 100644 --- 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 @@ -1,2 +1,8 @@ -/** Package containing the data models for AzureSchemaRegistryRestService. null. */ +// 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 index 6f1ee3cf00e96..b5b3b659b0932 100644 --- 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 @@ -1,2 +1,8 @@ -/** Package containing the classes for AzureSchemaRegistryRestService. null. */ +// 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/samples/java/com/azure/data/schemaregistry/GetSchemaIdSample.java b/sdk/schemaregistry/azure-data-schemaregistry/src/samples/java/com/azure/data/schemaregistry/GetSchemaIdSample.java index 1d7a804232a4a..5186a261d5c4c 100644 --- 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 @@ -33,9 +33,6 @@ public static void main(String[] args) throws InterruptedException { .subscribe(schemaId -> { System.out.println("Successfully retrieved the schema id: " + schemaId); countDownLatch.countDown(); - }, ex -> { - System.out.println("Failed to get schema id: " + ex.getMessage()); - countDownLatch.countDown(); }); // wait for the async task to complete 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 index 6442ffcfeb367..1481c9f9b8164 100644 --- 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 @@ -31,9 +31,6 @@ public static void main(String[] args) throws InterruptedException { .subscribe(schemaProperties -> { System.out.println("Successfully retrieved the schema " + schemaProperties.getSchemaName()); countDownLatch.countDown(); - }, ex -> { - System.out.println("Failed to get schema: " + ex.getMessage()); - countDownLatch.countDown(); }); // wait for the async task to complete 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 index e530088d96748..47fbd8316b80a 100644 --- 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 @@ -32,9 +32,6 @@ public static void main(String[] args) throws InterruptedException { .subscribe(schemaProperties -> { System.out.println("Successfully registered a schema with id " + schemaProperties.getSchemaId()); countDownLatch.countDown(); - }, ex -> { - System.out.println("Failed to register schema: " + ex.getMessage()); - countDownLatch.countDown(); }); // wait for the async task to complete 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 index 6275fc3f7577d..53c8cc292ca92 100644 --- 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 @@ -3,35 +3,39 @@ 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.Mockito.anyString; +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; -import com.azure.data.schemaregistry.implementation.AzureSchemaRegistryRestService; -import com.azure.data.schemaregistry.implementation.models.CreateSchemaResponse; -import com.azure.data.schemaregistry.implementation.models.GetIdBySchemaContentResponse; -import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdHeaders; -import com.azure.data.schemaregistry.implementation.models.GetSchemaByIdResponse; -import com.azure.data.schemaregistry.implementation.models.SchemaId; -import com.azure.data.schemaregistry.models.SchemaProperties; -import com.azure.data.schemaregistry.models.SerializationType; -import java.util.HashMap; -import java.util.concurrent.ConcurrentSkipListMap; -import java.util.function.Function; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Mono; - public class SchemaRegistryAsyncClientTest { - private static final SerializationType MOCK_SERIALIZATION = SerializationType.fromString("mock_serialization_type"); + 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"; @@ -39,10 +43,11 @@ public class SchemaRegistryAsyncClientTest { 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 AzureSchemaRegistryRestService restService; + private AzureSchemaRegistry restService; private HashMap guidCache; private HashMap schemaStringCache; private ConcurrentSkipListMap> typeParserDictionary; + private Schemas schemas; @BeforeEach protected void setUp() { @@ -52,12 +57,13 @@ protected void setUp() { this.typeParserDictionary = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); this.typeParserDictionary.put(MOCK_SERIALIZATION.toString(), (s) -> s); - this.restService = mock(AzureSchemaRegistryRestService.class); + this.restService = mock(AzureSchemaRegistry.class); this.client = new SchemaRegistryAsyncClient( this.restService, this.guidCache, this.schemaStringCache, this.typeParserDictionary); + this.schemas = mock(Schemas.class); } @AfterEach @@ -68,10 +74,13 @@ protected void tearDown() { @Test public void testRegisterThenSchemaCacheHit() throws Exception { MOCK_SCHEMA_ID.setId(MOCK_ID); - when(restService.createSchemaWithResponseAsync(anyString(), anyString(), anyString(), anyString())) + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.registerWithResponseAsync(anyString(), anyString(), + any(com.azure.data.schemaregistry.implementation.models.SerializationType.class), + anyString())) .thenReturn( Mono.just( - new CreateSchemaResponse( + new SchemasRegisterResponse( null, 200, null, @@ -80,22 +89,26 @@ public void testRegisterThenSchemaCacheHit() throws Exception { assertEquals( MOCK_ID, - client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); + 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()); + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION) + .block().getSchemaId()); - verify(restService, times(1)) - .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION.toString(), MOCK_AVRO_SCHEMA); + 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.getIdBySchemaContentWithResponseAsync(anyString(), anyString(), anyString(), anyString())) + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.queryIdByContentWithResponseAsync(anyString(), anyString(), + any(SerializationType.class), anyString())) .thenReturn( Mono.just( - new GetIdBySchemaContentResponse( + new SchemasQueryIdByContentResponse( null, 200, null, @@ -107,18 +120,19 @@ public void testGetGuidThenSchemaCacheHit() throws Exception { assertEquals(MOCK_ID, client.getSchemaId(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block()); - verify(restService, times(1)) - .getIdBySchemaContentWithResponseAsync(anyString(), anyString(), anyString(), anyString()); + verify(schemas, times(1)) + .queryIdByContentWithResponseAsync(anyString(), anyString(), any(SerializationType.class), anyString()); } @Test public void testGetSchemaThenGuidCacheHit() throws Exception { String mockId = "mock-id---"; - GetSchemaByIdHeaders mockHeaders = new GetSchemaByIdHeaders(); + SchemasGetByIdHeaders mockHeaders = new SchemasGetByIdHeaders(); mockHeaders.setXSchemaType(MOCK_SERIALIZATION.toString()); - when(restService.getSchemaByIdWithResponseAsync(mockId)) + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.getByIdWithResponseAsync(mockId)) .thenReturn( - Mono.just(new GetSchemaByIdResponse( + Mono.just(new SchemasGetByIdResponse( null, 200, null, @@ -131,16 +145,18 @@ public void testGetSchemaThenGuidCacheHit() throws Exception { assertTrue(first.equals(second)); assertEquals(mockId.toString(), first.getSchemaId()); - verify(restService, times(1)).getSchemaByIdWithResponseAsync(mockId); + verify(schemas, times(1)).getByIdWithResponseAsync(mockId); } @Test public void testClientReset() throws Exception { MOCK_SCHEMA_ID.setId(MOCK_ID); - when(restService.createSchemaWithResponseAsync(anyString(), anyString(), anyString(), anyString())) + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.registerWithResponseAsync(anyString(), anyString(), any(SerializationType.class), + anyString())) .thenReturn( Mono.just( - new CreateSchemaResponse( + new SchemasRegisterResponse( null, 200, null, @@ -149,7 +165,8 @@ public void testClientReset() throws Exception { assertEquals( MOCK_ID, - client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION) + .block().getSchemaId()); client.clearCache(); @@ -161,19 +178,22 @@ public void testClientReset() throws Exception { assertEquals( MOCK_ID, - client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION).block().getSchemaId()); + client.registerSchema(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_AVRO_SCHEMA, MOCK_SERIALIZATION) + .block().getSchemaId()); - verify(restService, times(2)) - .createSchemaWithResponseAsync(MOCK_GROUP, MOCK_SCHEMA_NAME, MOCK_SERIALIZATION.toString(), MOCK_AVRO_SCHEMA); + 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.createSchemaWithResponseAsync(anyString(), anyString(), anyString(), anyString())) + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.registerWithResponseAsync(anyString(), anyString(), any(SerializationType.class), + anyString())) .thenReturn( Mono.just( - new CreateSchemaResponse( + new SchemasRegisterResponse( null, 400, null, @@ -184,23 +204,25 @@ public void testBadRegisterRequestThenThrows() { "doesn't matter", "doesn't matter", "doesn't matter", - SerializationType.fromString("doesn't matter")).block(); + MOCK_SERIALIZATION).block(); fail("Should throw on 400 status code"); } catch (IllegalStateException e) { assert true; } - verify(restService, times(1)) - .createSchemaWithResponseAsync(anyString(), anyString(), anyString(), anyString()); + verify(schemas, times(1)) + .registerWithResponseAsync(anyString(), anyString(), any(SerializationType.class), anyString()); } @Test public void testGetIdBySchemaContentNotFoundThenThrows() { MOCK_SCHEMA_ID.setId(MOCK_ID); - when(restService.getIdBySchemaContentWithResponseAsync(anyString(), anyString(), anyString(), anyString())) + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.queryIdByContentWithResponseAsync(anyString(), anyString(), + any(SerializationType.class), anyString())) .thenReturn( Mono.just( - new GetIdBySchemaContentResponse( + new SchemasQueryIdByContentResponse( null, 404, null, @@ -212,22 +234,23 @@ public void testGetIdBySchemaContentNotFoundThenThrows() { "doesn't matter", "doesn't matter", "doesn't matter", - SerializationType.fromString("doesn't matter")).block(); + MOCK_SERIALIZATION).block(); fail("Should throw on 404 status code"); } catch (IllegalStateException e) { assert true; } - verify(restService, times(1)) - .getIdBySchemaContentWithResponseAsync(anyString(), anyString(), anyString(), anyString()); + verify(schemas, times(1)) + .queryIdByContentWithResponseAsync(anyString(), anyString(), any(SerializationType.class), anyString()); } @Test public void testGetSchemaByIdNotFoundThenThrows() { String mockId = "mock-id---"; - when(restService.getSchemaByIdWithResponseAsync(mockId)) + when(restService.getSchemas()).thenReturn(schemas); + when(schemas.getByIdWithResponseAsync(mockId)) .thenReturn( - Mono.just(new GetSchemaByIdResponse( + Mono.just(new SchemasGetByIdResponse( null, 404, null, @@ -243,7 +266,7 @@ public void testGetSchemaByIdNotFoundThenThrows() { assert false; } - verify(restService, times(1)) - .getSchemaByIdWithResponseAsync(mockId); + verify(schemas, times(1)) + .getByIdWithResponseAsync(mockId); } }