Ejemplo n.º 1
0
 /**
  * Creates a new Wire that can encode and decode the extensions specified in {@code
  * extensionClasses}. Typically the classes in this list are generated and start with the "Ext_"
  * prefix.
  */
 public Wire(List<Class<?>> extensionClasses) {
   this.registry = new ExtensionRegistry();
   for (Class<?> extensionClass : extensionClasses) {
     for (Field field : extensionClass.getDeclaredFields()) {
       if (field.getType().equals(Extension.class)) {
         try {
           Extension extension = (Extension) field.get(null);
           registry.add(extension);
         } catch (IllegalAccessException e) {
           throw new AssertionError(e);
         }
       }
     }
   }
 }
Ejemplo n.º 2
0
  public void testParseMessageSet() throws Exception {
    ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
    extensionRegistry.add(TestMessageSetExtension1.messageSetExtension);
    extensionRegistry.add(TestMessageSetExtension2.messageSetExtension);

    // Set up a RawMessageSet with two known messages and an unknown one.
    RawMessageSet raw =
        RawMessageSet.newBuilder()
            .addItem(
                RawMessageSet.Item.newBuilder()
                    .setTypeId(TYPE_ID_1)
                    .setMessage(
                        TestMessageSetExtension1.newBuilder().setI(123).build().toByteString())
                    .build())
            .addItem(
                RawMessageSet.Item.newBuilder()
                    .setTypeId(TYPE_ID_2)
                    .setMessage(
                        TestMessageSetExtension2.newBuilder().setStr("foo").build().toByteString())
                    .build())
            .addItem(
                RawMessageSet.Item.newBuilder()
                    .setTypeId(UNKNOWN_TYPE_ID)
                    .setMessage(ByteString.copyFromUtf8("bar"))
                    .build())
            .build();

    ByteString data = raw.toByteString();

    // Parse as a TestMessageSet and check the contents.
    TestMessageSet messageSet = TestMessageSet.parseFrom(data, extensionRegistry);

    assertEquals(123, messageSet.getExtension(TestMessageSetExtension1.messageSetExtension).getI());
    assertEquals(
        "foo", messageSet.getExtension(TestMessageSetExtension2.messageSetExtension).getStr());

    // Check for unknown field with type LENGTH_DELIMITED,
    //   number UNKNOWN_TYPE_ID, and contents "bar".
    UnknownFieldSet unknownFields = messageSet.getUnknownFields();
    assertEquals(1, unknownFields.asMap().size());
    assertTrue(unknownFields.hasField(UNKNOWN_TYPE_ID));

    UnknownFieldSet.Field field = unknownFields.getField(UNKNOWN_TYPE_ID);
    assertEquals(1, field.getLengthDelimitedList().size());
    assertEquals("bar", field.getLengthDelimitedList().get(0).toStringUtf8());
  }