-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
SchemaBuilder.java
2597 lines (2293 loc) · 80.8 KB
/
SchemaBuilder.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.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.avro.Schema.Field;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.io.JsonStringEncoder;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.TextNode;
/**
* <p>
* A fluent interface for building {@link Schema} instances. The flow of the API
* is designed to mimic the <a
* href="http://avro.apache.org/docs/current/spec.html#schemas">Avro Schema
* Specification</a>
* </p>
* For example, the below JSON schema and the fluent builder code to create it
* are very similar:
*
* <pre>
* {
* "type": "record",
* "name": "HandshakeRequest", "namespace":"org.apache.avro.ipc",
* "fields": [
* {"name": "clientHash",
* "type": {"type": "fixed", "name": "MD5", "size": 16}},
* {"name": "clientProtocol", "type": ["null", "string"]},
* {"name": "serverHash", "type": "MD5"},
* {"name": "meta", "type": ["null", {"type": "map", "values": "bytes"}]}
* ]
* }
* </pre>
*
* <pre>
* Schema schema = SchemaBuilder
* .record("HandshakeRequest").namespace("org.apache.avro.ipc)
* .fields()
* .name("clientHash").type().fixed("MD5").size(16).noDefault()
* .name("clientProtocol").type().nullable().stringType().noDefault()
* .name("serverHash").type("MD5")
* .name("meta").type().nullable().map().values().bytesType().noDefault()
* .endRecord();
* </pre>
* <p/>
*
* <h5>Usage Guide</h5>
* SchemaBuilder chains together many smaller builders and maintains nested
* context in order to mimic the Avro Schema specification. Every Avro type in
* JSON has required and optional JSON properties, as well as user-defined
* properties.
* <p/>
* <h6>Selecting and Building an Avro Type</h6>
* The API analogy for the right hand side of the Avro Schema JSON
* <pre>
* "type":
* </pre>
* is a {@link TypeBuilder}, {@link FieldTypeBuilder}, or
* {@link UnionFieldTypeBuilder}, depending on the context. These types all
* share a similar API for selecting and building types.
* <p/>
* <h5>Primitive Types</h5>
* All Avro primitive types are trivial to configure. A primitive type in
* Avro JSON can be declared two ways, one that supports custom properties
* and one that does not:
* <pre>
* {"type":"int"}
* {"type":{"name":"int"}}
* {"type":{"name":"int", "customProp":"val"}}
* </pre>
* The analogous code form for the above three JSON lines are the below
* three lines:
* <pre>
* .intType()
* .intBuilder().endInt()
* .intBuilder().prop("customProp", "val").endInt()
* </pre>
* Every primitive type has a shortcut to create the trivial type, and
* a builder when custom properties are required. The first line above is
* a shortcut for the second, analogous to the JSON case.
* <h6>Named Types</h6>
* Avro named types have names, namespace, aliases, and doc. In this API
* these share a common parent, {@link NamespacedBuilder}.
* The builders for named types require a name to be constructed, and optional
* configuration via:
* <li>{@link NamespacedBuilder#doc()}</li>
* <li>{@link NamespacedBuilder#namespace(String)}</li>
* <li>{@link NamespacedBuilder#aliases(String...)}</li>
* <li>{@link PropBuilder#prop(String, String)}</li>
* <p/>
* Each named type completes configuration of the optional properties
* with its own method:
* <li>{@link FixedBuilder#size(int)}</li>
* <li>{@link EnumBuilder#symbols(String...)}</li>
* <li>{@link RecordBuilder#fields()}</li>
* Example use of a named type with all optional parameters:
* <pre>
* .enumeration("Suit").namespace("org.apache.test")
* .aliases("org.apache.test.OldSuit")
* .doc("CardSuits")
* .prop("customProp", "val")
* .symbols("SPADES", "HEARTS", "DIAMONDS", "CLUBS")
* </pre>
* Which is equivalent to the JSON:
* <pre>
* { "type":"enum",
* "name":"Suit", "namespace":"org.apache.test",
* "aliases":["org.apache.test.OldSuit"],
* "doc":"Card Suits",
* "customProp":"val",
* "symbols":["SPADES", "HEARTS", "DIAMONDS", "CLUBS"]
* }
* </pre>
* <h6>Nested Types</h6>
* The Avro nested types, map and array, can have custom properties like
* all avro types, are not named, and must specify a nested type.
* After configuration of optional properties, an array or map
* builds or selects its nested type with {@link ArrayBuilder#items()}
* and {@link MapBuilder#values()}, respectively.
*
* <h6>Fields</h6>
* {@link RecordBuilder#fields()} returns a {@link FieldAssembler} for
* defining the fields of the record and completing it.
* Each field must have a name, specified via {@link FieldAssembler#name(String)},
* which returns a {@link FieldBuilder} for defining aliases, custom properties,
* and documentation of the field. After configuring these optional values for
* a field, the type is selected or built with {@link FieldBuilder#type()}.
* <p/>
* Fields have default values that must be specified to complete the field.
* {@link FieldDefault#noDefault()} is available for all field types, and
* a specific method is available for each type to use a default, for example
* {@link IntDefault#intDefault(int)}
* <p/>
* There are field shortcut methods on {@link FieldAssembler} for primitive types.
* These shortcuts create required, optional, and nullable fields, but do not
* support field aliases, doc, or custom properties.
*
* <h6>Unions</h6>
* Union types are built via {@link TypeBuilder#unionOf()} or
* {@link FieldTypeBuilder#unionOf()} in the context of type selection.
* This chains together multiple types, in union order. For example:
* <pre>
* .unionOf()
* .fixed("IPv4").size(4).and()
* .fixed("IPv6").size(16).and()
* .nullType().endUnion()
* </pre>
* is equivalent to the Avro schema JSON:
* <pre>
* [
* {"type":"fixed", "name":"IPv4", "size":4},
* {"type":"fixed", "name":"IPv6", "size":16},
* "null"
* ]
* </pre>
* In a field context, the first type of a union defines what default type
* is allowed.
* </p>
* Unions have two shortcuts for common cases. nullable()
* creates a union of a type and null. In a field type context, optional()
* is available and creates a union of null and a type, with a null default.
* The below two are equivalent:
* <pre>
* .unionOf().intType().and().nullType().endUnion()
* .nullable().intType()
* </pre>
* The below two field declarations are equivalent:
* <pre>
* .name("f").type().unionOf().nullType().and().longType().endUnion().nullDefault()
* .name("f").type().optional().longType()
* </pre>
*
* <h6>Explicit Types and Types by Name</h6>
* Types can also be specified explicitly by passing in a Schema, or by name:
* <pre>
* .type(Schema.create(Schema.Type.INT)) // explicitly specified
* .type("MD5") // reference by full name or short name
* .type("MD5", "org.apache.avro.test") // reference by name and namespace
* </pre>
* When a type is specified by name, and the namespace is absent or null, the
* namespace is inherited from the enclosing context. A namespace will
* propagate as a default to child fields, nested types, or later defined types
* in a union. To specify a name that has no namespace and ignore the inherited
* namespace, set the namespace to "".
* <p/>
* {@link SchemaBuilder#builder(String)} returns a type builder with a default
* namespace. {@link SchemaBuilder#builder()} returns a type builder with no
* default namespace.
*/
public class SchemaBuilder {
private SchemaBuilder() {
}
/**
* Create a builder for Avro schemas.
*/
public static TypeBuilder<Schema> builder() {
return new TypeBuilder<Schema>(new SchemaCompletion(), new NameContext());
}
/**
* Create a builder for Avro schemas with a default namespace. Types created
* without namespaces will inherit the namespace provided.
*/
public static TypeBuilder<Schema> builder(String namespace) {
return new TypeBuilder<Schema>(new SchemaCompletion(),
new NameContext().namespace(namespace));
}
/**
* Create a builder for an Avro record with the specified name.
* This is equivalent to:
* <pre>
* builder().record(name);
* </pre>
* @param name the record name
*/
public static RecordBuilder<Schema> record(String name) {
return builder().record(name);
}
/**
* Create a builder for an Avro enum with the specified name and symbols (values).
* This is equivalent to:
* <pre>
* builder().enumeration(name);
* </pre>
* @param name the enum name
*/
public static EnumBuilder<Schema> enumeration(String name) {
return builder().enumeration(name);
}
/**
* Create a builder for an Avro fixed type with the specified name and size.
* This is equivalent to:
* <pre>
* builder().fixed(name);
* </pre>
* @param name the fixed name
*/
public static FixedBuilder<Schema> fixed(String name) {
return builder().fixed(name);
}
/**
* Create a builder for an Avro array
* This is equivalent to:
* <pre>
* builder().array();
* </pre>
*/
public static ArrayBuilder<Schema> array() {
return builder().array();
}
/**
* Create a builder for an Avro map
* This is equivalent to:
* <pre>
* builder().map();
* </pre>
*/
public static MapBuilder<Schema> map() {
return builder().map();
}
/**
* Create a builder for an Avro union
* This is equivalent to:
* <pre>
* builder().unionOf();
* </pre>
*/
public static BaseTypeBuilder<UnionAccumulator<Schema>> unionOf() {
return builder().unionOf();
}
/**
* Create a builder for a union of a type and null.
* This is a shortcut for:
* <pre>
* builder().nullable();
* </pre>
* and the following two lines are equivalent:
* <pre>
* nullable().intType();
* </pre>
* <pre>
* unionOf().intType().and().nullType().endUnion();
* </pre>
*/
public static BaseTypeBuilder<Schema> nullable() {
return builder().nullable();
}
/**
* An abstract builder for all Avro types. All Avro types
* can have arbitrary string key-value properties.
*/
public static abstract class PropBuilder<S extends PropBuilder<S>> {
private Map<String, JsonNode> props = null;
protected PropBuilder() {
}
/**
* Set name-value pair properties for this type or field.
*/
public final S prop(String name, String val) {
return prop(name, TextNode.valueOf(val));
}
// for internal use by the Parser
final S prop(String name, JsonNode val) {
if(!hasProps()) {
props = new HashMap<String, JsonNode>();
}
props.put(name, val);
return self();
}
private boolean hasProps() {
return (props != null);
}
final <T extends JsonProperties> T addPropsTo(T jsonable) {
if (hasProps()) {
for(Map.Entry<String, JsonNode> prop : props.entrySet()) {
jsonable.addProp(prop.getKey(), prop.getValue());
}
}
return jsonable;
}
/** a self-type for chaining builder subclasses. Concrete subclasses
* must return 'this' **/
protected abstract S self();
}
/**
* An abstract type that provides builder methods for configuring the name,
* doc, and aliases of all Avro types that have names (fields, Fixed, Record,
* and Enum).
* <p/>
* All Avro named types and fields have 'doc', 'aliases', and 'name'
* components. 'name' is required, and provided to this builder. 'doc' and
* 'alises' are optional.
*/
public static abstract class NamedBuilder<S extends NamedBuilder<S>> extends
PropBuilder<S> {
private final String name;
private final NameContext names;
private String doc;
private String[] aliases;
protected NamedBuilder(NameContext names, String name) {
checkRequired(name, "Type must have a name");
this.names = names;
this.name = name;
}
/** configure this type's optional documentation string **/
public final S doc(String doc) {
this.doc = doc;
return self();
}
/** configure this type's optional name aliases **/
public final S aliases(String... aliases) {
this.aliases = aliases;
return self();
}
final String doc() {
return doc;
}
final String name() {
return name;
}
final NameContext names() {
return names;
}
final Schema addAliasesTo(Schema schema) {
if (null != aliases) {
for (String alias : aliases) {
schema.addAlias(alias);
}
}
return schema;
}
final Field addAliasesTo(Field field) {
if (null != aliases) {
for (String alias : aliases) {
field.addAlias(alias);
}
}
return field;
}
}
/**
* An abstract type that provides builder methods for configuring the
* namespace for all Avro types that have namespaces (Fixed, Record, and
* Enum).
*/
public static abstract class NamespacedBuilder<R, S extends NamespacedBuilder<R, S>>
extends NamedBuilder<S> {
private final Completion<R> context;
private String namespace;
protected NamespacedBuilder(Completion<R> context, NameContext names,
String name) {
super(names, name);
this.context = context;
}
/**
* Set the namespace of this type. To clear the namespace, set empty string.
* <p/>
* When the namespace is null or unset, the namespace of the type defaults
* to the namespace of the enclosing context.
**/
public final S namespace(String namespace) {
this.namespace = namespace;
return self();
}
final String space() {
if (null == namespace) {
return names().namespace;
}
return namespace;
}
final Schema completeSchema(Schema schema) {
addPropsTo(schema);
addAliasesTo(schema);
names().put(schema);
return schema;
}
final Completion<R> context() {
return context;
}
}
/**
* An abstraction for sharing code amongst all primitive type builders.
*/
private static abstract class PrimitiveBuilder<R, P extends PrimitiveBuilder<R, P>>
extends PropBuilder<P> {
private final Completion<R> context;
private final Schema immutable;
protected PrimitiveBuilder(Completion<R> context, NameContext names,
Schema.Type type) {
this.context = context;
this.immutable = names.getFullname(type.getName());
}
private R end() {
Schema schema = immutable;
if (super.hasProps()) {
schema = Schema.create(immutable.getType());
addPropsTo(schema);
}
return context.complete(schema);
}
}
/**
* Builds an Avro boolean type with optional properties. Set properties with
* {@link #prop(String, String)}, and finalize with {@link #endBoolean()}
**/
public static final class BooleanBuilder<R> extends
PrimitiveBuilder<R, BooleanBuilder<R>> {
private BooleanBuilder(Completion<R> context, NameContext names) {
super(context, names, Schema.Type.BOOLEAN);
}
private static <R> BooleanBuilder<R> create(Completion<R> context,
NameContext names) {
return new BooleanBuilder<R>(context, names);
}
@Override
protected BooleanBuilder<R> self() {
return this;
}
/** complete building this type, return control to context **/
public R endBoolean() {
return super.end();
}
}
/**
* Builds an Avro int type with optional properties. Set properties with
* {@link #prop(String, String)}, and finalize with {@link #endInt()}
**/
public static final class IntBuilder<R> extends
PrimitiveBuilder<R, IntBuilder<R>> {
private IntBuilder(Completion<R> context, NameContext names) {
super(context, names, Schema.Type.INT);
}
private static <R> IntBuilder<R> create(Completion<R> context,
NameContext names) {
return new IntBuilder<R>(context, names);
}
@Override
protected IntBuilder<R> self() {
return this;
}
/** complete building this type, return control to context **/
public R endInt() {
return super.end();
}
}
/**
* Builds an Avro long type with optional properties. Set properties with
* {@link #prop(String, String)}, and finalize with {@link #endLong()}
**/
public static final class LongBuilder<R> extends
PrimitiveBuilder<R, LongBuilder<R>> {
private LongBuilder(Completion<R> context, NameContext names) {
super(context, names, Schema.Type.LONG);
}
private static <R> LongBuilder<R> create(Completion<R> context,
NameContext names) {
return new LongBuilder<R>(context, names);
}
@Override
protected LongBuilder<R> self() {
return this;
}
/** complete building this type, return control to context **/
public R endLong() {
return super.end();
}
}
/**
* Builds an Avro float type with optional properties. Set properties with
* {@link #prop(String, String)}, and finalize with {@link #endFloat()}
**/
public static final class FloatBuilder<R> extends
PrimitiveBuilder<R, FloatBuilder<R>> {
private FloatBuilder(Completion<R> context, NameContext names) {
super(context, names, Schema.Type.FLOAT);
}
private static <R> FloatBuilder<R> create(Completion<R> context,
NameContext names) {
return new FloatBuilder<R>(context, names);
}
@Override
protected FloatBuilder<R> self() {
return this;
}
/** complete building this type, return control to context **/
public R endFloat() {
return super.end();
}
}
/**
* Builds an Avro double type with optional properties. Set properties with
* {@link #prop(String, String)}, and finalize with {@link #endDouble()}
**/
public static final class DoubleBuilder<R> extends
PrimitiveBuilder<R, DoubleBuilder<R>> {
private DoubleBuilder(Completion<R> context, NameContext names) {
super(context, names, Schema.Type.DOUBLE);
}
private static <R> DoubleBuilder<R> create(Completion<R> context,
NameContext names) {
return new DoubleBuilder<R>(context, names);
}
@Override
protected DoubleBuilder<R> self() {
return this;
}
/** complete building this type, return control to context **/
public R endDouble() {
return super.end();
}
}
/**
* Builds an Avro string type with optional properties. Set properties with
* {@link #prop(String, String)}, and finalize with {@link #endString()}
**/
public static final class StringBldr<R> extends
PrimitiveBuilder<R, StringBldr<R>> {
private StringBldr(Completion<R> context, NameContext names) {
super(context, names, Schema.Type.STRING);
}
private static <R> StringBldr<R> create(Completion<R> context,
NameContext names) {
return new StringBldr<R>(context, names);
}
@Override
protected StringBldr<R> self() {
return this;
}
/** complete building this type, return control to context **/
public R endString() {
return super.end();
}
}
/**
* Builds an Avro bytes type with optional properties. Set properties with
* {@link #prop(String, String)}, and finalize with {@link #endBytes()}
**/
public static final class BytesBuilder<R> extends
PrimitiveBuilder<R, BytesBuilder<R>> {
private BytesBuilder(Completion<R> context, NameContext names) {
super(context, names, Schema.Type.BYTES);
}
private static <R> BytesBuilder<R> create(Completion<R> context,
NameContext names) {
return new BytesBuilder<R>(context, names);
}
@Override
protected BytesBuilder<R> self() {
return this;
}
/** complete building this type, return control to context **/
public R endBytes() {
return super.end();
}
}
/**
* Builds an Avro null type with optional properties. Set properties with
* {@link #prop(String, String)}, and finalize with {@link #endNull()}
**/
public static final class NullBuilder<R> extends
PrimitiveBuilder<R, NullBuilder<R>> {
private NullBuilder(Completion<R> context, NameContext names) {
super(context, names, Schema.Type.NULL);
}
private static <R> NullBuilder<R> create(Completion<R> context,
NameContext names) {
return new NullBuilder<R>(context, names);
}
@Override
protected NullBuilder<R> self() {
return this;
}
/** complete building this type, return control to context **/
public R endNull() {
return super.end();
}
}
/**
* Builds an Avro Fixed type with optional properties, namespace, doc, and
* aliases.
* <p/>
* Set properties with {@link #prop(String, String)}, namespace with
* {@link #namespace(String)}, doc with {@link #doc(String)}, and aliases with
* {@link #aliases(String[])}.
* <p/>
* The Fixed schema is finalized when its required size is set via
* {@link #size(int)}.
**/
public static final class FixedBuilder<R> extends
NamespacedBuilder<R, FixedBuilder<R>> {
private FixedBuilder(Completion<R> context, NameContext names, String name) {
super(context, names, name);
}
private static <R> FixedBuilder<R> create(Completion<R> context,
NameContext names, String name) {
return new FixedBuilder<R>(context, names, name);
}
@Override
protected FixedBuilder<R> self() {
return this;
}
/** Configure this fixed type's size, and end its configuration. **/
public R size(int size) {
Schema schema = Schema.createFixed(name(), super.doc(), space(), size);
completeSchema(schema);
return context().complete(schema);
}
}
/**
* Builds an Avro Enum type with optional properties, namespace, doc, and
* aliases.
* <p/>
* Set properties with {@link #prop(String, String)}, namespace with
* {@link #namespace(String)}, doc with {@link #doc(String)}, and aliases with
* {@link #aliases(String[])}.
* <p/>
* The Enum schema is finalized when its required symbols are set via
* {@link #symbols(String[])}.
**/
public static final class EnumBuilder<R> extends
NamespacedBuilder<R, EnumBuilder<R>> {
private EnumBuilder(Completion<R> context, NameContext names, String name) {
super(context, names, name);
}
private static <R> EnumBuilder<R> create(Completion<R> context,
NameContext names, String name) {
return new EnumBuilder<R>(context, names, name);
}
@Override
protected EnumBuilder<R> self() {
return this;
}
/** Configure this enum type's symbols, and end its configuration. **/
public R symbols(String... symbols) {
Schema schema = Schema.createEnum(name(), doc(), space(),
Arrays.asList(symbols));
completeSchema(schema);
return context().complete(schema);
}
}
/**
* Builds an Avro Map type with optional properties.
* <p/>
* Set properties with {@link #prop(String, String)}.
* <p/>
* The Map schema's properties are finalized when {@link #values()} or
* {@link #values(Schema)} is called.
**/
public static final class MapBuilder<R> extends PropBuilder<MapBuilder<R>> {
private final Completion<R> context;
private final NameContext names;
private MapBuilder(Completion<R> context, NameContext names) {
this.context = context;
this.names = names;
}
private static <R> MapBuilder<R> create(Completion<R> context,
NameContext names) {
return new MapBuilder<R>(context, names);
}
@Override
protected MapBuilder<R> self() {
return this;
}
/**
* Return a type builder for configuring the map's nested values schema.
* This builder will return control to the map's enclosing context when
* complete.
**/
public TypeBuilder<R> values() {
return new TypeBuilder<R>(new MapCompletion<R>(this, context), names);
}
/**
* Complete configuration of this map, setting the schema of the map values
* to the schema provided. Returns control to the enclosing context.
**/
public R values(Schema valueSchema) {
return new MapCompletion<R>(this, context).complete(valueSchema);
}
}
/**
* Builds an Avro Array type with optional properties.
* <p/>
* Set properties with {@link #prop(String, String)}.
* <p/>
* The Array schema's properties are finalized when {@link #items()} or
* {@link #items(Schema)} is called.
**/
public static final class ArrayBuilder<R> extends
PropBuilder<ArrayBuilder<R>> {
private final Completion<R> context;
private final NameContext names;
public ArrayBuilder(Completion<R> context, NameContext names) {
this.context = context;
this.names = names;
}
private static <R> ArrayBuilder<R> create(Completion<R> context,
NameContext names) {
return new ArrayBuilder<R>(context, names);
}
@Override
protected ArrayBuilder<R> self() {
return this;
}
/**
* Return a type builder for configuring the array's nested items schema.
* This builder will return control to the array's enclosing context when
* complete.
**/
public TypeBuilder<R> items() {
return new TypeBuilder<R>(new ArrayCompletion<R>(this, context), names);
}
/**
* Complete configuration of this array, setting the schema of the array
* items to the schema provided. Returns control to the enclosing context.
**/
public R items(Schema itemsSchema) {
return new ArrayCompletion<R>(this, context).complete(itemsSchema);
}
}
/**
* internal class for passing the naming context around. This allows for the
* following:
* <li>Cache and re-use primitive schemas when they do not set
* properties.</li>
* <li>Provide a default namespace for nested contexts (as
* the JSON Schema spec does).</li>
* <li>Allow previously defined named types or primitive types
* to be referenced by name.</li>
**/
private static class NameContext {
private static final Set<String> PRIMITIVES = new HashSet<String>();
{
PRIMITIVES.add("null");
PRIMITIVES.add("boolean");
PRIMITIVES.add("int");
PRIMITIVES.add("long");
PRIMITIVES.add("float");
PRIMITIVES.add("double");
PRIMITIVES.add("bytes");
PRIMITIVES.add("string");
}
private final HashMap<String, Schema> schemas;
private final String namespace;
private NameContext() {
this.schemas = new HashMap<String, Schema>();
this.namespace = null;
schemas.put("null", Schema.create(Schema.Type.NULL));
schemas.put("boolean", Schema.create(Schema.Type.BOOLEAN));
schemas.put("int", Schema.create(Schema.Type.INT));
schemas.put("long", Schema.create(Schema.Type.LONG));
schemas.put("float", Schema.create(Schema.Type.FLOAT));
schemas.put("double", Schema.create(Schema.Type.DOUBLE));
schemas.put("bytes", Schema.create(Schema.Type.BYTES));
schemas.put("string", Schema.create(Schema.Type.STRING));
}
private NameContext(HashMap<String, Schema> schemas, String namespace) {
this.schemas = schemas;
this.namespace = "".equals(namespace) ? null : namespace;
}
private NameContext namespace(String namespace) {
return new NameContext(schemas, namespace);
}
private Schema get(String name, String namespace) {
return getFullname(resolveName(name, namespace));
}
private Schema getFullname(String fullName) {
Schema schema = schemas.get(fullName);
if(schema == null) {
throw new SchemaParseException("Undefined name: " + fullName);
}
return schema;
}
private void put(Schema schema) {
String fullName = schema.getFullName();
if(schemas.containsKey(fullName)){
throw new SchemaParseException("Can't redefine: " + fullName);
}
schemas.put(fullName, schema);
}
private String resolveName(String name, String space) {
if (PRIMITIVES.contains(name) && space == null) {
return name;
}
int lastDot = name.lastIndexOf('.');
if (lastDot < 0) { // short name
if (space == null) {
space = namespace;
}
if (space != null && !"".equals(space)) {
return space + "." + name;
}
}
return name;
}
}
/**
* A common API for building types within a context. BaseTypeBuilder can build
* all types other than Unions. {@link TypeBuilder} can additionally build
* Unions.
* <p/>
* The builder has two contexts:
* <li>A naming context provides a default namespace and allows for previously
* defined named types to be referenced from {@link #type(String)}</li>
* <li>A completion context representing the scope that the builder was
* created in. A builder created in a nested context (for example,
* {@link #MapBuilder.values()} will have a completion context assigned by the
* {@link MapBuilder}</li>
**/
public static class BaseTypeBuilder<R> {
private final Completion<R> context;
private final NameContext names;
private BaseTypeBuilder(Completion<R> context, NameContext names) {
this.context = context;
this.names = names;
}
/** Use the schema provided as the type. **/
public final R type(Schema schema) {
return context.complete(schema);
}
/**
* Look up the type by name. This type must be previously defined in the
* context of this builder.
* <p/>
* The name may be fully qualified or a short name. If it is a short name,
* the default namespace of the current context will additionally be
* searched.
**/
public final R type(String name) {
return type(name, null);
}
/**
* Look up the type by name and namespace. This type must be previously
* defined in the context of this builder.
* <p/>