Avro Schema Evolution with Enum – Deserialization Crashes - avro

I defined two versions of a record in two separate AVCS schema files. I used the namespace to distinguish versions
SimpleV1.avsc
{
"type" : "record",
"name" : "Simple",
"namespace" : "test.simple.v1",
"fields" : [
{
"name" : "name",
"type" : "string"
},
{
"name" : "status",
"type" : {
"type" : "enum",
"name" : "Status",
"symbols" : [ "ON", "OFF" ]
},
"default" : "ON"
}
]
}
Example JSON
{"name":"A","status":"ON"}
Version 2 just has an additional description field with default value.
SimpleV2.avsc
{
"type" : "record",
"name" : "Simple",
"namespace" : "test.simple.v2",
"fields" : [
{
"name" : "name",
"type" : "string"
},
{
"name" : "description",
"type" : "string",
"default" : ""
},
{
"name" : "status",
"type" : {
"type" : "enum",
"name" : "Status",
"symbols" : [ "ON", "OFF" ]
},
"default" : "ON"
}
]
}
Example JSON
{"name":"B","description":"b","status":"ON"}
Both schemas were serialized to Java classes.
In my example I was going to test backward compatibility. A record written by V1 shall be read by a reader using V2. I wanted to see that default values are inserted. This is working as long as I do not use enums.
public class EnumEvolutionExample {
public static void main(String[] args) throws IOException {
Schema schemaV1 = new org.apache.avro.Schema.Parser().parse(new File("./src/main/resources/SimpleV1.avsc"));
//works as well
//Schema schemaV1 = test.simple.v1.Simple.getClassSchema();
Schema schemaV2 = new org.apache.avro.Schema.Parser().parse(new File("./src/main/resources/SimpleV2.avsc"));
test.simple.v1.Simple simpleV1 = test.simple.v1.Simple.newBuilder()
.setName("A")
.setStatus(test.simple.v1.Status.ON)
.build();
SchemaPairCompatibility schemaCompatibility = SchemaCompatibility.checkReaderWriterCompatibility(
schemaV2,
schemaV1);
//Checks that writing v1 and reading v2 schemas is compatible
Assert.assertEquals(SchemaCompatibilityType.COMPATIBLE, schemaCompatibility.getType());
byte[] binaryV1 = serealizeBinary(simpleV1);
//Crashes with: AvroTypeException: Found test.simple.v1.Status, expecting test.simple.v2.Status
test.simple.v2.Simple v2 = deSerealizeBinary(binaryV1, new test.simple.v2.Simple(), schemaV1);
}
public static byte[] serealizeBinary(SpecificRecord record) {
DatumWriter<SpecificRecord> writer = new SpecificDatumWriter<>(record.getSchema());
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Encoder binaryEncoder = EncoderFactory.get()
.binaryEncoder(stream, null);
try {
writer.write(record, binaryEncoder);
binaryEncoder.flush();
data = stream.toByteArray();
} catch (IOException e) {
System.out.println("Serialization error " + e.getMessage());
}
return data;
}
public static <T extends SpecificRecord> T deSerealizeBinary(byte[] data, T reuse, Schema writer) {
Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
DatumReader<T> datumReader = new SpecificDatumReader<>(writer, reuse.getSchema());
try {
T datum = datumReader.read(null, decoder);
return datum;
} catch (IOException e) {
System.out.println("Deserialization error" + e.getMessage());
}
return null;
}
}
The checkReaderWriterCompatibility method confirms that schemas are compatible.
But when I deserialize I’m getting the following exception
Exception in thread "main" org.apache.avro.AvroTypeException: Found test.simple.v1.Status, expecting test.simple.v2.Status
at org.apache.avro.io.ResolvingDecoder.doAction(ResolvingDecoder.java:309)
at org.apache.avro.io.parsing.Parser.advance(Parser.java:86)
at org.apache.avro.io.ResolvingDecoder.readEnum(ResolvingDecoder.java:260)
at org.apache.avro.generic.GenericDatumReader.readEnum(GenericDatumReader.java:267)
at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:181)
at org.apache.avro.specific.SpecificDatumReader.readField(SpecificDatumReader.java:136)
at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:247)
at org.apache.avro.specific.SpecificDatumReader.readRecord(SpecificDatumReader.java:123)
at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:179)
at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:160)
at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:153)
at test.EnumEvolutionExample.deSerealizeBinary(EnumEvolutionExample.java:70)
at test.EnumEvolutionExample.main(EnumEvolutionExample.java:45)
I don’t understand why Avro thinks it got a v1.Status. Namespaces are not part of the encoding.
Is this a bug or has anyone an idea how get that running?

Try adding an #aliases.
For example:
v1
{
"type" : "record",
"name" : "Simple",
"namespace" : "test.simple.v1",
"fields" : [
{
"name" : "name",
"type" : "string"
},
{
"name" : "status",
"type" : {
"type" : "enum",
"name" : "Status",
"symbols" : [ "ON", "OFF" ]
},
"default" : "ON"
}
]
}
v2
{
"type" : "record",
"name" : "Simple",
"namespace" : "test.simple.v2",
"fields" : [
{
"name" : "name",
"type" : "string"
},
{
"name" : "description",
"type" : "string",
"default" : ""
},
{
"name" : "status",
"type" : {
"type" : "enum",
"name" : "Status",
"aliases" : [ "test.simple.v1.Status" ]
"symbols" : [ "ON", "OFF" ]
},
"default" : "ON"
}
]
}

Found a workaround. I moved the enum to a "unversioned" namespace. So it is in both versions the same.
But actually it looks like a bug for me. Converting a record is not an issue but enum is not working. Both are complex types in Avro.
{
"type" : "record",
"name" : "Simple",
"namespace" : "test.simple.v1",
"fields" : [
{
"name" : "name",
"type" : "string"
},
{
"name" : "status",
"type" : {
"type" : "enum",
"name" : "Status",
"namespace" : "test.model.unversioned",
"symbols" : [ "ON", "OFF" ]
},
"default" : "ON"
}
]
}

Related

Get multiple strings from JSON

So the JSON variable let json = JSON(nearbyChargingSites.jsonString!) contains the current data.:
{
"timestamp" : 1626902257093,
"superchargers" : [
{
"location" : {
"lat" : 63.325319,
"long" : 10.305137
},
"total_stalls" : 19,
"distance_miles" : 10.064082000000001,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 15,
"name" : "Leinstrand, Norway - Klett"
},
{
"location" : {
"lat" : 63.466445999999998,
"long" : 10.91766
},
"total_stalls" : 16,
"distance_miles" : 11.838984999999999,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 16,
"name" : "Stjørdal, Norway"
},
{
"location" : {
"lat" : 63.734355000000001,
"long" : 11.281487
},
"total_stalls" : 12,
"distance_miles" : 31.206503999999999,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 11,
"name" : "Levanger, Norway"
},
{
"location" : {
"lat" : 62.832030000000003,
"long" : 10.009639999999999
},
"total_stalls" : 20,
"distance_miles" : 44.117753,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 17,
"name" : "Berkåk, Norway"
}
],
"congestion_sync_time_utc_secs" : 1626902199,
"destination_charging" : [
{
"distance_miles" : 23.366278999999999,
"name" : "Bårdshaug Herregård",
"location" : {
"lat" : 63.299208,
"long" : 9.8448650000000004
},
"type" : "destination"
},
{
"distance_miles" : 38.390034,
"name" : "Fosen Fjordhotel",
"location" : {
"lat" : 63.959356999999997,
"long" : 10.223908
},
"type" : "destination"
},
{
"distance_miles" : 46.220022999999998,
"name" : "Falksenteret",
"location" : {
"lat" : 63.293301999999997,
"long" : 9.0834460000000004
},
"type" : "destination"
},
{
"distance_miles" : 54.981445000000001,
"name" : "Væktarstua",
"location" : {
"lat" : 62.908683000000003,
"long" : 11.893306000000001
},
"type" : "destination"
}
]
}
I use SwiftyJSON and tries to get the superchargers latitude, longitude and name, like this:
let jsonName = json["superchargers"]["name"]
let jsonLat = json["superchargers"]["location"]["lat"]
let jsonLong = json["superchargers"]["location"]["long"]
When trying to print any of those, all of them return nil.
Any ideas what I am doing wrong, and how to do this?
The reason I want to do this is because I want to add them as annotation to a MKMapView.
The first error is that the JSON initializer you are using will create a single JSON string object, it will not parse the string as JSON data:
Instead of:
let json = JSON(nearbyChargingSites.jsonString!)
you need to use:
let json = JSON(data: dataFromJSONString)
Second you need to iterate over the superchargers array to collect all the values
Try something like:
if let dataFromString = nearbyChargingSites.jsonString!.data(using: .utf8, allowLossyConversion: false) {
let json = try! JSON(data: dataFromString,options: .allowFragments)
for supercharger in json["superchargers"].arrayValue {
let jsonName = supercharger["name"].stringValue
let jsonLat = supercharger["location"]["lat"].doubleValue
let jsonLong = supercharger["location"]["long"].doubleValue
}
}
Please note that the above code does not perform error handling and will crash if values are missing from JSON.

How do I compare two nested documents using mongo_dart

Here is my database entry structure, it has a nested document called friends, I want to compare two different _id's friends list in dart using mongo_dart
{
"_id" : ObjectId("60ae06074e162995281b4666"),
"email" : "one#one.com",
"emailverified" : false,
"username" : "one#one.com",
"displayName" : "complete n00b",
"phonenumber" : "",
"dob" : "",
"points" : 0,
"friends" : [
{
"username" : "three#one.com",
"sent" : ISODate("2021-05-26T10:01:30.616Z")
},
{
"username" : "six#one.com",
"sent" : ISODate("2021-05-26T10:43:16.822Z")
}
]
}
Here is my code, but I am not getting any returns
Future<Map> commonFriends(store, myObjectId, theirObjectId) async {
var commonList = await store.aggregate([
{
'\$project': {
'friends': 1,
'commonToBoth': {
'\$setIntersection': [
{'_id': myObjectId, 'friends': '\$username'},
{'_id': theirObjectId, 'friends': '\$username'}
]
},
}
}
]);
return commonList;
}
I am getting an error from db.dart which is apart of mongo_dart package. The error is "Exception has occurred.
Map (4 items)"

firebase database filtering is not working. Need some assistance

I have a simple test database that I cant get to filter. I indexed the category in the rules:
"questions":{
".indexOn": ["category"]
},
My filter for the quiz app:
/questions.json?orderBy="category"&equalTo="Basics"&print=pretty
and my database:
"-MKoucSP33zm4jC43AnY" : {
"title" : {
"answers" : [ {
"score" : 30,
"text" : "Pineapple"
}, {
"score" : 5,
"text" : "Ham"
}, {
"score" : 20,
"text" : "Yogurt"
}, {
"score" : 10,
"text" : "Crab"
} ],
"category" : "Basics",
"questionId" : "101",
"questionImage" : "",
"questionLink" : "",
"questionText" : "What topping do you like the best on pizza?"
}
}
The category property is nested under the title node, so the property you need to order/filter on is title/category:
/questions.json?orderBy="title/category"&equalTo="Basics"&print=pretty
You'll also need to update your index definition for that path, so:
"questions": { ".indexOn": "title/category" }
Working example: https://stackoverflow.firebaseio.com/64596200/questions.json?orderBy="title/category"&equalTo="Basics"

Adding Implementation Notes and Description to Swagger UI

I am attempting to add Implementation Notes and Description to my Swagger UI. However, neither show up on the UI when implemented as below:
{
"swagger" : "2.0",
"info" : {
"description" : "The definition of the Rest API to service plugin over https on port 9443.",
"version" : "1.0",
"title" : "Plugin Rest API",
"contact" : {
"name" : "John Doe",
"email" : "john.doe#gmail.com"
}
},
"basePath" : "/service",
"tags" : [ {
"name" : "service"
} ],
"schemes" : [ "https" ],
"paths" : {
"/entry" : {
"get" : {
"notes" : "This is a note",
"method" : "get",
"tags" : [ "service" ],
"summary" : "Get an entry by first name and last name",
"description" : "This is a description",
"operationId" : "getEntry",
"produces" : [ "application/xml", "application/json" ],
"parameters" : [ {
"name" : "first",
"in" : "query",
"description" : "The first name",
"required" : true,
"type" : "string"
}, {
"name" : "last",
"in" : "query",
"description" : "The last name",
"required" : true,
"type" : "string"
} ],
"responses" : {
"200" : {
"description" : "Matching entry, or entries, if any, were returned",
"schema" : {
"$ref" : "#/definitions/Service"
}
}
}
},
I am not sure what I am doing wrong in my code. I've tested it on various sample swagger.json files and I cannot seem to get it to work.
notes is not a swagger field. See the documentation
Your description field is written twice, so the first one has been overridden.
you can add implementation notes using notes tag in #ApiOperation annotation as shown below,
#ApiOperation(notes = "Your Implementation Notes will show here[![enter image description here][1]][1]", value = "Add Customer Payment Details and Generate Payment Link through Batch.", nickname = "insertPaymentBatch", tags =
"Insert Payment" )

Is it possible to create Salesreceipt without product/service value through QBO API?

Is it possible to create Salesreceipt without product/service value through QBO API? I have tried through API but it's not reflecting rate value and storing description value only.
If I remove ItemRef attribute(in request body) then it's reflecting rate and amount values and it's assigning some default and random product/service.
It is possible directly in QBO UI.
Request body where only description value storing:
{
"TxnDate" : "2016-05-27",
"Line" : [ {
"Amount" : 2222.00,
"Description" : "hi chk",
"DetailType" : "ItemReceiptLineDetail",
"ItemReceiptLineDetail" : {
"ItemRef" : { },
"Qty" : 1,
"UnitPrice" : 2222
} }
],
"CustomerRef" : {
"value" : "67"
},
"CustomerMemo" : {
"value" : "Thanks for your business! We appreciate referrals!"
},
"TotalAmt": 2222.00,
"PrivateNote" : "",
"CustomField" : [ {
"DefinitionId" : "1",
"Type" : "StringType",
"StringValue" : ""
} ]
}
Request body where default product/service assigning:
{
"TxnDate" : "2016-05-27",
"Line" : [ {
"Amount" : 2222.00,
"Description" : "hi chk",
"DetailType" : "ItemReceiptLineDetail",
"ItemReceiptLineDetail" : {
"Qty" : 1,
"UnitPrice" : 2222
} }
],
"CustomerRef" : {
"value" : "67"
},
"CustomerMemo" : {
"value" : "Thanks for your business! We appreciate referrals!"
},
"TotalAmt": 2222.00,
"PrivateNote" : "",
"CustomField" : [ {
"DefinitionId" : "1",
"Type" : "StringType",
"StringValue" : ""
} ]
}
No.
QuickBooks Online does not support this.

Resources