1 package org.apache.avro;
2
3 import com.fasterxml.jackson.core.JsonGenerator;
4 import com.fasterxml.jackson.databind.JsonNode;
5 import java.io.IOException;
6 import java.util.function.Function;
7 import javax.annotation.Nonnull;
8 import javax.annotation.Nullable;
9
10
11
12
13 public interface SchemaResolver {
14
15
16
17
18
19
20
21
22 default boolean customWrite(Schema schema, JsonGenerator gen) throws IOException {
23 String ref = getId(schema);
24 if (ref != null) {
25 gen.writeStartObject();
26 gen.writeFieldName(getJsonAttrName());
27 gen.writeString(ref);
28 gen.writeEndObject();
29 return true;
30 } else {
31 return false;
32 }
33 }
34
35
36
37
38
39
40 @Nullable
41 default Schema customRead(Function<String, JsonNode> object) {
42 JsonNode refVal = object.apply(getJsonAttrName());
43 if (refVal != null) {
44 return resolveSchema(refVal.asText());
45 } else {
46 return null;
47 }
48 }
49
50 default String getJsonAttrName() {
51 return "$ref";
52 }
53
54 @Nonnull
55 Schema resolveSchema(String id);
56
57 @Nullable
58 String getId(Schema schema);
59
60 SchemaResolver NONE = new SchemaResolver() {
61 @Override
62 public Schema resolveSchema(final String id) {
63 throw new UnsupportedOperationException();
64 }
65
66 @Override
67 public String getId(final Schema schema) {
68 return null;
69 }
70 };
71
72 default void registerAsDefault() {
73 SchemaResolvers.registerDefault(this);
74 }
75
76 }