Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  // Protocol Buffers - Google's data interchange format
  // Copyright 2008 Google Inc.  All rights reserved.
  // http://code.google.com/p/protobuf/
  //
  // Redistribution and use in source and binary forms, with or without
  // modification, are permitted provided that the following conditions are
  // met:
  //
  //     * Redistributions of source code must retain the above copyright
 // notice, this list of conditions and the following disclaimer.
 //     * Redistributions in binary form must reproduce the above
 // copyright notice, this list of conditions and the following disclaimer
 // in the documentation and/or other materials provided with the
 // distribution.
 //     * Neither the name of Google Inc. nor the names of its
 // contributors may be used to endorse or promote products derived from
 // this software without specific prior written permission.
 //
 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 package com.google.protobuf;
 
 
 import java.util.Map;

An implementation of Message that can represent arbitrary types, given a Descriptors.Descriptor.

Author(s):
kenton@google.com Kenton Varda
 
 public final class DynamicMessage extends AbstractMessage {
   private final Descriptor type;
   private final FieldSet<FieldDescriptorfields;
   private final FieldDescriptor[] oneofCases;
   private final UnknownFieldSet unknownFields;
   private int memoizedSize = -1;

  
Construct a DynamicMessage using the given FieldSet. oneofCases stores the FieldDescriptor for each oneof to indicate which field is set. Caller should make sure the array is immutable. This contructor is package private and will be used in DynamicMutableMessage to convert a mutable message to an immutable message.
 
                  FieldDescriptor[] oneofCases,
                  UnknownFieldSet unknownFields) {
     this. = type;
     this. = fields;
     this. = oneofCases;
     this. = unknownFields;
   }

  
Get a DynamicMessage representing the default instance of the given type.
 
   public static DynamicMessage getDefaultInstance(Descriptor type) {
     int oneofDeclCount = type.toProto().getOneofDeclCount();
     FieldDescriptor[] oneofCases = new FieldDescriptor[oneofDeclCount];
     return new DynamicMessage(type, FieldSet.<FieldDescriptor>emptySet(),
                               oneofCases,
                               UnknownFieldSet.getDefaultInstance());
   }


  
Parse a message of the given type from the given input stream.
 
   public static DynamicMessage parseFrom(Descriptor type,
                                          CodedInputStream input)
                                          throws IOException {
     return newBuilder(type).mergeFrom(input).buildParsed();
   }

  
Parse a message of the given type from the given input stream.
 
   public static DynamicMessage parseFrom(
       Descriptor type,
       CodedInputStream input,
       ExtensionRegistry extensionRegistry)
       throws IOException {
    return newBuilder(type).mergeFrom(inputextensionRegistry).buildParsed();
  }

  
Parse data as a message of the given type and return it.
  public static DynamicMessage parseFrom(Descriptor typeByteString data)
                                         throws InvalidProtocolBufferException {
    return newBuilder(type).mergeFrom(data).buildParsed();
  }

  
Parse data as a message of the given type and return it.
  public static DynamicMessage parseFrom(Descriptor typeByteString data,
                                         ExtensionRegistry extensionRegistry)
                                         throws InvalidProtocolBufferException {
    return newBuilder(type).mergeFrom(dataextensionRegistry).buildParsed();
  }

  
Parse data as a message of the given type and return it.
  public static DynamicMessage parseFrom(Descriptor typebyte[] data)
                                         throws InvalidProtocolBufferException {
    return newBuilder(type).mergeFrom(data).buildParsed();
  }

  
Parse data as a message of the given type and return it.
  public static DynamicMessage parseFrom(Descriptor typebyte[] data,
                                         ExtensionRegistry extensionRegistry)
                                         throws InvalidProtocolBufferException {
    return newBuilder(type).mergeFrom(dataextensionRegistry).buildParsed();
  }

  
Parse a message of the given type from input and return it.
  public static DynamicMessage parseFrom(Descriptor typeInputStream input)
                                         throws IOException {
    return newBuilder(type).mergeFrom(input).buildParsed();
  }

  
Parse a message of the given type from input and return it.
  public static DynamicMessage parseFrom(Descriptor typeInputStream input,
                                         ExtensionRegistry extensionRegistry)
                                         throws IOException {
    return newBuilder(type).mergeFrom(inputextensionRegistry).buildParsed();
  }

  
Construct a Message.Builder for the given type.
  public static Builder newBuilder(Descriptor type) {
    return new Builder(type);
  }

  
Construct a Message.Builder for a message of the same type as prototype, and initialize it with prototype's contents.
  public static Builder newBuilder(Message prototype) {
    return new Builder(prototype.getDescriptorForType()).mergeFrom(prototype);
  }
  // -----------------------------------------------------------------
  // Implementation of Message interface.
    return ;
  }
    return getDefaultInstance();
  }
    return .getAllFields();
  }
  public boolean hasOneof(OneofDescriptor oneof) {
    FieldDescriptor field = [oneof.getIndex()];
    if (field == null) {
      return false;
    }
    return true;
  }
    return [oneof.getIndex()];
  }
  public boolean hasField(FieldDescriptor field) {
    verifyContainingType(field);
    return .hasField(field);
  }
  public Object getField(FieldDescriptor field) {
    verifyContainingType(field);
    Object result = .getField(field);
    if (result == null) {
      if (field.isRepeated()) {
        result = Collections.emptyList();
      } else if (field.getJavaType() == ..) {
        result = getDefaultInstance(field.getMessageType());
      } else {
        result = field.getDefaultValue();
      }
    }
    return result;
  }
  public int getRepeatedFieldCount(FieldDescriptor field) {
    verifyContainingType(field);
    return .getRepeatedFieldCount(field);
  }
  public Object getRepeatedField(FieldDescriptor fieldint index) {
    verifyContainingType(field);
    return .getRepeatedField(fieldindex);
  }
    return ;
  }
  static boolean isInitialized(Descriptor type,
                               FieldSet<FieldDescriptorfields) {
    // Check that all required fields are present.
    for (final FieldDescriptor field : type.getFields()) {
      if (field.isRequired()) {
        if (!fields.hasField(field)) {
          return false;
        }
      }
    }
    // Check that embedded messages are initialized.
    return fields.isInitialized();
  }
  public boolean isInitialized() {
    return isInitialized();
  }
  public void writeTo(CodedOutputStream outputthrows IOException {
      .writeMessageSetTo(output);
    } else {
      .writeTo(output);
      .writeTo(output);
    }
  }
  public int getSerializedSize() {
    int size = ;
    if (size != -1) return size;
      size = .getMessageSetSerializedSize();
    } else {
      size = .getSerializedSize();
      size += .getSerializedSize();
    }
     = size;
    return size;
  }
  public Builder newBuilderForType() {
    return new Builder();
  }
  public Builder toBuilder() {
    return newBuilderForType().mergeFrom(this);
  }
    return new AbstractParser<DynamicMessage>() {
      public DynamicMessage parsePartialFrom(
          CodedInputStream input,
          ExtensionRegistryLite extensionRegistry)
          throws InvalidProtocolBufferException {
        Builder builder = newBuilder();
        try {
          builder.mergeFrom(inputextensionRegistry);
        } catch (InvalidProtocolBufferException e) {
          throw e.setUnfinishedMessage(builder.buildPartial());
        } catch (IOException e) {
          throw new InvalidProtocolBufferException(e.getMessage())
              .setUnfinishedMessage(builder.buildPartial());
        }
        return builder.buildPartial();
      }
    };
  }

  
Verifies that the field is a field of this message.
  private void verifyContainingType(FieldDescriptor field) {
    if (field.getContainingType() != ) {
      throw new IllegalArgumentException(
        "FieldDescriptor does not match message type.");
    }
  }

  
Verifies that the oneof is an oneof of this message.
  private void verifyOneofContainingType(OneofDescriptor oneof) {
    if (oneof.getContainingType() != ) {
      throw new IllegalArgumentException(
        "OneofDescriptor does not match message type.");
    }
  }
  // =================================================================

  
Builder for DynamicMessages.
  public static final class Builder extends AbstractMessage.Builder<Builder> {
    private final Descriptor type;
    private FieldSet<FieldDescriptorfields;
    private final FieldDescriptor[] oneofCases;
    private UnknownFieldSet unknownFields;

    
Construct a Builder for the given type.
    private Builder(Descriptor type) {
      this. = type;
      this. = FieldSet.newFieldSet();
      this. = UnknownFieldSet.getDefaultInstance();
      this. = new FieldDescriptor[type.toProto().getOneofDeclCount()];
    }
    // ---------------------------------------------------------------
    // Implementation of Message.Builder interface.
    @Override
    public Builder clear() {
      if (.isImmutable()) {
         = FieldSet.newFieldSet();
      } else {
        .clear();
      }
       = UnknownFieldSet.getDefaultInstance();
      return this;
    }
    @Override
    public Builder mergeFrom(Message other) {
      if (other instanceof DynamicMessage) {
        // This should be somewhat faster than calling super.mergeFrom().
        DynamicMessage otherDynamicMessage = (DynamicMessageother;
        if (otherDynamicMessage.type != ) {
          throw new IllegalArgumentException(
            "mergeFrom(Message) can only merge messages of the same type.");
        }
        ensureIsMutable();
        .mergeFrom(otherDynamicMessage.fields);
        mergeUnknownFields(otherDynamicMessage.unknownFields);
        for (int i = 0; i < .i++) {
          if ([i] == null) {
            [i] = otherDynamicMessage.oneofCases[i];
          } else {
            if ((otherDynamicMessage.oneofCases[i] != null)
                && ([i] != otherDynamicMessage.oneofCases[i])) {
              .clearField([i]);
              [i] = otherDynamicMessage.oneofCases[i];
            }
          }
        }
        return this;
      } else {
        return super.mergeFrom(other);
      }
    }
    public DynamicMessage build() {
      if (!isInitialized()) {
        throw newUninitializedMessageException(
          new DynamicMessage(,
              java.util.Arrays.copyOf(.), ));
      }
      return buildPartial();
    }

    
Helper for DynamicMessage.parseFrom() methods to call. Throws InvalidProtocolBufferException instead of UninitializedMessageException.
      if (!isInitialized()) {
        throw newUninitializedMessageException(
          new DynamicMessage(,
              java.util.Arrays.copyOf(.), ))
          .asInvalidProtocolBufferException();
      }
      return buildPartial();
    }
    public DynamicMessage buildPartial() {
      .makeImmutable();
      DynamicMessage result =
        new DynamicMessage(,
            java.util.Arrays.copyOf(.), );
      return result;
    }
    @Override
    public Builder clone() {
      Builder result = new Builder();
      result.fields.mergeFrom();
      System.arraycopy(, 0, result.oneofCases, 0 , .);
      return result;
    }
    public boolean isInitialized() {
      return DynamicMessage.isInitialized();
    }
    public Descriptor getDescriptorForType() {
      return ;
    }
      return getDefaultInstance();
    }
    public Map<FieldDescriptorObjectgetAllFields() {
      return .getAllFields();
    }
    public Builder newBuilderForField(FieldDescriptor field) {
      verifyContainingType(field);
      if (field.getJavaType() != ..) {
        throw new IllegalArgumentException(
          "newBuilderForField is only valid for fields with message type.");
      }
      return new Builder(field.getMessageType());
    }
    public boolean hasOneof(OneofDescriptor oneof) {
      verifyOneofContainingType(oneof);
      FieldDescriptor field = [oneof.getIndex()];
      if (field == null) {
        return false;
      }
      return true;
    }
      verifyOneofContainingType(oneof);
      return [oneof.getIndex()];
    }
    public Builder clearOneof(OneofDescriptor oneof) {
      verifyOneofContainingType(oneof);
      FieldDescriptor field = [oneof.getIndex()];
      if (field != null) {
        clearField(field);
      }
      return this;
    }
    public boolean hasField(FieldDescriptor field) {
      verifyContainingType(field);
      return .hasField(field);
    }
    public Object getField(FieldDescriptor field) {
      verifyContainingType(field);
      Object result = .getField(field);
      if (result == null) {
        if (field.isRepeated()) {
          result = Collections.emptyList();
        } else if (field.getJavaType() == ..) {
          result = getDefaultInstance(field.getMessageType());
        } else {
          result = field.getDefaultValue();
        }
      }
      return result;
    }
    public Builder setField(FieldDescriptor fieldObject value) {
      verifyContainingType(field);
      ensureIsMutable();
      if (field.getType() == ..) {
        verifyEnumType(fieldvalue);
      }
      OneofDescriptor oneofDescriptor = field.getContainingOneof();
      if (oneofDescriptor != null) {
        int index = oneofDescriptor.getIndex();
        FieldDescriptor oldField = [index];
        if ((oldField != null) && (oldField != field)) {
          .clearField(oldField);
        }
        [index] = field;
      }
      .setField(fieldvalue);
      return this;
    }
    public Builder clearField(FieldDescriptor field) {
      verifyContainingType(field);
      ensureIsMutable();
      OneofDescriptor oneofDescriptor = field.getContainingOneof();
      if (oneofDescriptor != null) {
        int index = oneofDescriptor.getIndex();
        if ([index] == field) {
          [index] = null;
        }
      }
      .clearField(field);
      return this;
    }
    public int getRepeatedFieldCount(FieldDescriptor field) {
      verifyContainingType(field);
      return .getRepeatedFieldCount(field);
    }
    public Object getRepeatedField(FieldDescriptor fieldint index) {
      verifyContainingType(field);
      return .getRepeatedField(fieldindex);
    }
                                    int indexObject value) {
      verifyContainingType(field);
      ensureIsMutable();
      .setRepeatedField(fieldindexvalue);
      return this;
    }
    public Builder addRepeatedField(FieldDescriptor fieldObject value) {
      verifyContainingType(field);
      ensureIsMutable();
      .addRepeatedField(fieldvalue);
      return this;
    }
    public UnknownFieldSet getUnknownFields() {
      return ;
    }
    public Builder setUnknownFields(UnknownFieldSet unknownFields) {
      this. = unknownFields;
      return this;
    }
    @Override
    public Builder mergeUnknownFields(UnknownFieldSet unknownFields) {
      this. =
        UnknownFieldSet.newBuilder(this.)
                       .mergeFrom(unknownFields)
                       .build();
      return this;
    }

    
Verifies that the field is a field of this message.
    private void verifyContainingType(FieldDescriptor field) {
      if (field.getContainingType() != ) {
        throw new IllegalArgumentException(
          "FieldDescriptor does not match message type.");
      }
    }

    
Verifies that the oneof is an oneof of this message.
    private void verifyOneofContainingType(OneofDescriptor oneof) {
      if (oneof.getContainingType() != ) {
        throw new IllegalArgumentException(
          "OneofDescriptor does not match message type.");
      }
    }

    
Verifies that the value is EnumValueDescriptor and matchs Enum Type.
    private void verifyEnumType(FieldDescriptor fieldObject value) {
      if (value == null) {
        throw new NullPointerException();
      }
      if (!(value instanceof EnumValueDescriptor)) {
        throw new IllegalArgumentException(
          "DynamicMessage should use EnumValueDescriptor to set Enum Value.");
      }
      if (field.getEnumType() != ((EnumValueDescriptorvalue).getType()) {
        throw new IllegalArgumentException(
          "EnumValueDescriptor doesn't much Enum Field.");
      }
    }
    private void ensureIsMutable() {
      if (.isImmutable()) {
         = .clone();
      }
    }
    @Override
      // TODO(xiangl): need implementation for dynamic message
      throw new UnsupportedOperationException(
        "getFieldBuilder() called on a dynamic message type.");
    }
  }
New to GrepCode? Check out our FAQ X