forked from C0urante/avro-random-generator
/
Generator.java
1683 lines (1552 loc) · 58.2 KB
/
Generator.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
/*
Copyright 2018 Confluent Inc.
Licensed 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 io.confluent.avro.random.generator;
import com.mifmif.common.regex.Generex;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.apache.avro.LogicalType;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericEnumSymbol;
import org.apache.avro.generic.GenericFixed;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.generic.GenericRecordBuilder;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.RoundingMode;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
/**
* Generates Java objects according to an {@link Schema Avro Schema}.
*/
@SuppressWarnings("WeakerAccess")
public class Generator {
private final Map<Schema, Generex> generexCache = new HashMap<>();
private final Map<Schema, List<Object>> optionsCache = new HashMap<>();
private final Map<Schema, Iterator<Object>> iteratorCache = new IdentityHashMap<>();
/**
* The name to use for the top-level JSON property when specifying ARG-specific attributes.
*/
public static final String ARG_PROPERTIES_PROP = "arg.properties";
/**
* The name of the attribute for specifying length for supported schemas. Can be given as either
* an integral number or an object with at least one of {@link #LENGTH_PROP_MIN} or
* {@link #LENGTH_PROP_MAX} specified.
*/
public static final String LENGTH_PROP = "length";
/**
* The name of the attribute for specifying the minimum length a generated value should have.
* Must be given as an integral number greater than or equal to zero.
*/
public static final String LENGTH_PROP_MIN = "min";
/**
* The name of the attribute for specifying the maximum length a generated value should have.
* Must be given as an integral number strictly greater than the value given for
* {@link #LENGTH_PROP_MIN}, or strictly greater than zero if none is specified.
*/
public static final String LENGTH_PROP_MAX = "max";
/**
* The name of the attribute for specifying a regex that generated values should adhere to. Can
* be used in conjunction with {@link #LENGTH_PROP}. Must be given as a string.
*/
public static final String REGEX_PROP = "regex";
/**
* The name of the attribute for specifying a prefix that generated values should begin with. Will
* be prepended to the beginning of any string values generated. Can be used in conjunction with
* {@link #SUFFIX_PROP}.
*/
public static final String PREFIX_PROP = "prefix";
/**
* The name of the attribute for specifying a suffix that generated values should end with. Will
* be appended to the end of any string values generated. Can be used in conjunction with
* {@link #PREFIX_PROP}.
*/
public static final String SUFFIX_PROP = "suffix";
/**
* The name of the attribute for specifying specific values which should be randomly chosen from
* when generating values for the schema. Can be given as either an array of values or an object
* with both {@link #OPTIONS_PROP_FILE} and {@link #OPTIONS_PROP_ENCODING}
* specified.
*/
public static final String OPTIONS_PROP = "options";
/**
* The name of a file from which to read specific values to generate for the given schema. Must
* be given as a string.
*/
public static final String OPTIONS_PROP_FILE = "file";
/**
* The encoding of the options file; currently only "binary" and "json" are supported. Must be
* given as a string.
*/
public static final String OPTIONS_PROP_ENCODING = "encoding";
/**
* The name of the attribute for specifying special properties for keys in map schemas. Since
* all Avro maps have keys of type string, no schema is supplied to specify key attributes; this
* special keys attribute takes its place. Must be given as an object.
*/
public static final String KEYS_PROP = "keys";
/**
* The name of the attribute for specifying a possible range of values for numeric types. Must be
* given as an object.
*/
public static final String RANGE_PROP = "range";
/**
* The name of the attribute for specifying the (inclusive) minimum value in a range. Must be
* given as a numeric type that is integral if the given schema is as well.
*/
public static final String RANGE_PROP_MIN = "min";
/**
* The name of the attribute for specifying the (exclusive) maximum value in a range. Must be
* given as a numeric type that is integral if the given schema is as well.
*/
public static final String RANGE_PROP_MAX = "max";
/**
* The name of the attribute for specifying the likelihood that the value true is generated for a
* boolean schema. Must be given as a floating type in the range [0.0, 1.0].
*/
public static final String ODDS_PROP = "odds";
/**
* The name of the attribute for specifying iterative behavior for generated values. Must be
* given as an object with at least the {@link #ITERATION_PROP_START} property specified. The
* first generated value for the schema will then be equal to the value given for
* {@link #ITERATION_PROP_START}, and successive values will increment by the value given for
* {@link #ITERATION_PROP_STEP} (or its default, if no value is given), wrapping around at the
* value given for {@link #ITERATION_PROP_RESTART} (or its default, if no value is given).
*/
public static final String ITERATION_PROP = "iteration";
/**
* The name of the attribute for specifying the first value in a schema with iterative
* generation. Must be given as a numeric type that is integral if the given schema is as well.
*/
public static final String ITERATION_PROP_START = "start";
/**
* The name of the attribute for specifying the wraparound value in a schema with iterative
* generation. If given, must be a numeric type that is integral if the given schema is as well.
* If not given, defaults to the maximum possible value for the schema type if the value for
* {@link #ITERATION_PROP_STEP} is positive, or the minimum possible value for the schema type if
* the value for {@link #ITERATION_PROP_STEP} is negative.
*/
public static final String ITERATION_PROP_RESTART = "restart";
/**
* The name of the attribute for specifying the increment value in a schema with iterative
* generation. If given, must be a numeric type that is integral if the given schema is as well.
* If not given, defaults to 1 if the value for {@link #ITERATION_PROP_RESTART} is greater than
* the value for {@link #ITERATION_PROP_START}, and -1 if the value for
* {@link #ITERATION_PROP_RESTART} is less than the value for {@link #ITERATION_PROP_START}.
*/
public static final String ITERATION_PROP_STEP = "step";
/**
* The name of the attribute for specifying the initial value in a schema with iterative
* generation. If given, must be a numeric type that is integral if the given schema is as well.
* If not given, defaults to the value for {@link #ITERATION_PROP_START}.
*/
public static final String ITERATION_PROP_INITIAL = "initial";
static final String DECIMAL_LOGICAL_TYPE_NAME = "decimal";
private final Schema topLevelSchema;
private final Random random;
private final long generation;
/**
* Creates a generator out of an already-parsed {@link Schema}.
* @param topLevelSchema The schema to generate values for.
* @param random The object to use for generating randomness when producing values.
*/
@Deprecated
public Generator(Schema topLevelSchema, Random random) {
this(topLevelSchema, random, 0L);
}
protected Generator(Schema topLevelSchema, Random random, long generation) {
this.topLevelSchema = topLevelSchema;
this.random = random;
this.generation = generation;
}
/**
* Creates a generator out of the yet-to-be-parsed Schema string.
* @param schemaString An Avro Schema represented as a string.
* @param random The object to use for generating randomness when producing values.
*/
@Deprecated
public Generator(String schemaString, Random random) {
this(new Schema.Parser().parse(schemaString), random);
}
/**
* Reads in a schema, parses it, and creates a generator for it.
* @param schemaStream The stream that the schema is read from.
* @param random The object to use for generating randomness when producing values.
* @throws IOException if an error occurs while reading from the input stream.
*/
@Deprecated
public Generator(InputStream schemaStream, Random random) throws IOException {
this(new Schema.Parser().parse(schemaStream), random);
}
/**
* Reads in a schema, parses it, and creates a generator for it.
* @param schemaFile The file that contains the schema to generate values for.
* @param random The object to use for generating randomness when producing values.
* @throws IOException if an error occurs while reading from the schema file.
*/
@Deprecated
public Generator(File schemaFile, Random random) throws IOException {
this(new Schema.Parser().parse(schemaFile), random);
}
public static class Builder {
private Schema topLevelSchema;
private Random random;
private long generation;
private Schema.Parser parser;
public Builder() {
parser = new Schema.Parser();
random = new Random();
generation = 0L;
}
public Builder schema(Schema schema) {
topLevelSchema = schema;
return this;
}
public Builder schemaFile(File schemaFile) throws IOException {
topLevelSchema = parser.parse(schemaFile);
return this;
}
public Builder schemaStream(InputStream schemaStream) throws IOException {
topLevelSchema = parser.parse(schemaStream);
return this;
}
public Builder schemaString(String schemaString) {
topLevelSchema = parser.parse(schemaString);
return this;
}
public Builder random(Random random) {
this.random = random;
return this;
}
public Builder generation(long generation) {
this.generation = generation;
return this;
}
public Generator build() {
return new Generator(topLevelSchema, random, generation);
}
}
/**
* @return The schema that the generator produces values for.
*/
public Schema schema() {
return topLevelSchema;
}
/**
* Generate an object that matches the given schema and its specified properties.
* @return An object whose type corresponds to the top-level schema as follows:
* <table summary="Schema Type-to-Java class specifications">
* <tr>
* <th>Schema Type</th>
* <th>Java Class</th>
* </tr>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#ARRAY ARRAY}</td>
* <td>{@link Collection}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#BOOLEAN BOOLEAN}</td>
* <td>{@link Boolean}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#BYTES BYTES}</td>
* <td>{@link ByteBuffer}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#DOUBLE DOUBLE}</td>
* <td>{@link Double}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#ENUM ENUM}</td>
* <td>{@link GenericEnumSymbol}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#FIXED FIXED}</td>
* <td>{@link GenericFixed}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#FLOAT FLOAT}</td>
* <td>{@link Float}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#INT INT}</td>
* <td>{@link Integer}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#LONG LONG}</td>
* <td>{@link Long}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#MAP MAP}</td>
* <td>
* {@link Map}<{@link String}, V> where V is the corresponding Java class for the
* Avro map's values
* </td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#NULL NULL}</td>
* <td>{@link Object} (but will always be null)</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#RECORD RECORD}</td>
* <td>{@link GenericRecord}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#STRING STRING}</td>
* <td>{@link String}</td>
* <tr>
* <td>{@link org.apache.avro.Schema.Type#UNION UNION}</td>
* <td>
* The corresponding Java class for whichever schema is chosen to be generated out of the
* ones present in the given Avro union.
* </td>
* </table>
*/
public Object generate() {
return generateObject(topLevelSchema);
}
private Object generateObject(Schema schema) {
Map propertiesProp = getProperties(schema).orElse(Collections.emptyMap());
if (propertiesProp.containsKey(OPTIONS_PROP)) {
return generateOption(schema, propertiesProp);
}
if (propertiesProp.containsKey(ITERATION_PROP)) {
return generateIteration(schema, propertiesProp);
}
switch (schema.getType()) {
case ARRAY:
return generateArray(schema, propertiesProp);
case BOOLEAN:
return generateBoolean(propertiesProp);
case BYTES:
return generateBytes(schema, propertiesProp);
case DOUBLE:
return generateDouble(propertiesProp);
case ENUM:
return generateEnumSymbol(schema);
case FIXED:
return generateFixed(schema);
case FLOAT:
return generateFloat(propertiesProp);
case INT:
return generateInt(propertiesProp);
case LONG:
return generateLong(propertiesProp);
case MAP:
return generateMap(schema, propertiesProp);
case NULL:
return generateNull();
case RECORD:
return generateRecord(schema);
case STRING:
return generateString(schema, propertiesProp);
case UNION:
return generateUnion(schema);
default:
throw new RuntimeException("Unrecognized schema type: " + schema.getType());
}
}
private Optional<Map> getProperties(Schema schema) {
Object propertiesProp = schema.getObjectProp(ARG_PROPERTIES_PROP);
if (propertiesProp == null) {
return Optional.empty();
} else if (propertiesProp instanceof Map) {
return Optional.of((Map) propertiesProp);
} else {
throw new RuntimeException(String.format(
"%s property must be given as object, was %s instead",
ARG_PROPERTIES_PROP,
propertiesProp.getClass().getName()
));
}
}
private <L extends LogicalType> L getLogicalType(
Schema schema,
String logicalTypeName,
Class<L> logicalTypeClass
) {
return Optional.ofNullable(schema.getLogicalType())
.filter(logicalType -> Objects.equals(logicalTypeName, logicalType.getName()))
.map(logicalTypeClass::cast)
.orElse(null);
}
private LogicalTypes.Decimal getDecimalLogicalType(Schema schema) {
return getLogicalType(schema, DECIMAL_LOGICAL_TYPE_NAME, LogicalTypes.Decimal.class);
}
private void enforceMutualExclusion(
Map propertiesProp,
String includedProp,
String... excludedProps) {
for (String excludedProp : excludedProps) {
if (propertiesProp.containsKey(excludedProp)) {
throw new RuntimeException(String.format(
"Cannot specify %s prop when %s prop is given",
excludedProp,
includedProp
));
}
}
}
@SuppressWarnings("unchecked")
private Object wrapOption(Schema schema, Object option) {
if (schema.getType() == Schema.Type.BYTES && option instanceof String) {
option = ByteBuffer.wrap(((String) option).getBytes(Charset.defaultCharset()));
} else if (schema.getType() == Schema.Type.FLOAT && option instanceof Double) {
option = ((Double) option).floatValue();
} else if (schema.getType() == Schema.Type.LONG && option instanceof Integer) {
option = ((Integer) option).longValue();
} else if (schema.getType() == Schema.Type.ARRAY && option instanceof Collection) {
option = new GenericData.Array(schema, (Collection) option);
} else if (schema.getType() == Schema.Type.ENUM && option instanceof String) {
option = new GenericData.EnumSymbol(schema, (String) option);
} else if (schema.getType() == Schema.Type.FIXED && option instanceof String) {
option =
new GenericData.Fixed(schema, ((String) option).getBytes(Charset.defaultCharset()));
} else if (schema.getType() == Schema.Type.RECORD && option instanceof Map) {
Map optionMap = (Map) option;
GenericRecordBuilder optionBuilder = new GenericRecordBuilder(schema);
for (Schema.Field field : schema.getFields()) {
if (optionMap.containsKey(field.name())) {
optionBuilder.set(field, optionMap.get(field.name()));
}
}
option = optionBuilder.build();
}
return option;
}
@SuppressWarnings("unchecked")
private List<Object> parseOptions(Schema schema, Map propertiesProp) {
enforceMutualExclusion(
propertiesProp, OPTIONS_PROP,
LENGTH_PROP, REGEX_PROP, ITERATION_PROP, RANGE_PROP
);
Object optionsProp = propertiesProp.get(OPTIONS_PROP);
if (optionsProp instanceof Collection) {
Collection optionsList = (Collection) optionsProp;
if (optionsList.isEmpty()) {
throw new RuntimeException(String.format(
"%s property cannot be empty",
OPTIONS_PROP
));
}
List<Object> options = new ArrayList<>();
for (Object option : optionsList) {
option = wrapOption(schema, option);
if (!GenericData.get().validate(schema, option)) {
throw new RuntimeException(String.format(
"Invalid option for %s schema: type %s, value '%s'",
schema.getType().getName(),
option.getClass().getName(),
option
));
}
options.add(option);
}
return options;
} else if (optionsProp instanceof Map) {
Map optionsProps = (Map) optionsProp;
Object optionsFile = optionsProps.get(OPTIONS_PROP_FILE);
if (optionsFile == null) {
throw new RuntimeException(String.format(
"%s property must contain '%s' field when given as object",
OPTIONS_PROP,
OPTIONS_PROP_FILE
));
}
if (!(optionsFile instanceof String)) {
throw new RuntimeException(String.format(
"'%s' field of %s property must be given as string, was %s instead",
OPTIONS_PROP_FILE,
OPTIONS_PROP,
optionsFile.getClass().getName()
));
}
Object optionsEncoding = optionsProps.get(OPTIONS_PROP_ENCODING);
if (optionsEncoding == null) {
throw new RuntimeException(String.format(
"%s property must contain '%s' field when given as object",
OPTIONS_PROP,
OPTIONS_PROP_FILE
));
}
if (!(optionsEncoding instanceof String)) {
throw new RuntimeException(String.format(
"'%s' field of %s property must be given as string, was %s instead",
OPTIONS_PROP_ENCODING,
OPTIONS_PROP,
optionsEncoding.getClass().getName()
));
}
try (InputStream optionsStream = new FileInputStream((String) optionsFile)) {
DatumReader<Object> optionReader = new GenericDatumReader(schema);
Decoder decoder;
if ("binary".equals(optionsEncoding)) {
decoder = DecoderFactory.get().binaryDecoder(optionsStream, null);
} else if ("json".equals(optionsEncoding)) {
decoder = DecoderFactory.get().jsonDecoder(schema, optionsStream);
} else {
throw new RuntimeException(String.format(
"'%s' field of %s property only supports two formats: 'binary' and 'json'",
OPTIONS_PROP_ENCODING,
OPTIONS_PROP
));
}
List<Object> options = new ArrayList<>();
Object option = optionReader.read(null, decoder);
while (option != null) {
option = wrapOption(schema, option);
if (!GenericData.get().validate(schema, option)) {
throw new RuntimeException(String.format(
"Invalid option for %s schema: type %s, value '%s'",
schema.getType().getName(),
option.getClass().getName(),
option
));
}
options.add(option);
try {
option = optionReader.read(null, decoder);
} catch (EOFException eofe) {
break;
}
}
return options;
} catch (FileNotFoundException fnfe) {
throw new RuntimeException(
String.format(
"Unable to locate options file '%s'",
optionsFile
),
fnfe
);
} catch (IOException ioe) {
throw new RuntimeException(
String.format(
"Unable to read options file '%s'",
optionsFile
),
ioe
);
}
} else {
throw new RuntimeException(String.format(
"%s prop must be an array or an object, was %s instead",
OPTIONS_PROP,
optionsProp.getClass().getName()
));
}
}
@SuppressWarnings("unchecked")
private <T> T generateOption(Schema schema, Map propertiesProp) {
if (!optionsCache.containsKey(schema)) {
optionsCache.put(schema, parseOptions(schema, propertiesProp));
}
List<Object> options = optionsCache.get(schema);
return (T) options.get(random.nextInt(options.size()));
}
private Iterator<Object> getBooleanIterator(Map iterationProps) {
Object startProp = iterationProps.get(ITERATION_PROP_START);
if (startProp == null) {
throw new RuntimeException(String.format(
"%s property must contain %s field",
ITERATION_PROP,
ITERATION_PROP_START
));
}
if (!(startProp instanceof Boolean)) {
throw new RuntimeException(String.format(
"%s field of %s property for a boolean schema must be a boolean, was %s instead",
ITERATION_PROP_START,
ITERATION_PROP,
startProp.getClass().getName()
));
}
if (iterationProps.containsKey(ITERATION_PROP_RESTART)) {
throw new RuntimeException(String.format(
"%s property cannot contain %s field for a boolean schema",
ITERATION_PROP,
ITERATION_PROP_RESTART
));
}
if (iterationProps.containsKey(ITERATION_PROP_STEP)) {
throw new RuntimeException(String.format(
"%s property cannot contain %s field for a boolean schema",
ITERATION_PROP,
ITERATION_PROP_STEP
));
}
// If an odd number of records have been generated previously, then the boolean will have
// changed state effectively once, and so the start state should be inverted.
return new BooleanIterator((generation % 2 == 1) ^ ((Boolean) startProp));
}
private Iterator<Object> getIntegralIterator(
Long iterationStartField,
Long iterationRestartField,
Long iterationStepField,
Long iterationInitialField,
IntegralIterator.Type type) {
if (iterationStartField == null) {
throw new RuntimeException(String.format(
"%s property must contain %s field",
ITERATION_PROP,
ITERATION_PROP_START
));
}
long iterationStart = iterationStartField;
long iterationRestart;
long iterationStep;
long restartHighDefault;
long restartLowDefault;
switch (type) {
case INTEGER:
restartHighDefault = Integer.MAX_VALUE;
restartLowDefault = Integer.MIN_VALUE;
break;
case LONG:
restartHighDefault = Long.MAX_VALUE;
restartLowDefault = Long.MIN_VALUE;
break;
default:
throw new RuntimeException(String.format(
"Unexpected IntegralIterator type: %s",
type
));
}
if (iterationRestartField == null && iterationStepField == null) {
iterationRestart = restartHighDefault;
iterationStep = 1;
} else if (iterationRestartField == null) {
iterationStep = iterationStepField;
if (iterationStep > 0) {
iterationRestart = restartHighDefault;
} else if (iterationStep < 0) {
iterationRestart = -1 * restartLowDefault;
} else {
throw new RuntimeException(String.format(
"%s field of %s property cannot be zero",
ITERATION_PROP_STEP,
ITERATION_PROP
));
}
} else if (iterationStepField == null) {
iterationRestart = iterationRestartField;
if (iterationRestart > iterationStart) {
iterationStep = 1;
} else if (iterationRestart < iterationStart) {
iterationStep = -1;
} else {
throw new RuntimeException(String.format(
"%s and %s fields of %s property cannot be equal",
ITERATION_PROP_START,
ITERATION_PROP_RESTART,
ITERATION_PROP
));
}
} else {
iterationRestart = iterationRestartField;
iterationStep = iterationStepField;
if (iterationStep == 0) {
throw new RuntimeException(String.format(
"%s field of %s property cannot be zero",
ITERATION_PROP_STEP,
ITERATION_PROP
));
}
if (iterationStart == iterationRestart) {
throw new RuntimeException(String.format(
"%s and %s fields of %s property cannot be equal",
ITERATION_PROP_START,
ITERATION_PROP_RESTART,
ITERATION_PROP
));
}
if (iterationRestart > iterationStart && iterationStep < 0) {
throw new RuntimeException(String.format(
"%s field of %s property must be positive when %s field is greater than %s field",
ITERATION_PROP_STEP,
ITERATION_PROP,
ITERATION_PROP_RESTART,
ITERATION_PROP_START
));
}
if (iterationRestart < iterationStart && iterationStep > 0) {
throw new RuntimeException(String.format(
"%s field of %s property must be negative when %s field is less than %s field",
ITERATION_PROP_STEP,
ITERATION_PROP,
ITERATION_PROP_RESTART,
ITERATION_PROP_START
));
}
}
long iterationInitial = iterationStart;
if (iterationInitialField != null) {
iterationInitial = iterationInitialField;
}
return new IntegralIterator(
iterationStart,
iterationRestart,
iterationStep,
iterationInitial,
generation,
type
);
}
private Iterator<Object> getDecimalIterator(
Double iterationStartField,
Double iterationRestartField,
Double iterationStepField,
Double iterationInitialField,
DecimalIterator.Type type) {
if (iterationStartField == null) {
throw new RuntimeException(String.format(
"%s property must contain %s field",
ITERATION_PROP,
ITERATION_PROP_START
));
}
double iterationStart = iterationStartField;
double iterationRestart;
double iterationStep;
double restartHighDefault;
double restartLowDefault;
switch (type) {
case FLOAT:
restartHighDefault = Float.MAX_VALUE;
restartLowDefault = -1 * Float.MAX_VALUE;
break;
case DOUBLE:
restartHighDefault = Double.MAX_VALUE;
restartLowDefault = -1 * Double.MAX_VALUE;
break;
default:
throw new RuntimeException(String.format(
"Unexpected DecimalIterator type: %s",
type
));
}
if (iterationRestartField == null && iterationStepField == null) {
iterationRestart = restartHighDefault;
iterationStep = 1;
} else if (iterationRestartField == null) {
iterationStep = iterationStepField;
if (iterationStep > 0) {
iterationRestart = restartHighDefault;
} else if (iterationStep < 0) {
iterationRestart = -1 * restartLowDefault;
} else {
throw new RuntimeException(String.format(
"%s field of %s property cannot be zero",
ITERATION_PROP_STEP,
ITERATION_PROP
));
}
} else if (iterationStepField == null) {
iterationRestart = iterationRestartField;
if (iterationRestart > iterationStart) {
iterationStep = 1;
} else if (iterationRestart < iterationStart) {
iterationStep = -1;
} else {
throw new RuntimeException(String.format(
"%s and %s fields of %s property cannot be equal",
ITERATION_PROP_START,
ITERATION_PROP_RESTART,
ITERATION_PROP
));
}
} else {
iterationRestart = iterationRestartField;
iterationStep = iterationStepField;
if (iterationStep == 0) {
throw new RuntimeException(String.format(
"%s field of %s property cannot be zero",
ITERATION_PROP_STEP,
ITERATION_PROP
));
}
if (iterationStart == iterationRestart) {
throw new RuntimeException(String.format(
"%s and %s fields of %s property cannot be equal",
ITERATION_PROP_START,
ITERATION_PROP_RESTART,
ITERATION_PROP
));
}
if (iterationRestart > iterationStart && iterationStep < 0) {
throw new RuntimeException(String.format(
"%s field of %s property must be positive when %s field is greater than %s field",
ITERATION_PROP_STEP,
ITERATION_PROP,
ITERATION_PROP_RESTART,
ITERATION_PROP_START
));
}
if (iterationRestart < iterationStart && iterationStep > 0) {
throw new RuntimeException(String.format(
"%s field of %s property must be negative when %s field is less than %s field",
ITERATION_PROP_STEP,
ITERATION_PROP,
ITERATION_PROP_RESTART,
ITERATION_PROP_START
));
}
}
double iterationInitial = iterationStart;
if (iterationInitialField != null) {
iterationInitial = iterationInitialField;
}
return new DecimalIterator(
iterationStart,
iterationRestart,
iterationStep,
iterationInitial,
generation,
type
);
}
private Iterator<Object> parseIterations(Schema schema, Map propertiesProp) {
enforceMutualExclusion(
propertiesProp, ITERATION_PROP,
LENGTH_PROP, REGEX_PROP, OPTIONS_PROP, RANGE_PROP
);
Object iterationProp = propertiesProp.get(ITERATION_PROP);
if (!(iterationProp instanceof Map)) {
throw new RuntimeException(String.format(
"%s prop must be an object, was %s instead",
ITERATION_PROP,
iterationProp.getClass().getName()
));
}
Map iterationProps = (Map) iterationProp;
switch (schema.getType()) {
case BOOLEAN:
return getBooleanIterator(iterationProps);
case INT:
return getIntegerIterator(iterationProps);
case LONG:
return getLongIterator(iterationProps);
case FLOAT:
return getFloatIterator(iterationProps);
case DOUBLE:
return getDoubleIterator(iterationProps);
case STRING:
return createStringIterator(getIntegerIterator(iterationProps), propertiesProp);
default:
throw new UnsupportedOperationException(String.format(
"%s property can only be specified on numeric, boolean or string schemas, "
+ "not %s schema",
ITERATION_PROP,
schema.getType().toString()
));
}
}
private Iterator<Object> getDoubleIterator(final Map iterationProps) {
Double iterationStartField = getDecimalNumberField(
ITERATION_PROP,
ITERATION_PROP_START,
iterationProps
);
Double iterationRestartField = getDecimalNumberField(
ITERATION_PROP,
ITERATION_PROP_RESTART,
iterationProps
);
Double iterationStepField = getDecimalNumberField(
ITERATION_PROP,
ITERATION_PROP_STEP,
iterationProps
);
Double iterationInitialField = getDecimalNumberField(
ITERATION_PROP,
ITERATION_PROP_INITIAL,
iterationProps
);
return getDecimalIterator(
iterationStartField,
iterationRestartField,
iterationStepField,
iterationInitialField,
DecimalIterator.Type.DOUBLE
);
}
private Iterator<Object> getFloatIterator(final Map iterationProps) {
Float iterationStartField = getFloatNumberField(
ITERATION_PROP,
ITERATION_PROP_START,
iterationProps
);
Float iterationRestartField = getFloatNumberField(
ITERATION_PROP,
ITERATION_PROP_RESTART,
iterationProps
);
Float iterationStepField = getFloatNumberField(
ITERATION_PROP,
ITERATION_PROP_STEP,
iterationProps
);
Float iterationInitialField = getFloatNumberField(
ITERATION_PROP,
ITERATION_PROP_INITIAL,
iterationProps
);
return getDecimalIterator(
iterationStartField != null ? iterationStartField.doubleValue() : null,
iterationRestartField != null ? iterationRestartField.doubleValue() : null,
iterationStepField != null ? iterationStepField.doubleValue() : null,
iterationInitialField != null ? iterationInitialField.doubleValue() : null,
DecimalIterator.Type.FLOAT
);
}
private Iterator<Object> getLongIterator(final Map iterationProps) {
Long iterationStartField = getIntegralNumberField(
ITERATION_PROP,
ITERATION_PROP_START,
iterationProps
);
Long iterationRestartField = getIntegralNumberField(