/
Schema.java
1621 lines (1476 loc) · 55.5 KB
/
Schema.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.avro;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.avro.util.internal.JacksonUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.DoubleNode;
/** An abstract data type.
* <p>A schema may be one of:
* <ul>
* <li>A <i>record</i>, mapping field names to field value data;
* <li>An <i>enum</i>, containing one of a small set of symbols;
* <li>An <i>array</i> of values, all of the same schema;
* <li>A <i>map</i>, containing string/value pairs, of a declared schema;
* <li>A <i>union</i> of other schemas;
* <li>A <i>fixed</i> sized binary object;
* <li>A unicode <i>string</i>;
* <li>A sequence of <i>bytes</i>;
* <li>A 32-bit signed <i>int</i>;
* <li>A 64-bit signed <i>long</i>;
* <li>A 32-bit IEEE single-<i>float</i>; or
* <li>A 64-bit IEEE <i>double</i>-float; or
* <li>A <i>boolean</i>; or
* <li><i>null</i>.
* </ul>
*
* A schema can be constructed using one of its static <tt>createXXX</tt>
* methods, or more conveniently using {@link SchemaBuilder}. The schema objects are
* <i>logically</i> immutable.
* There are only two mutating methods - {@link #setFields(List)} and
* {@link #addProp(String, String)}. The following restrictions apply on these
* two methods.
* <ul>
* <li> {@link #setFields(List)}, can be called at most once. This method exists
* in order to enable clients to build recursive schemas.
* <li> {@link #addProp(String, String)} can be called with property names
* that are not present already. It is not possible to change or delete an
* existing property.
* </ul>
*/
public abstract class Schema extends JsonProperties {
static final JsonFactory FACTORY = new JsonFactory();
static final ObjectMapper MAPPER = new ObjectMapper(FACTORY);
private static final int NO_HASHCODE = Integer.MIN_VALUE;
static {
FACTORY.enable(JsonParser.Feature.ALLOW_COMMENTS);
FACTORY.setCodec(MAPPER);
}
/** The type of a schema. */
public enum Type {
RECORD, ENUM, ARRAY, MAP, UNION, FIXED, STRING, BYTES,
INT, LONG, FLOAT, DOUBLE, BOOLEAN, NULL;
private String name;
private Type() { this.name = this.name().toLowerCase(Locale.ENGLISH); }
public String getName() { return name; }
};
private final Type type;
private LogicalType logicalType = null;
Schema(Type type) {
super(SCHEMA_RESERVED);
this.type = type;
}
/** Create a schema for a primitive type. */
public static Schema create(Type type) {
switch (type) {
case STRING: return new StringSchema();
case BYTES: return new BytesSchema();
case INT: return new IntSchema();
case LONG: return new LongSchema();
case FLOAT: return new FloatSchema();
case DOUBLE: return new DoubleSchema();
case BOOLEAN: return new BooleanSchema();
case NULL: return new NullSchema();
default: throw new AvroRuntimeException("Can't create a: "+type);
}
}
private static final Set<String> SCHEMA_RESERVED = new HashSet<String>();
static {
Collections.addAll(SCHEMA_RESERVED,
"doc", "fields", "items", "name", "namespace",
"size", "symbols", "values", "type", "aliases");
}
int hashCode = NO_HASHCODE;
@Override public void addProp(String name, JsonNode value) {
super.addProp(name, value);
hashCode = NO_HASHCODE;
}
@Override public void addProp(String name, Object value) {
super.addProp(name, value);
hashCode = NO_HASHCODE;
}
public LogicalType getLogicalType() {
return logicalType;
}
void setLogicalType(LogicalType logicalType) {
this.logicalType = logicalType;
}
/** Create an anonymous record schema. */
public static Schema createRecord(List<Field> fields) {
Schema result = createRecord(null, null, null, false);
result.setFields(fields);
return result;
}
/** Create a named record schema. */
public static Schema createRecord(String name, String doc, String namespace,
boolean isError) {
return new RecordSchema(new Name(name, namespace), doc, isError);
}
/** Create a named record schema with fields already set. */
public static Schema createRecord(String name, String doc, String namespace,
boolean isError, List<Field> fields) {
return new RecordSchema(new Name(name, namespace), doc, isError, fields);
}
/** Create an enum schema. */
public static Schema createEnum(String name, String doc, String namespace,
List<String> values) {
return new EnumSchema(new Name(name, namespace), doc,
new LockableArrayList<String>(values));
}
/** Create an array schema. */
public static Schema createArray(Schema elementType) {
return new ArraySchema(elementType);
}
/** Create a map schema. */
public static Schema createMap(Schema valueType) {
return new MapSchema(valueType);
}
/** Create a union schema. */
public static Schema createUnion(List<Schema> types) {
return new UnionSchema(new LockableArrayList<Schema>(types));
}
/** Create a union schema. */
public static Schema createUnion(Schema... types) {
return createUnion(new LockableArrayList<Schema>(types));
}
/** Create a union schema. */
public static Schema createFixed(String name, String doc, String space,
int size) {
return new FixedSchema(new Name(name, space), doc, size);
}
/** Return the type of this schema. */
public Type getType() { return type; }
/**
* If this is a record, returns the Field with the
* given name <tt>fieldName</tt>. If there is no field by that name, a
* <tt>null</tt> is returned.
*/
public Field getField(String fieldname) {
throw new AvroRuntimeException("Not a record: "+this);
}
/**
* If this is a record, returns the fields in it. The returned
* list is in the order of their positions.
*/
public List<Field> getFields() {
throw new AvroRuntimeException("Not a record: "+this);
}
/**
* If this is a record, set its fields. The fields can be set
* only once in a schema.
*/
public void setFields(List<Field> fields) {
throw new AvroRuntimeException("Not a record: "+this);
}
/** If this is an enum, return its symbols. */
public List<String> getEnumSymbols() {
throw new AvroRuntimeException("Not an enum: "+this);
}
/** If this is an enum, return a symbol's ordinal value. */
public int getEnumOrdinal(String symbol) {
throw new AvroRuntimeException("Not an enum: "+this);
}
/** If this is an enum, returns true if it contains given symbol. */
public boolean hasEnumSymbol(String symbol) {
throw new AvroRuntimeException("Not an enum: "+this);
}
/** If this is a record, enum or fixed, returns its name, otherwise the name
* of the primitive type. */
public String getName() { return type.name; }
/** If this is a record, enum, or fixed, returns its docstring,
* if available. Otherwise, returns null. */
public String getDoc() {
return null;
}
/** If this is a record, enum or fixed, returns its namespace, if any. */
public String getNamespace() {
throw new AvroRuntimeException("Not a named type: "+this);
}
/** If this is a record, enum or fixed, returns its namespace-qualified name,
* otherwise returns the name of the primitive type. */
public String getFullName() {
return getName();
}
/** If this is a record, enum or fixed, add an alias. */
public void addAlias(String alias) {
throw new AvroRuntimeException("Not a named type: "+this);
}
/** If this is a record, enum or fixed, add an alias. */
public void addAlias(String alias, String space) {
throw new AvroRuntimeException("Not a named type: "+this);
}
/** If this is a record, enum or fixed, return its aliases, if any. */
public Set<String> getAliases() {
throw new AvroRuntimeException("Not a named type: "+this);
}
/** Returns true if this record is an error type. */
public boolean isError() {
throw new AvroRuntimeException("Not a record: "+this);
}
/** If this is an array, returns its element type. */
public Schema getElementType() {
throw new AvroRuntimeException("Not an array: "+this);
}
/** If this is a map, returns its value type. */
public Schema getValueType() {
throw new AvroRuntimeException("Not a map: "+this);
}
/** If this is a union, returns its types. */
public List<Schema> getTypes() {
throw new AvroRuntimeException("Not a union: "+this);
}
/** If this is a union, return the branch with the provided full name. */
public Integer getIndexNamed(String name) {
throw new AvroRuntimeException("Not a union: "+this);
}
/** If this is fixed, returns its size. */
public int getFixedSize() {
throw new AvroRuntimeException("Not fixed: "+this);
}
/** Render this as <a href="http://json.org/">JSON</a>.*/
@Override
public String toString() { return toString(false); }
/** Render this as <a href="http://json.org/">JSON</a>.
* @param pretty if true, pretty-print JSON.
*/
public String toString(boolean pretty) {
try {
StringWriter writer = new StringWriter();
JsonGenerator gen = FACTORY.createJsonGenerator(writer);
if (pretty) gen.useDefaultPrettyPrinter();
toJson(new Names(), gen);
gen.flush();
return writer.toString();
} catch (IOException e) {
throw new AvroRuntimeException(e);
}
}
void toJson(Names names, JsonGenerator gen) throws IOException {
if (props.size() == 0) { // no props defined
gen.writeString(getName()); // just write name
} else {
gen.writeStartObject();
gen.writeStringField("type", getName());
writeProps(gen);
gen.writeEndObject();
}
}
void fieldsToJson(Names names, JsonGenerator gen) throws IOException {
throw new AvroRuntimeException("Not a record: "+this);
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Schema)) return false;
Schema that = (Schema)o;
if (!(this.type == that.type)) return false;
return equalCachedHash(that) && props.equals(that.props);
}
public final int hashCode() {
if (hashCode == NO_HASHCODE)
hashCode = computeHash();
return hashCode;
}
int computeHash() { return getType().hashCode() + props.hashCode(); }
final boolean equalCachedHash(Schema other) {
return (hashCode == other.hashCode)
|| (hashCode == NO_HASHCODE)
|| (other.hashCode == NO_HASHCODE);
}
private static final Set<String> FIELD_RESERVED = new HashSet<String>();
static {
Collections.addAll(FIELD_RESERVED,
"default","doc","name","order","type","aliases");
}
/** A field within a record. */
public static class Field extends JsonProperties {
/** How values of this field should be ordered when sorting records. */
public enum Order {
ASCENDING, DESCENDING, IGNORE;
private String name;
private Order() { this.name = this.name().toLowerCase(Locale.ENGLISH); }
};
private final String name; // name of the field.
private int position = -1;
private final Schema schema;
private final String doc;
private final JsonNode defaultValue;
private final Order order;
private Set<String> aliases;
/** @deprecated use {@link #Field(String, Schema, String, Object)} */
@Deprecated
public Field(String name, Schema schema, String doc,
JsonNode defaultValue) {
this(name, schema, doc, defaultValue, Order.ASCENDING);
}
/** @deprecated use {@link #Field(String, Schema, String, Object, Order)} */
@Deprecated
public Field(String name, Schema schema, String doc,
JsonNode defaultValue, Order order) {
super(FIELD_RESERVED);
this.name = validateName(name);
this.schema = schema;
this.doc = doc;
this.defaultValue = validateDefault(name, schema, defaultValue);
this.order = order;
}
/**
* @param defaultValue the default value for this field specified using the mapping
* in {@link JsonProperties}
*/
public Field(String name, Schema schema, String doc,
Object defaultValue) {
this(name, schema, doc, defaultValue, Order.ASCENDING);
}
/**
* @param defaultValue the default value for this field specified using the mapping
* in {@link JsonProperties}
*/
public Field(String name, Schema schema, String doc,
Object defaultValue, Order order) {
this(name, schema, doc, JacksonUtils.toJsonNode(defaultValue), order);
}
public String name() { return name; };
/** The position of this field within the record. */
public int pos() { return position; }
/** This field's {@link Schema}. */
public Schema schema() { return schema; }
/** Field's documentation within the record, if set. May return null. */
public String doc() { return doc; }
/** @deprecated use {@link #defaultVal() } */
@Deprecated public JsonNode defaultValue() { return defaultValue; }
/**
* @return the default value for this field specified using the mapping
* in {@link JsonProperties}
*/
public Object defaultVal() { return JacksonUtils.toObject(defaultValue, schema); }
public Order order() { return order; }
@Deprecated public Map<String,String> props() { return getProps(); }
public void addAlias(String alias) {
if (aliases == null)
this.aliases = new LinkedHashSet<String>();
aliases.add(alias);
}
/** Return the defined aliases as an unmodifieable Set. */
public Set<String> aliases() {
if (aliases == null)
return Collections.emptySet();
return Collections.unmodifiableSet(aliases);
}
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof Field)) return false;
Field that = (Field) other;
return (name.equals(that.name)) &&
(schema.equals(that.schema)) &&
defaultValueEquals(that.defaultValue) &&
(order == that.order) &&
props.equals(that.props);
}
public int hashCode() { return name.hashCode() + schema.computeHash(); }
private boolean defaultValueEquals(JsonNode thatDefaultValue) {
if (defaultValue == null)
return thatDefaultValue == null;
if (Double.isNaN(defaultValue.getDoubleValue()))
return Double.isNaN(thatDefaultValue.getDoubleValue());
return defaultValue.equals(thatDefaultValue);
}
@Override
public String toString() {
return name + " type:" + schema.type + " pos:" + position;
}
}
static class Name {
private final String name;
private final String space;
private final String full;
public Name(String name, String space) {
if (name == null) { // anonymous
this.name = this.space = this.full = null;
return;
}
int lastDot = name.lastIndexOf('.');
if (lastDot < 0) { // unqualified name
this.name = validateName(name);
} else { // qualified name
space = name.substring(0, lastDot); // get space from name
this.name = validateName(name.substring(lastDot+1, name.length()));
}
if ("".equals(space))
space = null;
this.space = space;
this.full = (this.space == null) ? this.name : this.space+"."+this.name;
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Name)) return false;
Name that = (Name)o;
return full==null ? that.full==null : full.equals(that.full);
}
public int hashCode() {
return full==null ? 0 : full.hashCode();
}
public String toString() { return full; }
public void writeName(Names names, JsonGenerator gen) throws IOException {
if (name != null) gen.writeStringField("name", name);
if (space != null) {
if (!space.equals(names.space()))
gen.writeStringField("namespace", space);
} else if (names.space() != null) { // null within non-null
gen.writeStringField("namespace", "");
}
}
public String getQualified(String defaultSpace) {
return (space == null || space.equals(defaultSpace)) ? name : full;
}
}
private static abstract class NamedSchema extends Schema {
final Name name;
final String doc;
Set<Name> aliases;
public NamedSchema(Type type, Name name, String doc) {
super(type);
this.name = name;
this.doc = doc;
if (PRIMITIVES.containsKey(name.full)) {
throw new AvroTypeException("Schemas may not be named after primitives: " + name.full);
}
}
public String getName() { return name.name; }
public String getDoc() { return doc; }
public String getNamespace() { return name.space; }
public String getFullName() { return name.full; }
public void addAlias(String alias) {
addAlias(alias, null);
}
public void addAlias(String name, String space) {
if (aliases == null)
this.aliases = new LinkedHashSet<Name>();
if (space == null)
space = this.name.space;
aliases.add(new Name(name, space));
}
public Set<String> getAliases() {
Set<String> result = new LinkedHashSet<String>();
if (aliases != null)
for (Name alias : aliases)
result.add(alias.full);
return result;
}
public boolean writeNameRef(Names names, JsonGenerator gen)
throws IOException {
if (this.equals(names.get(name))) {
gen.writeString(name.getQualified(names.space()));
return true;
} else if (name.name != null) {
names.put(name, this);
}
return false;
}
public void writeName(Names names, JsonGenerator gen) throws IOException {
name.writeName(names, gen);
}
public boolean equalNames(NamedSchema that) {
return this.name.equals(that.name);
}
@Override int computeHash() {
return super.computeHash() + name.hashCode();
}
public void aliasesToJson(JsonGenerator gen) throws IOException {
if (aliases == null || aliases.size() == 0) return;
gen.writeFieldName("aliases");
gen.writeStartArray();
for (Name alias : aliases)
gen.writeString(alias.getQualified(name.space));
gen.writeEndArray();
}
}
private static class SeenPair {
private Object s1; private Object s2;
private SeenPair(Object s1, Object s2) { this.s1 = s1; this.s2 = s2; }
public boolean equals(Object o) {
return this.s1 == ((SeenPair)o).s1 && this.s2 == ((SeenPair)o).s2;
}
public int hashCode() {
return System.identityHashCode(s1) + System.identityHashCode(s2);
}
}
private static final ThreadLocal<Set> SEEN_EQUALS = new ThreadLocal<Set>() {
protected Set initialValue() { return new HashSet(); }
};
private static final ThreadLocal<Map> SEEN_HASHCODE = new ThreadLocal<Map>() {
protected Map initialValue() { return new IdentityHashMap(); }
};
@SuppressWarnings(value="unchecked")
private static class RecordSchema extends NamedSchema {
private List<Field> fields;
private Map<String, Field> fieldMap;
private final boolean isError;
public RecordSchema(Name name, String doc, boolean isError) {
super(Type.RECORD, name, doc);
this.isError = isError;
}
public RecordSchema(Name name, String doc, boolean isError,
List<Field> fields) {
super(Type.RECORD, name, doc);
this.isError = isError;
setFields(fields);
}
public boolean isError() { return isError; }
@Override
public Field getField(String fieldname) {
if (fieldMap == null)
throw new AvroRuntimeException("Schema fields not set yet");
return fieldMap.get(fieldname);
}
@Override
public List<Field> getFields() {
if (fields == null)
throw new AvroRuntimeException("Schema fields not set yet");
return fields;
}
@Override
public void setFields(List<Field> fields) {
if (this.fields != null) {
throw new AvroRuntimeException("Fields are already set");
}
int i = 0;
fieldMap = new HashMap<String, Field>();
LockableArrayList ff = new LockableArrayList();
for (Field f : fields) {
if (f.position != -1)
throw new AvroRuntimeException("Field already used: " + f);
f.position = i++;
final Field existingField = fieldMap.put(f.name(), f);
if (existingField != null) {
throw new AvroRuntimeException(String.format(
"Duplicate field %s in record %s: %s and %s.",
f.name(), name, f, existingField));
}
ff.add(f);
}
this.fields = ff.lock();
this.hashCode = NO_HASHCODE;
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof RecordSchema)) return false;
RecordSchema that = (RecordSchema)o;
if (!equalCachedHash(that)) return false;
if (!equalNames(that)) return false;
if (!props.equals(that.props)) return false;
Set seen = SEEN_EQUALS.get();
SeenPair here = new SeenPair(this, o);
if (seen.contains(here)) return true; // prevent stack overflow
boolean first = seen.isEmpty();
try {
seen.add(here);
return fields.equals(((RecordSchema)o).fields);
} finally {
if (first) seen.clear();
}
}
@Override int computeHash() {
Map seen = SEEN_HASHCODE.get();
if (seen.containsKey(this)) return 0; // prevent stack overflow
boolean first = seen.isEmpty();
try {
seen.put(this, this);
return super.computeHash() + fields.hashCode();
} finally {
if (first) seen.clear();
}
}
void toJson(Names names, JsonGenerator gen) throws IOException {
if (writeNameRef(names, gen)) return;
String savedSpace = names.space; // save namespace
gen.writeStartObject();
gen.writeStringField("type", isError?"error":"record");
writeName(names, gen);
names.space = name.space; // set default namespace
if (getDoc() != null)
gen.writeStringField("doc", getDoc());
if (fields != null) {
gen.writeFieldName("fields");
fieldsToJson(names, gen);
}
writeProps(gen);
aliasesToJson(gen);
gen.writeEndObject();
names.space = savedSpace; // restore namespace
}
void fieldsToJson(Names names, JsonGenerator gen) throws IOException {
gen.writeStartArray();
for (Field f : fields) {
gen.writeStartObject();
gen.writeStringField("name", f.name());
gen.writeFieldName("type");
f.schema().toJson(names, gen);
if (f.doc() != null)
gen.writeStringField("doc", f.doc());
if (f.defaultValue() != null) {
gen.writeFieldName("default");
gen.writeTree(f.defaultValue());
}
if (f.order() != Field.Order.ASCENDING)
gen.writeStringField("order", f.order().name);
if (f.aliases != null && f.aliases.size() != 0) {
gen.writeFieldName("aliases");
gen.writeStartArray();
for (String alias : f.aliases)
gen.writeString(alias);
gen.writeEndArray();
}
f.writeProps(gen);
gen.writeEndObject();
}
gen.writeEndArray();
}
}
private static class EnumSchema extends NamedSchema {
private final List<String> symbols;
private final Map<String,Integer> ordinals;
public EnumSchema(Name name, String doc,
LockableArrayList<String> symbols) {
super(Type.ENUM, name, doc);
this.symbols = symbols.lock();
this.ordinals = new HashMap<String,Integer>();
int i = 0;
for (String symbol : symbols)
if (ordinals.put(validateName(symbol), i++) != null)
throw new SchemaParseException("Duplicate enum symbol: "+symbol);
}
public List<String> getEnumSymbols() { return symbols; }
public boolean hasEnumSymbol(String symbol) {
return ordinals.containsKey(symbol); }
public int getEnumOrdinal(String symbol) { return ordinals.get(symbol); }
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof EnumSchema)) return false;
EnumSchema that = (EnumSchema)o;
return equalCachedHash(that)
&& equalNames(that)
&& symbols.equals(that.symbols)
&& props.equals(that.props);
}
@Override int computeHash() { return super.computeHash() + symbols.hashCode(); }
void toJson(Names names, JsonGenerator gen) throws IOException {
if (writeNameRef(names, gen)) return;
gen.writeStartObject();
gen.writeStringField("type", "enum");
writeName(names, gen);
if (getDoc() != null)
gen.writeStringField("doc", getDoc());
gen.writeArrayFieldStart("symbols");
for (String symbol : symbols)
gen.writeString(symbol);
gen.writeEndArray();
writeProps(gen);
aliasesToJson(gen);
gen.writeEndObject();
}
}
private static class ArraySchema extends Schema {
private final Schema elementType;
public ArraySchema(Schema elementType) {
super(Type.ARRAY);
this.elementType = elementType;
}
public Schema getElementType() { return elementType; }
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof ArraySchema)) return false;
ArraySchema that = (ArraySchema)o;
return equalCachedHash(that)
&& elementType.equals(that.elementType)
&& props.equals(that.props);
}
@Override int computeHash() {
return super.computeHash() + elementType.computeHash();
}
void toJson(Names names, JsonGenerator gen) throws IOException {
gen.writeStartObject();
gen.writeStringField("type", "array");
gen.writeFieldName("items");
elementType.toJson(names, gen);
writeProps(gen);
gen.writeEndObject();
}
}
private static class MapSchema extends Schema {
private final Schema valueType;
public MapSchema(Schema valueType) {
super(Type.MAP);
this.valueType = valueType;
}
public Schema getValueType() { return valueType; }
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof MapSchema)) return false;
MapSchema that = (MapSchema)o;
return equalCachedHash(that)
&& valueType.equals(that.valueType)
&& props.equals(that.props);
}
@Override int computeHash() {
return super.computeHash() + valueType.computeHash();
}
void toJson(Names names, JsonGenerator gen) throws IOException {
gen.writeStartObject();
gen.writeStringField("type", "map");
gen.writeFieldName("values");
valueType.toJson(names, gen);
writeProps(gen);
gen.writeEndObject();
}
}
private static class UnionSchema extends Schema {
private final List<Schema> types;
private final Map<String,Integer> indexByName
= new HashMap<String,Integer>();
public UnionSchema(LockableArrayList<Schema> types) {
super(Type.UNION);
this.types = types.lock();
int index = 0;
for (Schema type : types) {
if (type.getType() == Type.UNION)
throw new AvroRuntimeException("Nested union: "+this);
String name = type.getFullName();
if (name == null)
throw new AvroRuntimeException("Nameless in union:"+this);
if (indexByName.put(name, index++) != null)
throw new AvroRuntimeException("Duplicate in union:" + name);
}
}
public List<Schema> getTypes() { return types; }
public Integer getIndexNamed(String name) { return indexByName.get(name); }
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof UnionSchema)) return false;
UnionSchema that = (UnionSchema)o;
return equalCachedHash(that)
&& types.equals(that.types)
&& props.equals(that.props);
}
@Override int computeHash() {
int hash = super.computeHash();
for (Schema type : types)
hash += type.computeHash();
return hash;
}
@Override
public void addProp(String name, String value) {
throw new AvroRuntimeException("Can't set properties on a union: "+this);
}
void toJson(Names names, JsonGenerator gen) throws IOException {
gen.writeStartArray();
for (Schema type : types)
type.toJson(names, gen);
gen.writeEndArray();
}
}
private static class FixedSchema extends NamedSchema {
private final int size;
public FixedSchema(Name name, String doc, int size) {
super(Type.FIXED, name, doc);
if (size < 0)
throw new IllegalArgumentException("Invalid fixed size: "+size);
this.size = size;
}
public int getFixedSize() { return size; }
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof FixedSchema)) return false;
FixedSchema that = (FixedSchema)o;
return equalCachedHash(that)
&& equalNames(that)
&& size == that.size
&& props.equals(that.props);
}
@Override int computeHash() { return super.computeHash() + size; }
void toJson(Names names, JsonGenerator gen) throws IOException {
if (writeNameRef(names, gen)) return;
gen.writeStartObject();
gen.writeStringField("type", "fixed");
writeName(names, gen);
if (getDoc() != null)
gen.writeStringField("doc", getDoc());
gen.writeNumberField("size", size);
writeProps(gen);
aliasesToJson(gen);
gen.writeEndObject();
}
}
private static class StringSchema extends Schema {
public StringSchema() { super(Type.STRING); }
}
private static class BytesSchema extends Schema {
public BytesSchema() { super(Type.BYTES); }
}
private static class IntSchema extends Schema {
public IntSchema() { super(Type.INT); }
}
private static class LongSchema extends Schema {
public LongSchema() { super(Type.LONG); }
}
private static class FloatSchema extends Schema {
public FloatSchema() { super(Type.FLOAT); }
}
private static class DoubleSchema extends Schema {
public DoubleSchema() { super(Type.DOUBLE); }
}
private static class BooleanSchema extends Schema {
public BooleanSchema() { super(Type.BOOLEAN); }
}
private static class NullSchema extends Schema {
public NullSchema() { super(Type.NULL); }
}
/** A parser for JSON-format schemas. Each named schema parsed with a parser
* is added to the names known to the parser so that subsequently parsed
* schemas may refer to it by name. */
public static class Parser {
private Names names = new Names();
private boolean validate = true;
private boolean validateDefaults = false;
/** Adds the provided types to the set of defined, named types known to
* this parser. */
public Parser addTypes(Map<String,Schema> types) {
for (Schema s : types.values())
names.add(s);
return this;
}
/** Returns the set of defined, named types known to this parser. */
public Map<String,Schema> getTypes() {
Map<String,Schema> result = new LinkedHashMap<String,Schema>();
for (Schema s : names.values())
result.put(s.getFullName(), s);
return result;
}
/** Enable or disable name validation. */
public Parser setValidate(boolean validate) {
this.validate = validate;
return this;
}
/** True iff names are validated. True by default. */
public boolean getValidate() { return this.validate; }
/** Enable or disable default value validation. */
public Parser setValidateDefaults(boolean validateDefaults) {
this.validateDefaults = validateDefaults;
return this;
}
/** True iff default values are validated. False by default. */
public boolean getValidateDefaults() { return this.validateDefaults; }
/** Parse a schema from the provided file.
* If named, the schema is added to the names known to this parser. */
public Schema parse(File file) throws IOException {
return parse(FACTORY.createJsonParser(file));
}
/** Parse a schema from the provided stream.