PageRenderTime 46ms CodeModel.GetById 6ms RepoModel.GetById 0ms app.codeStats 0ms

/thirdparty/breakpad/third_party/protobuf/protobuf/java/src/main/java/com/google/protobuf/GeneratedMessage.java

http://github.com/tomahawk-player/tomahawk
Java | 1766 lines | 1198 code | 174 blank | 394 comment | 160 complexity | c0b797ab957d474c0a7c0e238f59c996 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, GPL-3.0, GPL-2.0
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // http://code.google.com/p/protobuf/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. package com.google.protobuf;
  31. import com.google.protobuf.Descriptors.Descriptor;
  32. import com.google.protobuf.Descriptors.EnumValueDescriptor;
  33. import com.google.protobuf.Descriptors.FieldDescriptor;
  34. import java.io.IOException;
  35. import java.io.ObjectStreamException;
  36. import java.io.Serializable;
  37. import java.lang.reflect.InvocationTargetException;
  38. import java.lang.reflect.Method;
  39. import java.util.ArrayList;
  40. import java.util.Collections;
  41. import java.util.Iterator;
  42. import java.util.List;
  43. import java.util.Map;
  44. import java.util.TreeMap;
  45. /**
  46. * All generated protocol message classes extend this class. This class
  47. * implements most of the Message and Builder interfaces using Java reflection.
  48. * Users can ignore this class and pretend that generated messages implement
  49. * the Message interface directly.
  50. *
  51. * @author kenton@google.com Kenton Varda
  52. */
  53. public abstract class GeneratedMessage extends AbstractMessage
  54. implements Serializable {
  55. private static final long serialVersionUID = 1L;
  56. private final UnknownFieldSet unknownFields;
  57. /**
  58. * For testing. Allows a test to disable the optimization that avoids using
  59. * field builders for nested messages until they are requested. By disabling
  60. * this optimization, existing tests can be reused to test the field builders.
  61. */
  62. protected static boolean alwaysUseFieldBuilders = false;
  63. protected GeneratedMessage() {
  64. this.unknownFields = UnknownFieldSet.getDefaultInstance();
  65. }
  66. protected GeneratedMessage(Builder<?> builder) {
  67. this.unknownFields = builder.getUnknownFields();
  68. }
  69. /**
  70. * For testing. Allows a test to disable the optimization that avoids using
  71. * field builders for nested messages until they are requested. By disabling
  72. * this optimization, existing tests can be reused to test the field builders.
  73. * See {@link RepeatedFieldBuilder} and {@link SingleFieldBuilder}.
  74. */
  75. static void enableAlwaysUseFieldBuildersForTesting() {
  76. alwaysUseFieldBuilders = true;
  77. }
  78. /**
  79. * Get the FieldAccessorTable for this type. We can't have the message
  80. * class pass this in to the constructor because of bootstrapping trouble
  81. * with DescriptorProtos.
  82. */
  83. protected abstract FieldAccessorTable internalGetFieldAccessorTable();
  84. //@Override (Java 1.6 override semantics, but we must support 1.5)
  85. public Descriptor getDescriptorForType() {
  86. return internalGetFieldAccessorTable().descriptor;
  87. }
  88. /** Internal helper which returns a mutable map. */
  89. private Map<FieldDescriptor, Object> getAllFieldsMutable() {
  90. final TreeMap<FieldDescriptor, Object> result =
  91. new TreeMap<FieldDescriptor, Object>();
  92. final Descriptor descriptor = internalGetFieldAccessorTable().descriptor;
  93. for (final FieldDescriptor field : descriptor.getFields()) {
  94. if (field.isRepeated()) {
  95. final List<?> value = (List<?>) getField(field);
  96. if (!value.isEmpty()) {
  97. result.put(field, value);
  98. }
  99. } else {
  100. if (hasField(field)) {
  101. result.put(field, getField(field));
  102. }
  103. }
  104. }
  105. return result;
  106. }
  107. @Override
  108. public boolean isInitialized() {
  109. for (final FieldDescriptor field : getDescriptorForType().getFields()) {
  110. // Check that all required fields are present.
  111. if (field.isRequired()) {
  112. if (!hasField(field)) {
  113. return false;
  114. }
  115. }
  116. // Check that embedded messages are initialized.
  117. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
  118. if (field.isRepeated()) {
  119. @SuppressWarnings("unchecked") final
  120. List<Message> messageList = (List<Message>) getField(field);
  121. for (final Message element : messageList) {
  122. if (!element.isInitialized()) {
  123. return false;
  124. }
  125. }
  126. } else {
  127. if (hasField(field) && !((Message) getField(field)).isInitialized()) {
  128. return false;
  129. }
  130. }
  131. }
  132. }
  133. return true;
  134. }
  135. //@Override (Java 1.6 override semantics, but we must support 1.5)
  136. public Map<FieldDescriptor, Object> getAllFields() {
  137. return Collections.unmodifiableMap(getAllFieldsMutable());
  138. }
  139. //@Override (Java 1.6 override semantics, but we must support 1.5)
  140. public boolean hasField(final FieldDescriptor field) {
  141. return internalGetFieldAccessorTable().getField(field).has(this);
  142. }
  143. //@Override (Java 1.6 override semantics, but we must support 1.5)
  144. public Object getField(final FieldDescriptor field) {
  145. return internalGetFieldAccessorTable().getField(field).get(this);
  146. }
  147. //@Override (Java 1.6 override semantics, but we must support 1.5)
  148. public int getRepeatedFieldCount(final FieldDescriptor field) {
  149. return internalGetFieldAccessorTable().getField(field)
  150. .getRepeatedCount(this);
  151. }
  152. //@Override (Java 1.6 override semantics, but we must support 1.5)
  153. public Object getRepeatedField(final FieldDescriptor field, final int index) {
  154. return internalGetFieldAccessorTable().getField(field)
  155. .getRepeated(this, index);
  156. }
  157. //@Override (Java 1.6 override semantics, but we must support 1.5)
  158. public final UnknownFieldSet getUnknownFields() {
  159. return unknownFields;
  160. }
  161. protected abstract Message.Builder newBuilderForType(BuilderParent parent);
  162. /**
  163. * Interface for the parent of a Builder that allows the builder to
  164. * communicate invalidations back to the parent for use when using nested
  165. * builders.
  166. */
  167. protected interface BuilderParent {
  168. /**
  169. * A builder becomes dirty whenever a field is modified -- including fields
  170. * in nested builders -- and becomes clean when build() is called. Thus,
  171. * when a builder becomes dirty, all its parents become dirty as well, and
  172. * when it becomes clean, all its children become clean. The dirtiness
  173. * state is used to invalidate certain cached values.
  174. * <br>
  175. * To this end, a builder calls markAsDirty() on its parent whenever it
  176. * transitions from clean to dirty. The parent must propagate this call to
  177. * its own parent, unless it was already dirty, in which case the
  178. * grandparent must necessarily already be dirty as well. The parent can
  179. * only transition back to "clean" after calling build() on all children.
  180. */
  181. void markDirty();
  182. }
  183. @SuppressWarnings("unchecked")
  184. public abstract static class Builder <BuilderType extends Builder>
  185. extends AbstractMessage.Builder<BuilderType> {
  186. private BuilderParent builderParent;
  187. private BuilderParentImpl meAsParent;
  188. // Indicates that we've built a message and so we are now obligated
  189. // to dispatch dirty invalidations. See GeneratedMessage.BuilderListener.
  190. private boolean isClean;
  191. private UnknownFieldSet unknownFields =
  192. UnknownFieldSet.getDefaultInstance();
  193. protected Builder() {
  194. this(null);
  195. }
  196. protected Builder(BuilderParent builderParent) {
  197. this.builderParent = builderParent;
  198. }
  199. void dispose() {
  200. builderParent = null;
  201. }
  202. /**
  203. * Called by the subclass when a message is built.
  204. */
  205. protected void onBuilt() {
  206. if (builderParent != null) {
  207. markClean();
  208. }
  209. }
  210. /**
  211. * Called by the subclass or a builder to notify us that a message was
  212. * built and may be cached and therefore invalidations are needed.
  213. */
  214. protected void markClean() {
  215. this.isClean = true;
  216. }
  217. /**
  218. * Gets whether invalidations are needed
  219. *
  220. * @return whether invalidations are needed
  221. */
  222. protected boolean isClean() {
  223. return isClean;
  224. }
  225. // This is implemented here only to work around an apparent bug in the
  226. // Java compiler and/or build system. See bug #1898463. The mere presence
  227. // of this dummy clone() implementation makes it go away.
  228. @Override
  229. public BuilderType clone() {
  230. throw new UnsupportedOperationException(
  231. "This is supposed to be overridden by subclasses.");
  232. }
  233. /**
  234. * Called by the initialization and clear code paths to allow subclasses to
  235. * reset any of their builtin fields back to the initial values.
  236. */
  237. public BuilderType clear() {
  238. unknownFields = UnknownFieldSet.getDefaultInstance();
  239. onChanged();
  240. return (BuilderType) this;
  241. }
  242. /**
  243. * Get the FieldAccessorTable for this type. We can't have the message
  244. * class pass this in to the constructor because of bootstrapping trouble
  245. * with DescriptorProtos.
  246. */
  247. protected abstract FieldAccessorTable internalGetFieldAccessorTable();
  248. //@Override (Java 1.6 override semantics, but we must support 1.5)
  249. public Descriptor getDescriptorForType() {
  250. return internalGetFieldAccessorTable().descriptor;
  251. }
  252. //@Override (Java 1.6 override semantics, but we must support 1.5)
  253. public Map<FieldDescriptor, Object> getAllFields() {
  254. return Collections.unmodifiableMap(getAllFieldsMutable());
  255. }
  256. /** Internal helper which returns a mutable map. */
  257. private Map<FieldDescriptor, Object> getAllFieldsMutable() {
  258. final TreeMap<FieldDescriptor, Object> result =
  259. new TreeMap<FieldDescriptor, Object>();
  260. final Descriptor descriptor = internalGetFieldAccessorTable().descriptor;
  261. for (final FieldDescriptor field : descriptor.getFields()) {
  262. if (field.isRepeated()) {
  263. final List value = (List) getField(field);
  264. if (!value.isEmpty()) {
  265. result.put(field, value);
  266. }
  267. } else {
  268. if (hasField(field)) {
  269. result.put(field, getField(field));
  270. }
  271. }
  272. }
  273. return result;
  274. }
  275. public Message.Builder newBuilderForField(
  276. final FieldDescriptor field) {
  277. return internalGetFieldAccessorTable().getField(field).newBuilder();
  278. }
  279. //@Override (Java 1.6 override semantics, but we must support 1.5)
  280. public boolean hasField(final FieldDescriptor field) {
  281. return internalGetFieldAccessorTable().getField(field).has(this);
  282. }
  283. //@Override (Java 1.6 override semantics, but we must support 1.5)
  284. public Object getField(final FieldDescriptor field) {
  285. Object object = internalGetFieldAccessorTable().getField(field).get(this);
  286. if (field.isRepeated()) {
  287. // The underlying list object is still modifiable at this point.
  288. // Make sure not to expose the modifiable list to the caller.
  289. return Collections.unmodifiableList((List) object);
  290. } else {
  291. return object;
  292. }
  293. }
  294. public BuilderType setField(final FieldDescriptor field,
  295. final Object value) {
  296. internalGetFieldAccessorTable().getField(field).set(this, value);
  297. return (BuilderType) this;
  298. }
  299. //@Override (Java 1.6 override semantics, but we must support 1.5)
  300. public BuilderType clearField(final FieldDescriptor field) {
  301. internalGetFieldAccessorTable().getField(field).clear(this);
  302. return (BuilderType) this;
  303. }
  304. //@Override (Java 1.6 override semantics, but we must support 1.5)
  305. public int getRepeatedFieldCount(final FieldDescriptor field) {
  306. return internalGetFieldAccessorTable().getField(field)
  307. .getRepeatedCount(this);
  308. }
  309. //@Override (Java 1.6 override semantics, but we must support 1.5)
  310. public Object getRepeatedField(final FieldDescriptor field,
  311. final int index) {
  312. return internalGetFieldAccessorTable().getField(field)
  313. .getRepeated(this, index);
  314. }
  315. public BuilderType setRepeatedField(final FieldDescriptor field,
  316. final int index, final Object value) {
  317. internalGetFieldAccessorTable().getField(field)
  318. .setRepeated(this, index, value);
  319. return (BuilderType) this;
  320. }
  321. public BuilderType addRepeatedField(final FieldDescriptor field,
  322. final Object value) {
  323. internalGetFieldAccessorTable().getField(field).addRepeated(this, value);
  324. return (BuilderType) this;
  325. }
  326. public final BuilderType setUnknownFields(
  327. final UnknownFieldSet unknownFields) {
  328. this.unknownFields = unknownFields;
  329. onChanged();
  330. return (BuilderType) this;
  331. }
  332. @Override
  333. public final BuilderType mergeUnknownFields(
  334. final UnknownFieldSet unknownFields) {
  335. this.unknownFields =
  336. UnknownFieldSet.newBuilder(this.unknownFields)
  337. .mergeFrom(unknownFields)
  338. .build();
  339. onChanged();
  340. return (BuilderType) this;
  341. }
  342. //@Override (Java 1.6 override semantics, but we must support 1.5)
  343. public boolean isInitialized() {
  344. for (final FieldDescriptor field : getDescriptorForType().getFields()) {
  345. // Check that all required fields are present.
  346. if (field.isRequired()) {
  347. if (!hasField(field)) {
  348. return false;
  349. }
  350. }
  351. // Check that embedded messages are initialized.
  352. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
  353. if (field.isRepeated()) {
  354. @SuppressWarnings("unchecked") final
  355. List<Message> messageList = (List<Message>) getField(field);
  356. for (final Message element : messageList) {
  357. if (!element.isInitialized()) {
  358. return false;
  359. }
  360. }
  361. } else {
  362. if (hasField(field) &&
  363. !((Message) getField(field)).isInitialized()) {
  364. return false;
  365. }
  366. }
  367. }
  368. }
  369. return true;
  370. }
  371. //@Override (Java 1.6 override semantics, but we must support 1.5)
  372. public final UnknownFieldSet getUnknownFields() {
  373. return unknownFields;
  374. }
  375. /**
  376. * Called by subclasses to parse an unknown field.
  377. * @return {@code true} unless the tag is an end-group tag.
  378. */
  379. protected boolean parseUnknownField(
  380. final CodedInputStream input,
  381. final UnknownFieldSet.Builder unknownFields,
  382. final ExtensionRegistryLite extensionRegistry,
  383. final int tag) throws IOException {
  384. return unknownFields.mergeFieldFrom(tag, input);
  385. }
  386. /**
  387. * Implementation of {@link BuilderParent} for giving to our children. This
  388. * small inner class makes it so we don't publicly expose the BuilderParent
  389. * methods.
  390. */
  391. private class BuilderParentImpl implements BuilderParent {
  392. //@Override (Java 1.6 override semantics, but we must support 1.5)
  393. public void markDirty() {
  394. onChanged();
  395. }
  396. }
  397. /**
  398. * Gets the {@link BuilderParent} for giving to our children.
  399. * @return The builder parent for our children.
  400. */
  401. protected BuilderParent getParentForChildren() {
  402. if (meAsParent == null) {
  403. meAsParent = new BuilderParentImpl();
  404. }
  405. return meAsParent;
  406. }
  407. /**
  408. * Called when a the builder or one of its nested children has changed
  409. * and any parent should be notified of its invalidation.
  410. */
  411. protected final void onChanged() {
  412. if (isClean && builderParent != null) {
  413. builderParent.markDirty();
  414. // Don't keep dispatching invalidations until build is called again.
  415. isClean = false;
  416. }
  417. }
  418. }
  419. // =================================================================
  420. // Extensions-related stuff
  421. public interface ExtendableMessageOrBuilder<
  422. MessageType extends ExtendableMessage> extends MessageOrBuilder {
  423. /** Check if a singular extension is present. */
  424. <Type> boolean hasExtension(
  425. GeneratedExtension<MessageType, Type> extension);
  426. /** Get the number of elements in a repeated extension. */
  427. <Type> int getExtensionCount(
  428. GeneratedExtension<MessageType, List<Type>> extension);
  429. /** Get the value of an extension. */
  430. <Type> Type getExtension(GeneratedExtension<MessageType, Type> extension);
  431. /** Get one element of a repeated extension. */
  432. <Type> Type getExtension(
  433. GeneratedExtension<MessageType, List<Type>> extension,
  434. int index);
  435. }
  436. /**
  437. * Generated message classes for message types that contain extension ranges
  438. * subclass this.
  439. *
  440. * <p>This class implements type-safe accessors for extensions. They
  441. * implement all the same operations that you can do with normal fields --
  442. * e.g. "has", "get", and "getCount" -- but for extensions. The extensions
  443. * are identified using instances of the class {@link GeneratedExtension};
  444. * the protocol compiler generates a static instance of this class for every
  445. * extension in its input. Through the magic of generics, all is made
  446. * type-safe.
  447. *
  448. * <p>For example, imagine you have the {@code .proto} file:
  449. *
  450. * <pre>
  451. * option java_class = "MyProto";
  452. *
  453. * message Foo {
  454. * extensions 1000 to max;
  455. * }
  456. *
  457. * extend Foo {
  458. * optional int32 bar;
  459. * }
  460. * </pre>
  461. *
  462. * <p>Then you might write code like:
  463. *
  464. * <pre>
  465. * MyProto.Foo foo = getFoo();
  466. * int i = foo.getExtension(MyProto.bar);
  467. * </pre>
  468. *
  469. * <p>See also {@link ExtendableBuilder}.
  470. */
  471. public abstract static class ExtendableMessage<
  472. MessageType extends ExtendableMessage>
  473. extends GeneratedMessage
  474. implements ExtendableMessageOrBuilder<MessageType> {
  475. private final FieldSet<FieldDescriptor> extensions;
  476. protected ExtendableMessage() {
  477. this.extensions = FieldSet.newFieldSet();
  478. }
  479. protected ExtendableMessage(
  480. ExtendableBuilder<MessageType, ?> builder) {
  481. super(builder);
  482. this.extensions = builder.buildExtensions();
  483. }
  484. private void verifyExtensionContainingType(
  485. final GeneratedExtension<MessageType, ?> extension) {
  486. if (extension.getDescriptor().getContainingType() !=
  487. getDescriptorForType()) {
  488. // This can only happen if someone uses unchecked operations.
  489. throw new IllegalArgumentException(
  490. "Extension is for type \"" +
  491. extension.getDescriptor().getContainingType().getFullName() +
  492. "\" which does not match message type \"" +
  493. getDescriptorForType().getFullName() + "\".");
  494. }
  495. }
  496. /** Check if a singular extension is present. */
  497. //@Override (Java 1.6 override semantics, but we must support 1.5)
  498. public final <Type> boolean hasExtension(
  499. final GeneratedExtension<MessageType, Type> extension) {
  500. verifyExtensionContainingType(extension);
  501. return extensions.hasField(extension.getDescriptor());
  502. }
  503. /** Get the number of elements in a repeated extension. */
  504. //@Override (Java 1.6 override semantics, but we must support 1.5)
  505. public final <Type> int getExtensionCount(
  506. final GeneratedExtension<MessageType, List<Type>> extension) {
  507. verifyExtensionContainingType(extension);
  508. final FieldDescriptor descriptor = extension.getDescriptor();
  509. return extensions.getRepeatedFieldCount(descriptor);
  510. }
  511. /** Get the value of an extension. */
  512. //@Override (Java 1.6 override semantics, but we must support 1.5)
  513. @SuppressWarnings("unchecked")
  514. public final <Type> Type getExtension(
  515. final GeneratedExtension<MessageType, Type> extension) {
  516. verifyExtensionContainingType(extension);
  517. FieldDescriptor descriptor = extension.getDescriptor();
  518. final Object value = extensions.getField(descriptor);
  519. if (value == null) {
  520. if (descriptor.isRepeated()) {
  521. return (Type) Collections.emptyList();
  522. } else if (descriptor.getJavaType() ==
  523. FieldDescriptor.JavaType.MESSAGE) {
  524. return (Type) extension.getMessageDefaultInstance();
  525. } else {
  526. return (Type) extension.fromReflectionType(
  527. descriptor.getDefaultValue());
  528. }
  529. } else {
  530. return (Type) extension.fromReflectionType(value);
  531. }
  532. }
  533. /** Get one element of a repeated extension. */
  534. //@Override (Java 1.6 override semantics, but we must support 1.5)
  535. @SuppressWarnings("unchecked")
  536. public final <Type> Type getExtension(
  537. final GeneratedExtension<MessageType, List<Type>> extension,
  538. final int index) {
  539. verifyExtensionContainingType(extension);
  540. FieldDescriptor descriptor = extension.getDescriptor();
  541. return (Type) extension.singularFromReflectionType(
  542. extensions.getRepeatedField(descriptor, index));
  543. }
  544. /** Called by subclasses to check if all extensions are initialized. */
  545. protected boolean extensionsAreInitialized() {
  546. return extensions.isInitialized();
  547. }
  548. @Override
  549. public boolean isInitialized() {
  550. return super.isInitialized() && extensionsAreInitialized();
  551. }
  552. /**
  553. * Used by subclasses to serialize extensions. Extension ranges may be
  554. * interleaved with field numbers, but we must write them in canonical
  555. * (sorted by field number) order. ExtensionWriter helps us write
  556. * individual ranges of extensions at once.
  557. */
  558. protected class ExtensionWriter {
  559. // Imagine how much simpler this code would be if Java iterators had
  560. // a way to get the next element without advancing the iterator.
  561. private final Iterator<Map.Entry<FieldDescriptor, Object>> iter =
  562. extensions.iterator();
  563. private Map.Entry<FieldDescriptor, Object> next;
  564. private final boolean messageSetWireFormat;
  565. private ExtensionWriter(final boolean messageSetWireFormat) {
  566. if (iter.hasNext()) {
  567. next = iter.next();
  568. }
  569. this.messageSetWireFormat = messageSetWireFormat;
  570. }
  571. public void writeUntil(final int end, final CodedOutputStream output)
  572. throws IOException {
  573. while (next != null && next.getKey().getNumber() < end) {
  574. FieldDescriptor descriptor = next.getKey();
  575. if (messageSetWireFormat && descriptor.getLiteJavaType() ==
  576. WireFormat.JavaType.MESSAGE &&
  577. !descriptor.isRepeated()) {
  578. output.writeMessageSetExtension(descriptor.getNumber(),
  579. (Message) next.getValue());
  580. } else {
  581. FieldSet.writeField(descriptor, next.getValue(), output);
  582. }
  583. if (iter.hasNext()) {
  584. next = iter.next();
  585. } else {
  586. next = null;
  587. }
  588. }
  589. }
  590. }
  591. protected ExtensionWriter newExtensionWriter() {
  592. return new ExtensionWriter(false);
  593. }
  594. protected ExtensionWriter newMessageSetExtensionWriter() {
  595. return new ExtensionWriter(true);
  596. }
  597. /** Called by subclasses to compute the size of extensions. */
  598. protected int extensionsSerializedSize() {
  599. return extensions.getSerializedSize();
  600. }
  601. protected int extensionsSerializedSizeAsMessageSet() {
  602. return extensions.getMessageSetSerializedSize();
  603. }
  604. // ---------------------------------------------------------------
  605. // Reflection
  606. protected Map<FieldDescriptor, Object> getExtensionFields() {
  607. return extensions.getAllFields();
  608. }
  609. @Override
  610. public Map<FieldDescriptor, Object> getAllFields() {
  611. final Map<FieldDescriptor, Object> result = super.getAllFieldsMutable();
  612. result.putAll(getExtensionFields());
  613. return Collections.unmodifiableMap(result);
  614. }
  615. @Override
  616. public boolean hasField(final FieldDescriptor field) {
  617. if (field.isExtension()) {
  618. verifyContainingType(field);
  619. return extensions.hasField(field);
  620. } else {
  621. return super.hasField(field);
  622. }
  623. }
  624. @Override
  625. public Object getField(final FieldDescriptor field) {
  626. if (field.isExtension()) {
  627. verifyContainingType(field);
  628. final Object value = extensions.getField(field);
  629. if (value == null) {
  630. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
  631. // Lacking an ExtensionRegistry, we have no way to determine the
  632. // extension's real type, so we return a DynamicMessage.
  633. return DynamicMessage.getDefaultInstance(field.getMessageType());
  634. } else {
  635. return field.getDefaultValue();
  636. }
  637. } else {
  638. return value;
  639. }
  640. } else {
  641. return super.getField(field);
  642. }
  643. }
  644. @Override
  645. public int getRepeatedFieldCount(final FieldDescriptor field) {
  646. if (field.isExtension()) {
  647. verifyContainingType(field);
  648. return extensions.getRepeatedFieldCount(field);
  649. } else {
  650. return super.getRepeatedFieldCount(field);
  651. }
  652. }
  653. @Override
  654. public Object getRepeatedField(final FieldDescriptor field,
  655. final int index) {
  656. if (field.isExtension()) {
  657. verifyContainingType(field);
  658. return extensions.getRepeatedField(field, index);
  659. } else {
  660. return super.getRepeatedField(field, index);
  661. }
  662. }
  663. private void verifyContainingType(final FieldDescriptor field) {
  664. if (field.getContainingType() != getDescriptorForType()) {
  665. throw new IllegalArgumentException(
  666. "FieldDescriptor does not match message type.");
  667. }
  668. }
  669. }
  670. /**
  671. * Generated message builders for message types that contain extension ranges
  672. * subclass this.
  673. *
  674. * <p>This class implements type-safe accessors for extensions. They
  675. * implement all the same operations that you can do with normal fields --
  676. * e.g. "get", "set", and "add" -- but for extensions. The extensions are
  677. * identified using instances of the class {@link GeneratedExtension}; the
  678. * protocol compiler generates a static instance of this class for every
  679. * extension in its input. Through the magic of generics, all is made
  680. * type-safe.
  681. *
  682. * <p>For example, imagine you have the {@code .proto} file:
  683. *
  684. * <pre>
  685. * option java_class = "MyProto";
  686. *
  687. * message Foo {
  688. * extensions 1000 to max;
  689. * }
  690. *
  691. * extend Foo {
  692. * optional int32 bar;
  693. * }
  694. * </pre>
  695. *
  696. * <p>Then you might write code like:
  697. *
  698. * <pre>
  699. * MyProto.Foo foo =
  700. * MyProto.Foo.newBuilder()
  701. * .setExtension(MyProto.bar, 123)
  702. * .build();
  703. * </pre>
  704. *
  705. * <p>See also {@link ExtendableMessage}.
  706. */
  707. @SuppressWarnings("unchecked")
  708. public abstract static class ExtendableBuilder<
  709. MessageType extends ExtendableMessage,
  710. BuilderType extends ExtendableBuilder>
  711. extends Builder<BuilderType>
  712. implements ExtendableMessageOrBuilder<MessageType> {
  713. private FieldSet<FieldDescriptor> extensions = FieldSet.emptySet();
  714. protected ExtendableBuilder() {}
  715. protected ExtendableBuilder(
  716. BuilderParent parent) {
  717. super(parent);
  718. }
  719. @Override
  720. public BuilderType clear() {
  721. extensions = FieldSet.emptySet();
  722. return super.clear();
  723. }
  724. // This is implemented here only to work around an apparent bug in the
  725. // Java compiler and/or build system. See bug #1898463. The mere presence
  726. // of this dummy clone() implementation makes it go away.
  727. @Override
  728. public BuilderType clone() {
  729. throw new UnsupportedOperationException(
  730. "This is supposed to be overridden by subclasses.");
  731. }
  732. private void ensureExtensionsIsMutable() {
  733. if (extensions.isImmutable()) {
  734. extensions = extensions.clone();
  735. }
  736. }
  737. private void verifyExtensionContainingType(
  738. final GeneratedExtension<MessageType, ?> extension) {
  739. if (extension.getDescriptor().getContainingType() !=
  740. getDescriptorForType()) {
  741. // This can only happen if someone uses unchecked operations.
  742. throw new IllegalArgumentException(
  743. "Extension is for type \"" +
  744. extension.getDescriptor().getContainingType().getFullName() +
  745. "\" which does not match message type \"" +
  746. getDescriptorForType().getFullName() + "\".");
  747. }
  748. }
  749. /** Check if a singular extension is present. */
  750. //@Override (Java 1.6 override semantics, but we must support 1.5)
  751. public final <Type> boolean hasExtension(
  752. final GeneratedExtension<MessageType, Type> extension) {
  753. verifyExtensionContainingType(extension);
  754. return extensions.hasField(extension.getDescriptor());
  755. }
  756. /** Get the number of elements in a repeated extension. */
  757. //@Override (Java 1.6 override semantics, but we must support 1.5)
  758. public final <Type> int getExtensionCount(
  759. final GeneratedExtension<MessageType, List<Type>> extension) {
  760. verifyExtensionContainingType(extension);
  761. final FieldDescriptor descriptor = extension.getDescriptor();
  762. return extensions.getRepeatedFieldCount(descriptor);
  763. }
  764. /** Get the value of an extension. */
  765. //@Override (Java 1.6 override semantics, but we must support 1.5)
  766. public final <Type> Type getExtension(
  767. final GeneratedExtension<MessageType, Type> extension) {
  768. verifyExtensionContainingType(extension);
  769. FieldDescriptor descriptor = extension.getDescriptor();
  770. final Object value = extensions.getField(descriptor);
  771. if (value == null) {
  772. if (descriptor.isRepeated()) {
  773. return (Type) Collections.emptyList();
  774. } else if (descriptor.getJavaType() ==
  775. FieldDescriptor.JavaType.MESSAGE) {
  776. return (Type) extension.getMessageDefaultInstance();
  777. } else {
  778. return (Type) extension.fromReflectionType(
  779. descriptor.getDefaultValue());
  780. }
  781. } else {
  782. return (Type) extension.fromReflectionType(value);
  783. }
  784. }
  785. /** Get one element of a repeated extension. */
  786. //@Override (Java 1.6 override semantics, but we must support 1.5)
  787. public final <Type> Type getExtension(
  788. final GeneratedExtension<MessageType, List<Type>> extension,
  789. final int index) {
  790. verifyExtensionContainingType(extension);
  791. FieldDescriptor descriptor = extension.getDescriptor();
  792. return (Type) extension.singularFromReflectionType(
  793. extensions.getRepeatedField(descriptor, index));
  794. }
  795. /** Set the value of an extension. */
  796. public final <Type> BuilderType setExtension(
  797. final GeneratedExtension<MessageType, Type> extension,
  798. final Type value) {
  799. verifyExtensionContainingType(extension);
  800. ensureExtensionsIsMutable();
  801. final FieldDescriptor descriptor = extension.getDescriptor();
  802. extensions.setField(descriptor, extension.toReflectionType(value));
  803. onChanged();
  804. return (BuilderType) this;
  805. }
  806. /** Set the value of one element of a repeated extension. */
  807. public final <Type> BuilderType setExtension(
  808. final GeneratedExtension<MessageType, List<Type>> extension,
  809. final int index, final Type value) {
  810. verifyExtensionContainingType(extension);
  811. ensureExtensionsIsMutable();
  812. final FieldDescriptor descriptor = extension.getDescriptor();
  813. extensions.setRepeatedField(
  814. descriptor, index,
  815. extension.singularToReflectionType(value));
  816. onChanged();
  817. return (BuilderType) this;
  818. }
  819. /** Append a value to a repeated extension. */
  820. public final <Type> BuilderType addExtension(
  821. final GeneratedExtension<MessageType, List<Type>> extension,
  822. final Type value) {
  823. verifyExtensionContainingType(extension);
  824. ensureExtensionsIsMutable();
  825. final FieldDescriptor descriptor = extension.getDescriptor();
  826. extensions.addRepeatedField(
  827. descriptor, extension.singularToReflectionType(value));
  828. onChanged();
  829. return (BuilderType) this;
  830. }
  831. /** Clear an extension. */
  832. public final <Type> BuilderType clearExtension(
  833. final GeneratedExtension<MessageType, ?> extension) {
  834. verifyExtensionContainingType(extension);
  835. ensureExtensionsIsMutable();
  836. extensions.clearField(extension.getDescriptor());
  837. onChanged();
  838. return (BuilderType) this;
  839. }
  840. /** Called by subclasses to check if all extensions are initialized. */
  841. protected boolean extensionsAreInitialized() {
  842. return extensions.isInitialized();
  843. }
  844. /**
  845. * Called by the build code path to create a copy of the extensions for
  846. * building the message.
  847. */
  848. private FieldSet<FieldDescriptor> buildExtensions() {
  849. extensions.makeImmutable();
  850. return extensions;
  851. }
  852. @Override
  853. public boolean isInitialized() {
  854. return super.isInitialized() && extensionsAreInitialized();
  855. }
  856. /**
  857. * Called by subclasses to parse an unknown field or an extension.
  858. * @return {@code true} unless the tag is an end-group tag.
  859. */
  860. @Override
  861. protected boolean parseUnknownField(
  862. final CodedInputStream input,
  863. final UnknownFieldSet.Builder unknownFields,
  864. final ExtensionRegistryLite extensionRegistry,
  865. final int tag) throws IOException {
  866. return AbstractMessage.Builder.mergeFieldFrom(
  867. input, unknownFields, extensionRegistry, this, tag);
  868. }
  869. // ---------------------------------------------------------------
  870. // Reflection
  871. @Override
  872. public Map<FieldDescriptor, Object> getAllFields() {
  873. final Map<FieldDescriptor, Object> result = super.getAllFieldsMutable();
  874. result.putAll(extensions.getAllFields());
  875. return Collections.unmodifiableMap(result);
  876. }
  877. @Override
  878. public Object getField(final FieldDescriptor field) {
  879. if (field.isExtension()) {
  880. verifyContainingType(field);
  881. final Object value = extensions.getField(field);
  882. if (value == null) {
  883. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
  884. // Lacking an ExtensionRegistry, we have no way to determine the
  885. // extension's real type, so we return a DynamicMessage.
  886. return DynamicMessage.getDefaultInstance(field.getMessageType());
  887. } else {
  888. return field.getDefaultValue();
  889. }
  890. } else {
  891. return value;
  892. }
  893. } else {
  894. return super.getField(field);
  895. }
  896. }
  897. @Override
  898. public int getRepeatedFieldCount(final FieldDescriptor field) {
  899. if (field.isExtension()) {
  900. verifyContainingType(field);
  901. return extensions.getRepeatedFieldCount(field);
  902. } else {
  903. return super.getRepeatedFieldCount(field);
  904. }
  905. }
  906. @Override
  907. public Object getRepeatedField(final FieldDescriptor field,
  908. final int index) {
  909. if (field.isExtension()) {
  910. verifyContainingType(field);
  911. return extensions.getRepeatedField(field, index);
  912. } else {
  913. return super.getRepeatedField(field, index);
  914. }
  915. }
  916. @Override
  917. public boolean hasField(final FieldDescriptor field) {
  918. if (field.isExtension()) {
  919. verifyContainingType(field);
  920. return extensions.hasField(field);
  921. } else {
  922. return super.hasField(field);
  923. }
  924. }
  925. @Override
  926. public BuilderType setField(final FieldDescriptor field,
  927. final Object value) {
  928. if (field.isExtension()) {
  929. verifyContainingType(field);
  930. ensureExtensionsIsMutable();
  931. extensions.setField(field, value);
  932. onChanged();
  933. return (BuilderType) this;
  934. } else {
  935. return super.setField(field, value);
  936. }
  937. }
  938. @Override
  939. public BuilderType clearField(final FieldDescriptor field) {
  940. if (field.isExtension()) {
  941. verifyContainingType(field);
  942. ensureExtensionsIsMutable();
  943. extensions.clearField(field);
  944. onChanged();
  945. return (BuilderType) this;
  946. } else {
  947. return super.clearField(field);
  948. }
  949. }
  950. @Override
  951. public BuilderType setRepeatedField(final FieldDescriptor field,
  952. final int index, final Object value) {
  953. if (field.isExtension()) {
  954. verifyContainingType(field);
  955. ensureExtensionsIsMutable();
  956. extensions.setRepeatedField(field, index, value);
  957. onChanged();
  958. return (BuilderType) this;
  959. } else {
  960. return super.setRepeatedField(field, index, value);
  961. }
  962. }
  963. @Override
  964. public BuilderType addRepeatedField(final FieldDescriptor field,
  965. final Object value) {
  966. if (field.isExtension()) {
  967. verifyContainingType(field);
  968. ensureExtensionsIsMutable();
  969. extensions.addRepeatedField(field, value);
  970. onChanged();
  971. return (BuilderType) this;
  972. } else {
  973. return super.addRepeatedField(field, value);
  974. }
  975. }
  976. protected final void mergeExtensionFields(final ExtendableMessage other) {
  977. ensureExtensionsIsMutable();
  978. extensions.mergeFrom(other.extensions);
  979. onChanged();
  980. }
  981. private void verifyContainingType(final FieldDescriptor field) {
  982. if (field.getContainingType() != getDescriptorForType()) {
  983. throw new IllegalArgumentException(
  984. "FieldDescriptor does not match message type.");
  985. }
  986. }
  987. }
  988. // -----------------------------------------------------------------
  989. /**
  990. * Gets the descriptor for an extension. The implementation depends on whether
  991. * the extension is scoped in the top level of a file or scoped in a Message.
  992. */
  993. private static interface ExtensionDescriptorRetriever {
  994. FieldDescriptor getDescriptor();
  995. }
  996. /** For use by generated code only. */
  997. public static <ContainingType extends Message, Type>
  998. GeneratedExtension<ContainingType, Type>
  999. newMessageScopedGeneratedExtension(final Message scope,
  1000. final int descriptorIndex,
  1001. final Class singularType,
  1002. final Message defaultInstance) {
  1003. // For extensions scoped within a Message, we use the Message to resolve
  1004. // the outer class's descriptor, from which the extension descriptor is
  1005. // obtained.
  1006. return new GeneratedExtension<ContainingType, Type>(
  1007. new ExtensionDescriptorRetriever() {
  1008. //@Override (Java 1.6 override semantics, but we must support 1.5)
  1009. public FieldDescriptor getDescriptor() {
  1010. return scope.getDescriptorForType().getExtensions()
  1011. .get(descriptorIndex);
  1012. }
  1013. },
  1014. singularType,
  1015. defaultInstance);
  1016. }
  1017. /** For use by generated code only. */
  1018. public static <ContainingType extends Message, Type>
  1019. GeneratedExtension<ContainingType, Type>
  1020. newFileScopedGeneratedExtension(final Class singularType,
  1021. final Message defaultInstance) {
  1022. // For extensions scoped within a file, we rely on the outer class's
  1023. // static initializer to call internalInit() on the extension when the
  1024. // descriptor is available.
  1025. return new GeneratedExtension<ContainingType, Type>(
  1026. null, // ExtensionDescriptorRetriever is initialized in internalInit();
  1027. singularType,
  1028. defaultInstance);
  1029. }
  1030. /**
  1031. * Type used to represent generated extensions. The protocol compiler
  1032. * generates a static singleton instance of this class for each extension.
  1033. *
  1034. * <p>For example, imagine you have the {@code .proto} file:
  1035. *
  1036. * <pre>
  1037. * option java_class = "MyProto";
  1038. *
  1039. * message Foo {
  1040. * extensions 1000 to max;
  1041. * }
  1042. *
  1043. * extend Foo {
  1044. * optional int32 bar;
  1045. * }
  1046. * </pre>
  1047. *
  1048. * <p>Then, {@code MyProto.Foo.bar} has type
  1049. * {@code GeneratedExtension<MyProto.Foo, Integer>}.
  1050. *
  1051. * <p>In general, users should ignore the details of this type, and simply use
  1052. * these static singletons as parameters to the extension accessors defined
  1053. * in {@link ExtendableMessage} and {@link ExtendableBuilder}.
  1054. */
  1055. public static final class GeneratedExtension<
  1056. ContainingType extends Message, Type> {
  1057. // TODO(kenton): Find ways to avoid using Java reflection within this
  1058. // class. Also try to avoid suppressing unchecked warnings.
  1059. // We can't always initialize the descriptor of a GeneratedExtension when
  1060. // we first construct it due to initialization order difficulties (namely,
  1061. // the descriptor may not have been constructed yet, since it is often
  1062. // constructed by the initializer of a separate module).
  1063. //
  1064. // In the case of nested extensions, we initialize the
  1065. // ExtensionDescriptorRetriever with an instance that uses the scoping
  1066. // Message's default instance to retrieve the extension's descriptor.
  1067. //
  1068. // In the case of non-nested extensions, we initialize the
  1069. // ExtensionDescriptorRetriever to null and rely on the outer class's static
  1070. // initializer to call internalInit() after the descriptor has been parsed.
  1071. private GeneratedExtension(ExtensionDescriptorRetriever descriptorRetriever,
  1072. Class singularType,
  1073. Message messageDefaultInstance) {
  1074. if (Message.class.isAssignableFrom(singularType) &&
  1075. !singularType.isInstance(messageDefaultInstance)) {
  1076. throw new IllegalArgumentException(
  1077. "Bad messageDefaultInstance for " + singularType.getName());
  1078. }
  1079. this.descriptorRetriever = descriptorRetriever;
  1080. this.singularType = singularType;
  1081. this.messageDefaultInstance = messageDefaultInstance;
  1082. if (ProtocolMessageEnum.class.isAssignableFrom(singularType)) {
  1083. this.enumValueOf = getMethodOrDie(singularType, "valueOf",
  1084. EnumValueDescriptor.class);
  1085. this.enumGetValueDescriptor =
  1086. getMethodOrDie(singularType, "getValueDescriptor");
  1087. } else {
  1088. this.enumValueOf = null;
  1089. this.enumGetValueDescriptor = null;
  1090. }
  1091. }
  1092. /** For use by generated code only. */
  1093. public void internalInit(final FieldDescriptor descriptor) {
  1094. if (descriptorRetriever != null) {
  1095. throw new IllegalStateException("Already initialized.");
  1096. }
  1097. descriptorRetriever = new ExtensionDescriptorRetriever() {
  1098. //@Override (Java 1.6 override semantics, but we must support 1.5)
  1099. public FieldDescriptor getDescriptor() {
  1100. return descriptor;
  1101. }
  1102. };
  1103. }
  1104. private ExtensionDescriptorRetriever descriptorRetriever;
  1105. private final Class singularType;
  1106. private final Message messageDefaultInstance;
  1107. private final Method enumValueOf;
  1108. private final Method enumGetValueDescriptor;
  1109. public FieldDescriptor getDescriptor() {
  1110. if (descriptorRetriever == null) {
  1111. throw new IllegalStateException(
  1112. "getDescriptor() called before internalInit()");
  1113. }
  1114. return descriptorRetriever.getDescriptor();
  1115. }
  1116. /**
  1117. * If the extension is an embedded message or group, returns the default
  1118. * instance of the message.
  1119. */
  1120. public Message getMessageDefaultInstance() {
  1121. return messageDefaultInstance;
  1122. }
  1123. /**
  1124. * Convert from the type used by the reflection accessors to the type used
  1125. * by native accessors. E.g., for enums, the reflection accessors use
  1126. * EnumValueDescriptors but the native accessors use the generated enum
  1127. * type.
  1128. */
  1129. @SuppressWarnings("unchecked")
  1130. private Object fromReflectionType(final Object value) {
  1131. FieldDescriptor descriptor = getDescriptor();
  1132. if (descriptor.isRepeated()) {
  1133. if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE ||
  1134. descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) {
  1135. // Must convert the whole list.
  1136. final List result = new ArrayList();
  1137. for (final Object element : (List) value) {
  1138. result.add(singularFromReflectionType(element));
  1139. }
  1140. return result;
  1141. } else {
  1142. return value;
  1143. }
  1144. } else {
  1145. return singularFromReflectionType(value);
  1146. }
  1147. }
  1148. /**
  1149. * Like {@link #fromReflectionType(Object)}, but if the type is a repeated
  1150. * type, this converts a single element.
  1151. */
  1152. private Object singularFromReflectionType(final Object value) {
  1153. FieldDescriptor descriptor = getDescriptor();
  1154. switch (descriptor.getJavaType()) {
  1155. case MESSAGE:
  1156. if (singularType.isInstance(value)) {
  1157. return value;
  1158. } else {
  1159. // It seems the copy of the embedded message stored inside the
  1160. // extended message is not of the exact type the user was
  1161. // expecting. This can happen if a user defines a
  1162. // GeneratedExtension manually and gives it a different type.
  1163. // This should not happen in normal use. But, to be nice, we'll
  1164. // copy the message to whatever type the caller was expecting.
  1165. return messageDefaultInstance.newBuilderForType()
  1166. .mergeFrom((Message) value).build();
  1167. }
  1168. case ENUM:
  1169. return invokeOrDie(enumValueOf, null, (EnumValueDescriptor) value);
  1170. default:
  1171. return value;
  1172. }
  1173. }
  1174. /**
  1175. * Convert from the type used by the native accessors to the type used
  1176. * by reflection accessors. E.g., for enums, the reflection accessors use
  1177. * EnumValueDescriptors but the native accessors use the generated enum
  1178. * type.
  1179. */
  1180. @SuppressWarnings("unchecked")
  1181. private Object toReflectionType(final Object value) {
  1182. FieldDescriptor descriptor = getDescriptor();
  1183. if (descriptor.isRepeated()) {
  1184. if (descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) {
  1185. // Must convert the whole list.
  1186. final List result = new ArrayList();
  1187. for (final Object element : (List) value) {
  1188. result.add(singularToReflectionType(element));
  1189. }
  1190. return result;
  1191. } else {
  1192. return value;
  1193. }
  1194. } else {
  1195. return singularToReflectionType(value);
  1196. }
  1197. }
  1198. /**
  1199. * Like {@link #toReflectionType(Object)}, but if the type is a repeated
  1200. * type, this converts a single element.
  1201. */
  1202. private Object singularToReflectionType(final Object value) {
  1203. FieldDescriptor descriptor = getDescriptor();
  1204. switch (descriptor.getJavaType()) {
  1205. case ENUM:
  1206. return invokeOrDie(enumGetValueDescriptor, value);
  1207. default:
  1208. return value;
  1209. }
  1210. }
  1211. }
  1212. // =================================================================
  1213. /** Calls Class.getMethod and throws a RuntimeException if it fails. */
  1214. @SuppressWarnings("unchecked")
  1215. private static Method getMethodOrDie(
  1216. final Class clazz, final String name, final Class... params) {
  1217. try {
  1218. return clazz.getMethod(name, params);
  1219. } catch (NoSuchMethodException e) {
  1220. throw new RuntimeException(
  1221. "Generated message class \"" + clazz.getName() +
  1222. "\" missing method \"" + name + "\".", e);
  1223. }
  1224. }
  1225. /** Calls invoke and throws a RuntimeException if it fails. */
  1226. private static Object invokeOrDie(
  1227. final Method method, final Object object, final Object... params) {
  1228. try {
  1229. return method.invoke(object, params);
  1230. } catch (IllegalAccessException e) {
  1231. throw new RuntimeException(
  1232. "Couldn't use Java reflection to implement protocol message " +
  1233. "reflection.", e);
  1234. } catch (InvocationTargetException e) {
  1235. final Throwable cause = e.getCause();
  1236. if (cause instanceof RuntimeException) {
  1237. throw (RuntimeException) cause;
  1238. } else if (cause instanceof Error) {
  1239. throw (Error) cause;
  1240. } else {
  1241. throw new RuntimeException(
  1242. "Unexpected exception thrown by generated accessor method.", cause);
  1243. }
  1244. }
  1245. }
  1246. /**
  1247. * Users should ignore this class. This class provides the implementation
  1248. * with access to the fields of a message object using Java reflection.
  1249. */
  1250. public static final class FieldAccessorTable {
  1251. /**
  1252. * Construct a FieldAccessorTable for a particular message class. Only
  1253. * one FieldAccessorTable should ever be constructed per class.
  1254. *
  1255. * @param descriptor The type's descriptor.
  1256. * @param camelCaseNames The camelcase names of all fields in the message.
  1257. * These are used to derive the accessor method names.
  1258. * @param messageClass The message type.
  1259. * @param builderClass The builder type.
  1260. */
  1261. public FieldAccessorTable(
  1262. final Descriptor descriptor,
  1263. final String[] camelCaseNames,
  1264. final Class<? extends GeneratedMessage> messageClass,
  1265. final Class<? extends Builder> builderClass) {
  1266. this.descriptor = descriptor;
  1267. fields = new FieldAccessor[descriptor.getFields().size()];
  1268. for (int i = 0; i < fields.length; i++) {
  1269. final FieldDescriptor field = descriptor.getFields().get(i);
  1270. if (field.isRepeated()) {
  1271. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
  1272. fields[i] = new RepeatedMessageFieldAccessor(
  1273. field, camelCaseNames[i], messageClass, builderClass);
  1274. } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) {
  1275. fields[i] = new RepeatedEnumFieldAccessor(
  1276. field, camelCaseNames[i], messageClass, builderClass);
  1277. } else {
  1278. fields[i] = new RepeatedFieldAccessor(
  1279. field, camelCaseNames[i], messageClass, builderClass);
  1280. }
  1281. } else {
  1282. if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
  1283. fields[i] = new SingularMessageFieldAccessor(
  1284. field, camelCaseNames[i], messageClass, builderClass);
  1285. } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) {
  1286. fields[i] = new SingularEnumFieldAccessor(
  1287. field, camelCaseNames[i], messageClass, builderClass);
  1288. } else {
  1289. fields[i] = new SingularFieldAccessor(
  1290. field, camelCaseNames[i], messageClass, builderClass);
  1291. }
  1292. }
  1293. }
  1294. }
  1295. private final Descriptor descriptor;
  1296. private final FieldAccessor[] fields;
  1297. /** Get the FieldAccessor for a particular field. */
  1298. private FieldAccessor getField(final FieldDescriptor field) {
  1299. if (field.getContainingType() != descriptor) {
  1300. throw new IllegalArgumentException(
  1301. "FieldDescriptor does not match message type.");
  1302. } else if (field.isExtension()) {
  1303. // If this type had extensions, it would subclass ExtendableMessage,
  1304. // which overrides the reflection interface to handle extensions.
  1305. throw new IllegalArgumentException(
  1306. "This type does not have extensions.");
  1307. }
  1308. return fields[field.getIndex()];
  1309. }
  1310. /**
  1311. * Abstract interface that provides access to a single field. This is
  1312. * implemented differently depending on the field type and cardinality.
  1313. */
  1314. private interface FieldAccessor {
  1315. Object get(GeneratedMessage message);
  1316. Object get(GeneratedMessage.Builder builder);
  1317. void set(Builder builder, Object value);
  1318. Object getRepeated(GeneratedMessage message, int index);
  1319. Object getRepeated(GeneratedMessage.Builder builder, int index);
  1320. void setRepeated(Builder builder,
  1321. int index, Object value);
  1322. void addRepeated(Builder builder, Object value);
  1323. boolean has(GeneratedMessage message);
  1324. boolean has(GeneratedMessage.Builder builder);
  1325. int getRepeatedCount(GeneratedMessage message);
  1326. int getRepeatedCount(GeneratedMessage.Builder builder);
  1327. void clear(Builder builder);
  1328. Message.Builder newBuilder();
  1329. }
  1330. // ---------------------------------------------------------------
  1331. private static class SingularFieldAccessor implements FieldAccessor {
  1332. SingularFieldAccessor(
  1333. final FieldDescriptor descriptor, final String camelCaseName,
  1334. final Class<? extends GeneratedMessage> messageClass,
  1335. final Class<? extends Builder> builderClass) {
  1336. getMethod = getMethodOrDie(messageClass, "get" + camelCaseName);
  1337. getMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName);
  1338. type = getMethod.getReturnType();
  1339. setMethod = getMethodOrDie(builderClass, "set" + camelCaseName, type);
  1340. hasMethod =
  1341. getMethodOrDie(messageClass, "has" + camelCaseName);
  1342. hasMethodBuilder =
  1343. getMethodOrDie(builderClass, "has" + camelCaseName);
  1344. clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName);
  1345. }
  1346. // Note: We use Java reflection to call public methods rather than
  1347. // access private fields directly as this avoids runtime security
  1348. // checks.
  1349. protected final Class<?> type;
  1350. protected final Method getMethod;
  1351. protected final Method getMethodBuilder;
  1352. protected final Method setMethod;
  1353. protected final Method hasMethod;
  1354. protected final Method hasMethodBuilder;
  1355. protected final Method clearMethod;
  1356. public Object get(final GeneratedMessage message) {
  1357. return invokeOrDie(getMethod, message);
  1358. }
  1359. public Object get(GeneratedMessage.Builder builder) {
  1360. return invokeOrDie(getMethodBuilder, builder);
  1361. }
  1362. public void set(final Builder builder, final Object value) {
  1363. invokeOrDie(setMethod, builder, value);
  1364. }
  1365. public Object getRepeated(final GeneratedMessage message,
  1366. final int index) {
  1367. throw new UnsupportedOperationException(
  1368. "getRepeatedField() called on a singular field.");
  1369. }
  1370. public Object getRepeated(GeneratedMessage.Builder builder, int index) {
  1371. throw new UnsupportedOperationException(
  1372. "getRepeatedField() called on a singular field.");
  1373. }
  1374. public void setRepeated(final Builder builder,
  1375. final int index, final Object value) {
  1376. throw new UnsupportedOperationException(
  1377. "setRepeatedField() called on a singular field.");
  1378. }
  1379. public void addRepeated(final Builder builder, final Object value) {
  1380. throw new UnsupportedOperationException(
  1381. "addRepeatedField() called on a singular field.");
  1382. }
  1383. public boolean has(final GeneratedMessage message) {
  1384. return (Boolean) invokeOrDie(hasMethod, message);
  1385. }
  1386. public boolean has(GeneratedMessage.Builder builder) {
  1387. return (Boolean) invokeOrDie(hasMethodBuilder, builder);
  1388. }
  1389. public int getRepeatedCount(final GeneratedMessage message) {
  1390. throw new UnsupportedOperationException(
  1391. "getRepeatedFieldSize() called on a singular field.");
  1392. }
  1393. public int getRepeatedCount(GeneratedMessage.Builder builder) {
  1394. throw new UnsupportedOperationException(
  1395. "getRepeatedFieldSize() called on a singular field.");
  1396. }
  1397. public void clear(final Builder builder) {
  1398. invokeOrDie(clearMethod, builder);
  1399. }
  1400. public Message.Builder newBuilder() {
  1401. throw new UnsupportedOperationException(
  1402. "newBuilderForField() called on a non-Message type.");
  1403. }
  1404. }
  1405. private static class RepeatedFieldAccessor implements FieldAccessor {
  1406. protected final Class type;
  1407. protected final Method getMethod;
  1408. protected final Method getMethodBuilder;
  1409. protected final Method getRepeatedMethod;
  1410. protected final Method getRepeatedMethodBuilder;
  1411. protected final Method setRepeatedMethod;
  1412. protected final Method addRepeatedMethod;
  1413. protected final Method getCountMethod;
  1414. protected final Method getCountMethodBuilder;
  1415. protected final Method clearMethod;
  1416. RepeatedFieldAccessor(
  1417. final FieldDescriptor descriptor, final String camelCaseName,
  1418. final Class<? extends GeneratedMessage> messageClass,
  1419. final Class<? extends Builder> builderClass) {
  1420. getMethod = getMethodOrDie(messageClass,
  1421. "get" + camelCaseName + "List");
  1422. getMethodBuilder = getMethodOrDie(builderClass,
  1423. "get" + camelCaseName + "List");
  1424. getRepeatedMethod =
  1425. getMethodOrDie(messageClass, "get" + camelCaseName, Integer.TYPE);
  1426. getRepeatedMethodBuilder =
  1427. getMethodOrDie(builderClass, "get" + camelCaseName, Integer.TYPE);
  1428. type = getRepeatedMethod.getReturnType();
  1429. setRepeatedMethod =
  1430. getMethodOrDie(builderClass, "set" + camelCaseName,
  1431. Integer.TYPE, type);
  1432. addRepeatedMethod =
  1433. getMethodOrDie(builderClass, "add" + camelCaseName, type);
  1434. getCountMethod =
  1435. getMethodOrDie(messageClass, "get" + camelCaseName + "Count");
  1436. getCountMethodBuilder =
  1437. getMethodOrDie(builderClass, "get" + camelCaseName + "Count");
  1438. clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName);
  1439. }
  1440. public Object get(final GeneratedMessage message) {
  1441. return invokeOrDie(getMethod, message);
  1442. }
  1443. public Object get(GeneratedMessage.Builder builder) {
  1444. return invokeOrDie(getMethodBuilder, builder);
  1445. }
  1446. public void set(final Builder builder, final Object value) {
  1447. // Add all the elements individually. This serves two purposes:
  1448. // 1) Verifies that each element has the correct type.
  1449. // 2) Insures that the caller cannot modify the list later on and
  1450. // have the modifications be reflected in the message.
  1451. clear(builder);
  1452. for (final Object element : (List<?>) value) {
  1453. addRepeated(builder, element);
  1454. }
  1455. }
  1456. public Object getRepeated(final GeneratedMessage message,
  1457. final int index) {
  1458. return invokeOrDie(getRepeatedMethod, message, index);
  1459. }
  1460. public Object getRepeated(GeneratedMessage.Builder builder, int index) {
  1461. return invokeOrDie(getRepeatedMethodBuilder, builder, index);
  1462. }
  1463. public void setRepeated(final Builder builder,
  1464. final int index, final Object value) {
  1465. invokeOrDie(setRepeatedMethod, builder, index, value);
  1466. }
  1467. public void addRepeated(final Builder builder, final Object value) {
  1468. invokeOrDie(addRepeatedMethod, builder, value);
  1469. }
  1470. public boolean has(final GeneratedMessage message) {
  1471. throw new UnsupportedOperationException(
  1472. "hasField() called on a singular field.");
  1473. }
  1474. public boolean has(GeneratedMessage.Builder builder) {
  1475. throw new UnsupportedOperationException(
  1476. "hasField() called on a singular field.");
  1477. }
  1478. public int getRepeatedCount(final GeneratedMessage message) {
  1479. return (Integer) invokeOrDie(getCountMethod, message);
  1480. }
  1481. public int getRepeatedCount(GeneratedMessage.Builder builder) {
  1482. return (Integer) invokeOrDie(getCountMethodBuilder, builder);
  1483. }
  1484. public void clear(final Builder builder) {
  1485. invokeOrDie(clearMethod, builder);
  1486. }
  1487. public Message.Builder newBuilder() {
  1488. throw new UnsupportedOperationException(
  1489. "newBuilderForField() called on a non-Message type.");
  1490. }
  1491. }
  1492. // ---------------------------------------------------------------
  1493. private static final class SingularEnumFieldAccessor
  1494. extends SingularFieldAccessor {
  1495. SingularEnumFieldAccessor(
  1496. final FieldDescriptor descriptor, final String camelCaseName,
  1497. final Class<? extends GeneratedMessage> messageClass,
  1498. final Class<? extends Builder> builderClass) {
  1499. super(descriptor, camelCaseName, messageClass, builderClass);
  1500. valueOfMethod = getMethodOrDie(type, "valueOf",
  1501. EnumValueDescriptor.class);
  1502. getValueDescriptorMethod =
  1503. getMethodOrDie(type, "getValueDescriptor");
  1504. }
  1505. private Method valueOfMethod;
  1506. private Method getValueDescriptorMethod;
  1507. @Override
  1508. public Object get(final GeneratedMessage message) {
  1509. return invokeOrDie(getValueDescriptorMethod, super.get(message));
  1510. }
  1511. @Override
  1512. public Object get(final GeneratedMessage.Builder builder) {
  1513. return invokeOrDie(getValueDescriptorMethod, super.get(builder));
  1514. }
  1515. @Override
  1516. public void set(final Builder builder, final Object value) {
  1517. super.set(builder, invokeOrDie(valueOfMethod, null, value));
  1518. }
  1519. }
  1520. private static final class RepeatedEnumFieldAccessor
  1521. extends RepeatedFieldAccessor {
  1522. RepeatedEnumFieldAccessor(
  1523. final FieldDescriptor descriptor, final String camelCaseName,
  1524. final Class<? extends GeneratedMessage> messageClass,
  1525. final Class<? extends Builder> builderClass) {
  1526. super(descriptor, camelCaseName, messageClass, builderClass);
  1527. valueOfMethod = getMethodOrDie(type, "valueOf",
  1528. EnumValueDescriptor.class);
  1529. getValueDescriptorMethod =
  1530. getMethodOrDie(type, "getValueDescriptor");
  1531. }
  1532. private final Method valueOfMethod;
  1533. private final Method getValueDescriptorMethod;
  1534. @Override
  1535. @SuppressWarnings("unchecked")
  1536. public Object get(final GeneratedMessage message) {
  1537. final List newList = new ArrayList();
  1538. for (final Object element : (List) super.get(message)) {
  1539. newList.add(invokeOrDie(getValueDescriptorMethod, element));
  1540. }
  1541. return Collections.unmodifiableList(newList);
  1542. }
  1543. @Override
  1544. @SuppressWarnings("unchecked")
  1545. public Object get(final GeneratedMessage.Builder builder) {
  1546. final List newList = new ArrayList();
  1547. for (final Object element : (List) super.get(builder)) {
  1548. newList.add(invokeOrDie(getValueDescriptorMethod, element));
  1549. }
  1550. return Collections.unmodifiableList(newList);
  1551. }
  1552. @Override
  1553. public Object getRepeated(final GeneratedMessage message,
  1554. final int index) {
  1555. return invokeOrDie(getValueDescriptorMethod,
  1556. super.getRepeated(message, index));
  1557. }
  1558. @Override
  1559. public Object getRepeated(final GeneratedMessage.Builder builder,
  1560. final int index) {
  1561. return invokeOrDie(getValueDescriptorMethod,
  1562. super.getRepeated(builder, index));
  1563. }
  1564. @Override
  1565. public void setRepeated(final Builder builder,
  1566. final int index, final Object value) {
  1567. super.setRepeated(builder, index, invokeOrDie(valueOfMethod, null,
  1568. value));
  1569. }
  1570. @Override
  1571. public void addRepeated(final Builder builder, final Object value) {
  1572. super.addRepeated(builder, invokeOrDie(valueOfMethod, null, value));
  1573. }
  1574. }
  1575. // ---------------------------------------------------------------
  1576. private static final class SingularMessageFieldAccessor
  1577. extends SingularFieldAccessor {
  1578. SingularMessageFieldAccessor(
  1579. final FieldDescriptor descriptor, final String camelCaseName,
  1580. final Class<? extends GeneratedMessage> messageClass,
  1581. final Class<? extends Builder> builderClass) {
  1582. super(descriptor, camelCaseName, messageClass, builderClass);
  1583. newBuilderMethod = getMethodOrDie(type, "newBuilder");
  1584. }
  1585. private final Method newBuilderMethod;
  1586. private Object coerceType(final Object value) {
  1587. if (type.isInstance(value)) {
  1588. return value;
  1589. } else {
  1590. // The value is not the exact right message type. However, if it
  1591. // is an alternative implementation of the same type -- e.g. a
  1592. // DynamicMessage -