/
GeneratedMessage.java
3426 lines (2985 loc) · 120 KB
/
GeneratedMessage.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
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
import static com.google.protobuf.Internal.checkNotNull;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FileDescriptor;
import com.google.protobuf.Descriptors.OneofDescriptor;
import com.google.protobuf.Internal.BooleanList;
import com.google.protobuf.Internal.DoubleList;
import com.google.protobuf.Internal.FloatList;
import com.google.protobuf.Internal.IntList;
import com.google.protobuf.Internal.LongList;
import com.google.protobuf.Internal.ProtobufList;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* All generated protocol message classes extend this class. This class implements most of the
* Message and Builder interfaces using Java reflection. Users can ignore this class and pretend
* that generated messages implement the Message interface directly.
*
* @author kenton@google.com Kenton Varda
*/
public abstract class GeneratedMessage extends AbstractMessage implements Serializable {
private static final long serialVersionUID = 1L;
/**
* For testing. Allows a test to disable the optimization that avoids using field builders for
* nested messages until they are requested. By disabling this optimization, existing tests can be
* reused to test the field builders.
*/
protected static boolean alwaysUseFieldBuilders = false;
/**
* For use by generated code only.
*
* <p>TODO: mark this private and final (breaking change)
*/
protected UnknownFieldSet unknownFields;
protected GeneratedMessage() {
unknownFields = UnknownFieldSet.getDefaultInstance();
}
protected GeneratedMessage(Builder<?> builder) {
unknownFields = builder.getUnknownFields();
}
/** TODO: Remove this unnecessary intermediate implementation of this method. */
@Override
public Parser<? extends GeneratedMessage> getParserForType() {
throw new UnsupportedOperationException("This is supposed to be overridden by subclasses.");
}
/**
* TODO: Stop using SingleFieldBuilder and remove this setting
*
* @see #setAlwaysUseFieldBuildersForTesting(boolean)
*/
static void enableAlwaysUseFieldBuildersForTesting() {
setAlwaysUseFieldBuildersForTesting(true);
}
/**
* For testing. Allows a test to disable/re-enable the optimization that avoids using field
* builders for nested messages until they are requested. By disabling this optimization, existing
* tests can be reused to test the field builders. See {@link RepeatedFieldBuilder} and {@link
* SingleFieldBuilder}.
*
* <p>TODO: Stop using SingleFieldBuilder and remove this setting
*/
static void setAlwaysUseFieldBuildersForTesting(boolean useBuilders) {
alwaysUseFieldBuilders = useBuilders;
}
/**
* Get the FieldAccessorTable for this type. We can't have the message class pass this in to the
* constructor because of bootstrapping trouble with DescriptorProtos.
*/
protected abstract FieldAccessorTable internalGetFieldAccessorTable();
@Override
public Descriptor getDescriptorForType() {
return internalGetFieldAccessorTable().descriptor;
}
/**
* TODO: This method should be removed. It enables parsing directly into an
* "immutable" message. Have to leave it for now to support old gencode.
*
* @deprecated use newBuilder().mergeFrom() instead
*/
@Deprecated
protected void mergeFromAndMakeImmutableInternal(
CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException {
Schema<GeneratedMessage> schema = Protobuf.getInstance().schemaFor(this);
try {
schema.mergeFrom(this, CodedInputStreamReader.forCodedInput(input), extensionRegistry);
} catch (InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (IOException e) {
throw new InvalidProtocolBufferException(e).setUnfinishedMessage(this);
}
schema.makeImmutable(this);
}
/**
* Internal helper to return a modifiable map containing all the fields. The returned Map is
* modifiable so that the caller can add additional extension fields to implement {@link
* #getAllFields()}.
*
* @param getBytesForString whether to generate ByteString for string fields
*/
private Map<FieldDescriptor, Object> getAllFieldsMutable(boolean getBytesForString) {
final TreeMap<FieldDescriptor, Object> result = new TreeMap<>();
final Descriptor descriptor = internalGetFieldAccessorTable().descriptor;
final List<FieldDescriptor> fields = descriptor.getFields();
for (int i = 0; i < fields.size(); i++) {
FieldDescriptor field = fields.get(i);
final OneofDescriptor oneofDescriptor = field.getContainingOneof();
/*
* If the field is part of a Oneof, then at maximum one field in the Oneof is set
* and it is not repeated. There is no need to iterate through the others.
*/
if (oneofDescriptor != null) {
// Skip other fields in the Oneof we know are not set
i += oneofDescriptor.getFieldCount() - 1;
if (!hasOneof(oneofDescriptor)) {
// If no field is set in the Oneof, skip all the fields in the Oneof
continue;
}
// Get the pointer to the only field which is set in the Oneof
field = getOneofFieldDescriptor(oneofDescriptor);
} else {
// If we are not in a Oneof, we need to check if the field is set and if it is repeated
if (field.isRepeated()) {
final List<?> value = (List<?>) getField(field);
if (!value.isEmpty()) {
result.put(field, value);
}
continue;
}
if (!hasField(field)) {
continue;
}
}
// Add the field to the map
if (getBytesForString && field.getJavaType() == FieldDescriptor.JavaType.STRING) {
result.put(field, getFieldRaw(field));
} else {
result.put(field, getField(field));
}
}
return result;
}
// TODO: compute this at {@code build()} time in the Builder class.
@Override
public boolean isInitialized() {
for (final FieldDescriptor field : getDescriptorForType().getFields()) {
// Check that all required fields are present.
if (field.isRequired()) {
if (!hasField(field)) {
return false;
}
}
// Check that embedded messages are initialized.
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
if (field.isRepeated()) {
@SuppressWarnings("unchecked")
final List<Message> messageList = (List<Message>) getField(field);
for (final Message element : messageList) {
if (!element.isInitialized()) {
return false;
}
}
} else {
if (hasField(field) && !((Message) getField(field)).isInitialized()) {
return false;
}
}
}
}
return true;
}
@Override
public Map<FieldDescriptor, Object> getAllFields() {
return Collections.unmodifiableMap(getAllFieldsMutable(/* getBytesForString= */ false));
}
/**
* Returns a collection of all the fields in this message which are set and their corresponding
* values. A singular ("required" or "optional") field is set iff hasField() returns true for that
* field. A "repeated" field is set iff getRepeatedFieldCount() is greater than zero. The values
* are exactly what would be returned by calling {@link #getFieldRaw(Descriptors.FieldDescriptor)}
* for each field. The map is guaranteed to be a sorted map, so iterating over it will return
* fields in order by field number.
*/
Map<FieldDescriptor, Object> getAllFieldsRaw() {
return Collections.unmodifiableMap(getAllFieldsMutable(/* getBytesForString= */ true));
}
@Override
public boolean hasOneof(final OneofDescriptor oneof) {
return internalGetFieldAccessorTable().getOneof(oneof).has(this);
}
@Override
public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) {
return internalGetFieldAccessorTable().getOneof(oneof).get(this);
}
@Override
public boolean hasField(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).has(this);
}
@Override
public Object getField(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).get(this);
}
/**
* Obtains the value of the given field, or the default value if it is not set. For primitive
* fields, the boxed primitive value is returned. For enum fields, the EnumValueDescriptor for the
* value is returned. For embedded message fields, the sub-message is returned. For repeated
* fields, a java.util.List is returned. For present string fields, a ByteString is returned
* representing the bytes that the field contains.
*/
Object getFieldRaw(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).getRaw(this);
}
@Override
public int getRepeatedFieldCount(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).getRepeatedCount(this);
}
@Override
public Object getRepeatedField(final FieldDescriptor field, final int index) {
return internalGetFieldAccessorTable().getField(field).getRepeated(this, index);
}
// TODO: This method should be final.
@Override
public UnknownFieldSet getUnknownFields() {
return unknownFields;
}
// TODO: This should go away when Schema classes cannot modify immutable
// GeneratedMessage objects anymore.
void setUnknownFields(UnknownFieldSet unknownFields) {
this.unknownFields = unknownFields;
}
/**
* Called by subclasses to parse an unknown field.
*
* <p>TODO remove this method
*
* @return {@code true} unless the tag is an end-group tag.
*/
protected boolean parseUnknownField(
CodedInputStream input,
UnknownFieldSet.Builder unknownFields,
ExtensionRegistryLite extensionRegistry,
int tag)
throws IOException {
if (input.shouldDiscardUnknownFields()) {
return input.skipField(tag);
}
return unknownFields.mergeFieldFrom(tag, input);
}
/**
* Delegates to parseUnknownField. This method is obsolete, but we must retain it for
* compatibility with older generated code.
*
* <p>TODO remove this method
*/
protected boolean parseUnknownFieldProto3(
CodedInputStream input,
UnknownFieldSet.Builder unknownFields,
ExtensionRegistryLite extensionRegistry,
int tag)
throws IOException {
return parseUnknownField(input, unknownFields, extensionRegistry, tag);
}
/** Used by generated code. */
@SuppressWarnings("ProtoParseWithRegistry")
protected static <M extends Message> M parseWithIOException(Parser<M> parser, InputStream input)
throws IOException {
try {
return parser.parseFrom(input);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
/** Used by generated code. */
protected static <M extends Message> M parseWithIOException(
Parser<M> parser, InputStream input, ExtensionRegistryLite extensions) throws IOException {
try {
return parser.parseFrom(input, extensions);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
/** Used by generated code. */
@SuppressWarnings("ProtoParseWithRegistry")
protected static <M extends Message> M parseWithIOException(
Parser<M> parser, CodedInputStream input) throws IOException {
try {
return parser.parseFrom(input);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
/** Used by generated code. */
protected static <M extends Message> M parseWithIOException(
Parser<M> parser, CodedInputStream input, ExtensionRegistryLite extensions)
throws IOException {
try {
return parser.parseFrom(input, extensions);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
/** Used by generated code. */
@SuppressWarnings("ProtoParseWithRegistry")
protected static <M extends Message> M parseDelimitedWithIOException(
Parser<M> parser, InputStream input) throws IOException {
try {
return parser.parseDelimitedFrom(input);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
/** Used by generated code. */
protected static <M extends Message> M parseDelimitedWithIOException(
Parser<M> parser, InputStream input, ExtensionRegistryLite extensions) throws IOException {
try {
return parser.parseDelimitedFrom(input, extensions);
} catch (InvalidProtocolBufferException e) {
throw e.unwrapIOException();
}
}
protected static boolean canUseUnsafe() {
return UnsafeUtil.hasUnsafeArrayOperations() && UnsafeUtil.hasUnsafeByteBufferOperations();
}
protected static IntList emptyIntList() {
return IntArrayList.emptyList();
}
// TODO: Unused. Remove.
protected static IntList newIntList() {
return new IntArrayList();
}
// TODO: Redundant with makeMutableCopy(). Remove.
protected static IntList mutableCopy(IntList list) {
return makeMutableCopy(list);
}
// TODO: Redundant with makeMutableCopy(). Remove.
protected static LongList mutableCopy(LongList list) {
return makeMutableCopy(list);
}
// TODO: Redundant with makeMutableCopy(). Remove.
protected static FloatList mutableCopy(FloatList list) {
return makeMutableCopy(list);
}
// TODO: Redundant with makeMutableCopy(). Remove.
protected static DoubleList mutableCopy(DoubleList list) {
return makeMutableCopy(list);
}
// TODO: Redundant with makeMutableCopy(). Remove.
protected static BooleanList mutableCopy(BooleanList list) {
return makeMutableCopy(list);
}
protected static LongList emptyLongList() {
return LongArrayList.emptyList();
}
// TODO: Unused. Remove.
protected static LongList newLongList() {
return new LongArrayList();
}
protected static FloatList emptyFloatList() {
return FloatArrayList.emptyList();
}
// TODO: Unused. Remove.
protected static FloatList newFloatList() {
return new FloatArrayList();
}
protected static DoubleList emptyDoubleList() {
return DoubleArrayList.emptyList();
}
// TODO: Unused. Remove.
protected static DoubleList newDoubleList() {
return new DoubleArrayList();
}
protected static BooleanList emptyBooleanList() {
return BooleanArrayList.emptyList();
}
// TODO: Unused. Remove.
protected static BooleanList newBooleanList() {
return new BooleanArrayList();
}
protected static <ListT extends ProtobufList<?>> ListT makeMutableCopy(ListT list) {
return makeMutableCopy(list, 0);
}
@SuppressWarnings("unchecked") // Guaranteed by proto runtime.
protected static <ListT extends ProtobufList<?>> ListT makeMutableCopy(
ListT list, int minCapacity) {
int size = list.size();
if (minCapacity <= size) {
minCapacity = size * 2;
}
if (minCapacity <= 0) {
minCapacity = AbstractProtobufList.DEFAULT_CAPACITY;
}
return (ListT) list.mutableCopyWithCapacity(minCapacity);
}
@SuppressWarnings("unchecked") // The empty list can be safely cast
protected static <T> ProtobufList<T> emptyList(Class<T> elementType) {
return (ProtobufList<T>) ProtobufArrayList.emptyList();
}
@Override
public void writeTo(final CodedOutputStream output) throws IOException {
MessageReflection.writeMessageTo(this, getAllFieldsRaw(), output, false);
}
@Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) {
return size;
}
memoizedSize = MessageReflection.getSerializedSize(
this, getAllFieldsRaw());
return memoizedSize;
}
/**
* This class is used to make a generated protected method inaccessible from user's code (e.g.,
* the {@link #newInstance} method below). When this class is used as a parameter's type in a
* generated protected method, the method is visible to user's code in the same package, but since
* the constructor of this class is private to protobuf runtime, user's code can't obtain an
* instance of this class and as such can't actually make a method call on the protected method.
*/
protected static final class UnusedPrivateParameter {
static final UnusedPrivateParameter INSTANCE = new UnusedPrivateParameter();
private UnusedPrivateParameter() {}
}
/** Creates a new instance of this message type. Overridden in the generated code. */
@SuppressWarnings({"unused"})
protected Object newInstance(UnusedPrivateParameter unused) {
throw new UnsupportedOperationException("This method must be overridden by the subclass.");
}
/**
* Used by parsing constructors in generated classes.
*
* <p>TODO: remove unused method (extensions should be immutable after build)
*/
protected void makeExtensionsImmutable() {
// Noop for messages without extensions.
}
/**
* TODO: remove this after b/29368482 is fixed. We need to move this interface to
* AbstractMessage in order to versioning GeneratedMessage but this move breaks binary
* compatibility for AppEngine. After AppEngine is fixed we can exclude this from google3.
*
* <p>TODO: Remove at breaking change since b/29368482 was fixed in 2020
*/
protected interface BuilderParent extends AbstractMessage.BuilderParent {}
/** TODO: remove this together with GeneratedMessage.BuilderParent. */
protected abstract Message.Builder newBuilderForType(BuilderParent parent);
/** TODO: generated class should implement this directly */
@Override
protected Message.Builder newBuilderForType(final AbstractMessage.BuilderParent parent) {
return newBuilderForType(
new BuilderParent() {
@Override
public void markDirty() {
parent.markDirty();
}
});
}
/** Builder class for {@link GeneratedMessage}. */
@SuppressWarnings("unchecked")
public abstract static class Builder<BuilderT extends Builder<BuilderT>>
extends AbstractMessage.Builder<BuilderT> {
private BuilderParent builderParent;
private BuilderParentImpl meAsParent;
// Indicates that we've built a message and so we are now obligated
// to dispatch dirty invalidations. See GeneratedMessage.BuilderListener.
private boolean isClean;
/**
* This field holds either an {@link UnknownFieldSet} or {@link UnknownFieldSet.Builder}.
*
* <p>We use an object because it should only be one or the other of those things at a time and
* Object is the only common base. This also saves space.
*
* <p>Conversions are lazy: if {@link #setUnknownFields} is called, this will contain {@link
* UnknownFieldSet}. If unknown fields are merged into this builder, the current {@link
* UnknownFieldSet} will be converted to a {@link UnknownFieldSet.Builder} and left that way
* until either {@link #setUnknownFields} or {@link #buildPartial} or {@link #build} is called.
*/
private Object unknownFieldsOrBuilder = UnknownFieldSet.getDefaultInstance();
protected Builder() {
this(null);
}
protected Builder(BuilderParent builderParent) {
this.builderParent = builderParent;
}
@Override
void dispose() {
builderParent = null;
}
/** Called by the subclass when a message is built. */
protected void onBuilt() {
if (builderParent != null) {
markClean();
}
}
/**
* Called by the subclass or a builder to notify us that a message was built and may be cached
* and therefore invalidations are needed.
*/
@Override
protected void markClean() {
this.isClean = true;
}
/**
* Gets whether invalidations are needed
*
* @return whether invalidations are needed
*/
protected boolean isClean() {
return isClean;
}
@Override
public BuilderT clone() {
BuilderT builder = (BuilderT) getDefaultInstanceForType().newBuilderForType();
builder.mergeFrom(buildPartial());
return builder;
}
/**
* Called by the initialization and clear code paths to allow subclasses to reset any of their
* builtin fields back to the initial values.
*/
@Override
public BuilderT clear() {
unknownFieldsOrBuilder = UnknownFieldSet.getDefaultInstance();
onChanged();
return (BuilderT) this;
}
/**
* Get the FieldAccessorTable for this type. We can't have the message class pass this in to the
* constructor because of bootstrapping trouble with DescriptorProtos.
*/
protected abstract FieldAccessorTable internalGetFieldAccessorTable();
@Override
public Descriptor getDescriptorForType() {
return internalGetFieldAccessorTable().descriptor;
}
@Override
public Map<FieldDescriptor, Object> getAllFields() {
return Collections.unmodifiableMap(getAllFieldsMutable());
}
/** Internal helper which returns a mutable map. */
private Map<FieldDescriptor, Object> getAllFieldsMutable() {
final TreeMap<FieldDescriptor, Object> result = new TreeMap<>();
final Descriptor descriptor = internalGetFieldAccessorTable().descriptor;
final List<FieldDescriptor> fields = descriptor.getFields();
for (int i = 0; i < fields.size(); i++) {
FieldDescriptor field = fields.get(i);
final OneofDescriptor oneofDescriptor = field.getContainingOneof();
/*
* If the field is part of a Oneof, then at maximum one field in the Oneof is set
* and it is not repeated. There is no need to iterate through the others.
*/
if (oneofDescriptor != null) {
// Skip other fields in the Oneof we know are not set
i += oneofDescriptor.getFieldCount() - 1;
if (!hasOneof(oneofDescriptor)) {
// If no field is set in the Oneof, skip all the fields in the Oneof
continue;
}
// Get the pointer to the only field which is set in the Oneof
field = getOneofFieldDescriptor(oneofDescriptor);
} else {
// If we are not in a Oneof, we need to check if the field is set and if it is repeated
if (field.isRepeated()) {
final List<?> value = (List<?>) getField(field);
if (!value.isEmpty()) {
result.put(field, value);
}
continue;
}
if (!hasField(field)) {
continue;
}
}
// Add the field to the map
result.put(field, getField(field));
}
return result;
}
@Override
public Message.Builder newBuilderForField(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).newBuilder();
}
@Override
public Message.Builder getFieldBuilder(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).getBuilder(this);
}
@Override
public Message.Builder getRepeatedFieldBuilder(final FieldDescriptor field, int index) {
return internalGetFieldAccessorTable().getField(field).getRepeatedBuilder(this, index);
}
@Override
public boolean hasOneof(final OneofDescriptor oneof) {
return internalGetFieldAccessorTable().getOneof(oneof).has(this);
}
@Override
public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) {
return internalGetFieldAccessorTable().getOneof(oneof).get(this);
}
@Override
public boolean hasField(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).has(this);
}
@Override
public Object getField(final FieldDescriptor field) {
Object object = internalGetFieldAccessorTable().getField(field).get(this);
if (field.isRepeated()) {
// The underlying list object is still modifiable at this point.
// Make sure not to expose the modifiable list to the caller.
return Collections.unmodifiableList((List<?>) object);
} else {
return object;
}
}
@Override
public BuilderT setField(final FieldDescriptor field, final Object value) {
internalGetFieldAccessorTable().getField(field).set(this, value);
return (BuilderT) this;
}
@Override
public BuilderT clearField(final FieldDescriptor field) {
internalGetFieldAccessorTable().getField(field).clear(this);
return (BuilderT) this;
}
@Override
public BuilderT clearOneof(final OneofDescriptor oneof) {
internalGetFieldAccessorTable().getOneof(oneof).clear(this);
return (BuilderT) this;
}
@Override
public int getRepeatedFieldCount(final FieldDescriptor field) {
return internalGetFieldAccessorTable().getField(field).getRepeatedCount(this);
}
@Override
public Object getRepeatedField(final FieldDescriptor field, final int index) {
return internalGetFieldAccessorTable().getField(field).getRepeated(this, index);
}
@Override
public BuilderT setRepeatedField(
final FieldDescriptor field, final int index, final Object value) {
internalGetFieldAccessorTable().getField(field).setRepeated(this, index, value);
return (BuilderT) this;
}
@Override
public BuilderT addRepeatedField(final FieldDescriptor field, final Object value) {
internalGetFieldAccessorTable().getField(field).addRepeated(this, value);
return (BuilderT) this;
}
private BuilderT setUnknownFieldsInternal(final UnknownFieldSet unknownFields) {
unknownFieldsOrBuilder = unknownFields;
onChanged();
return (BuilderT) this;
}
@Override
public BuilderT setUnknownFields(final UnknownFieldSet unknownFields) {
return setUnknownFieldsInternal(unknownFields);
}
/**
* This method is obsolete, but we must retain it for compatibility with older generated code.
*/
protected BuilderT setUnknownFieldsProto3(final UnknownFieldSet unknownFields) {
return setUnknownFieldsInternal(unknownFields);
}
@Override
public BuilderT mergeUnknownFields(final UnknownFieldSet unknownFields) {
if (UnknownFieldSet.getDefaultInstance().equals(unknownFields)) {
return (BuilderT) this;
}
if (UnknownFieldSet.getDefaultInstance().equals(unknownFieldsOrBuilder)) {
unknownFieldsOrBuilder = unknownFields;
onChanged();
return (BuilderT) this;
}
getUnknownFieldSetBuilder().mergeFrom(unknownFields);
onChanged();
return (BuilderT) this;
}
@Override
public boolean isInitialized() {
for (final FieldDescriptor field : getDescriptorForType().getFields()) {
// Check that all required fields are present.
if (field.isRequired()) {
if (!hasField(field)) {
return false;
}
}
// Check that embedded messages are initialized.
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
if (field.isRepeated()) {
@SuppressWarnings("unchecked")
final List<Message> messageList = (List<Message>) getField(field);
for (final Message element : messageList) {
if (!element.isInitialized()) {
return false;
}
}
} else {
if (hasField(field) && !((Message) getField(field)).isInitialized()) {
return false;
}
}
}
}
return true;
}
@Override
public final UnknownFieldSet getUnknownFields() {
if (unknownFieldsOrBuilder instanceof UnknownFieldSet) {
return (UnknownFieldSet) unknownFieldsOrBuilder;
} else {
return ((UnknownFieldSet.Builder) unknownFieldsOrBuilder).buildPartial();
}
}
/**
* Called by generated subclasses to parse an unknown field.
*
* @return {@code true} unless the tag is an end-group tag.
*/
protected boolean parseUnknownField(
CodedInputStream input, ExtensionRegistryLite extensionRegistry, int tag)
throws IOException {
if (input.shouldDiscardUnknownFields()) {
return input.skipField(tag);
}
return getUnknownFieldSetBuilder().mergeFieldFrom(tag, input);
}
/** Called by generated subclasses to add to the unknown field set. */
protected final void mergeUnknownLengthDelimitedField(int number, ByteString bytes) {
getUnknownFieldSetBuilder().mergeLengthDelimitedField(number, bytes);
}
/** Called by generated subclasses to add to the unknown field set. */
protected final void mergeUnknownVarintField(int number, int value) {
getUnknownFieldSetBuilder().mergeVarintField(number, value);
}
@Override
protected UnknownFieldSet.Builder getUnknownFieldSetBuilder() {
if (unknownFieldsOrBuilder instanceof UnknownFieldSet) {
unknownFieldsOrBuilder = ((UnknownFieldSet) unknownFieldsOrBuilder).toBuilder();
}
onChanged();
return (UnknownFieldSet.Builder) unknownFieldsOrBuilder;
}
@Override
protected void setUnknownFieldSetBuilder(UnknownFieldSet.Builder builder) {
unknownFieldsOrBuilder = builder;
onChanged();
}
/**
* Implementation of {@link BuilderParent} for giving to our children. This small inner class
* makes it so we don't publicly expose the BuilderParent methods.
*/
private class BuilderParentImpl implements BuilderParent {
@Override
public void markDirty() {
onChanged();
}
}
/**
* Gets the {@link BuilderParent} for giving to our children.
*
* @return The builder parent for our children.
*/
protected BuilderParent getParentForChildren() {
if (meAsParent == null) {
meAsParent = new BuilderParentImpl();
}
return meAsParent;
}
/**
* Called when a builder or one of its nested children has changed and any parent should be
* notified of its invalidation.
*/
protected final void onChanged() {
if (isClean && builderParent != null) {
builderParent.markDirty();
// Don't keep dispatching invalidations until build is called again.
isClean = false;
}
}
/**
* Gets the map field with the given field number. This method should be overridden in the
* generated message class if the message contains map fields.
*
* <p>Unlike other field types, reflection support for map fields can't be implemented based on
* generated public API because we need to access a map field as a list in reflection API but
* the generated API only allows us to access it as a map. This method returns the underlying
* map field directly and thus enables us to access the map field as a list.
*/
@SuppressWarnings({"unused", "rawtypes"})
protected MapFieldReflectionAccessor internalGetMapFieldReflection(int fieldNumber) {
return internalGetMapField(fieldNumber);
}
/** TODO: Remove, exists for compatibility with generated code. */
@Deprecated
@SuppressWarnings({"unused", "rawtypes"})
protected MapField internalGetMapField(int fieldNumber) {
// Note that we can't use descriptor names here because this method will
// be called when descriptor is being initialized.
throw new IllegalArgumentException("No map fields found in " + getClass().getName());
}
/** Like {@link #internalGetMapFieldReflection} but return a mutable version. */
@SuppressWarnings({"unused", "rawtypes"})
protected MapFieldReflectionAccessor internalGetMutableMapFieldReflection(int fieldNumber) {
return internalGetMutableMapField(fieldNumber);
}
/** TODO: Remove, exists for compatibility with generated code. */
@Deprecated
@SuppressWarnings({"unused", "rawtypes"})
protected MapField internalGetMutableMapField(int fieldNumber) {
// Note that we can't use descriptor names here because this method will
// be called when descriptor is being initialized.
throw new IllegalArgumentException("No map fields found in " + getClass().getName());
}
}
// =================================================================
// Extensions-related stuff
/** Extends {@link MessageOrBuilder} with extension-related functions. */
public interface ExtendableMessageOrBuilder<MessageT extends ExtendableMessage<MessageT>>
extends MessageOrBuilder {
// Re-define for return type covariance.
@Override
Message getDefaultInstanceForType();
/** Check if a singular extension is present. */
<T> boolean hasExtension(ExtensionLite<MessageT, T> extension);
/** Get the number of elements in a repeated extension. */
<T> int getExtensionCount(ExtensionLite<MessageT, List<T>> extension);
/** Get the value of an extension. */
<T> T getExtension(ExtensionLite<MessageT, T> extension);
/** Get one element of a repeated extension. */
<T> T getExtension(ExtensionLite<MessageT, List<T>> extension, int index);
}
/**
* Generated message classes for message types that contain extension ranges subclass this.
*
* <p>This class implements type-safe accessors for extensions. They implement all the same
* operations that you can do with normal fields -- e.g. "has", "get", and "getCount" -- but for
* extensions. The extensions are identified using instances of the class {@link
* GeneratedExtension}; the protocol compiler generates a static instance of this class for every
* extension in its input. Through the magic of generics, all is made type-safe.
*
* <p>For example, imagine you have the {@code .proto} file:
*
* <pre>
* option java_class = "MyProto";
*
* message Foo {
* extensions 1000 to max;
* }
*
* extend Foo {
* optional int32 bar;
* }