Java Code Examples for com.google.protobuf.Parser#parseFrom()

The following examples show how to use com.google.protobuf.Parser#parseFrom() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MessagePayloadSerializerPb.java    From stateful-functions with Apache License 2.0 8 votes vote down vote up
@Override
public Object copy(@Nonnull ClassLoader targetClassLoader, @Nonnull Object what) {
  Objects.requireNonNull(targetClassLoader);
  if (!(what instanceof Message)) {
    throw new IllegalStateException();
  }
  Message message = (Message) what;
  ByteString messageBytes = message.toByteString();
  try {
    Parser<? extends Message> parser =
        parserForClassName(targetClassLoader, what.getClass().getName());
    return parser.parseFrom(messageBytes);
  } catch (InvalidProtocolBufferException | ClassNotFoundException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 2
Source File: MessagePayloadSerializerPb.java    From flink-statefun with Apache License 2.0 6 votes vote down vote up
@Override
public Object copy(@Nonnull ClassLoader targetClassLoader, @Nonnull Object what) {
  Objects.requireNonNull(targetClassLoader);
  if (!(what instanceof Message)) {
    throw new IllegalStateException();
  }
  Message message = (Message) what;
  ByteString messageBytes = message.toByteString();
  try {
    Parser<? extends Message> parser =
        parserForClassName(targetClassLoader, what.getClass().getName());
    return parser.parseFrom(messageBytes);
  } catch (InvalidProtocolBufferException | ClassNotFoundException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 3
Source File: ProtoDecoder.java    From xrpc with Apache License 2.0 6 votes vote down vote up
/**
 * Decode a ByteBuf body from protobuf format to an object of designated Class type.
 *
 * @param body current http request
 * @param clazz target class for decoding
 * @return object of type clazz
 */
@Override
@SuppressWarnings("unchecked")
public <T> T decode(ByteBuf body, CharSequence contentType, Class<T> clazz) throws IOException {
  // TODO (AD): given a Content-Type of application/protobuf; proto=org.some.Message,
  // we currently ignore the 2nd part, but should at least validate it in the future.

  if (!MessageLite.class.isAssignableFrom(clazz)) {
    throw new IllegalArgumentException(
        String.format("%s does not extend from MessageLite", clazz.getName()));
  }

  MessageLite message = protoDefaultInstances.get(clazz);
  Parser<?> parser = message.getParserForType();
  try (ByteBufInputStream stream = new ByteBufInputStream(body)) {
    return (T) parser.parseFrom(stream);
  }
}
 
Example 4
Source File: IntentProtocolBufferExtractor.java    From OpenYOLO-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to extract a protocol buffer from the specified extra.
 * @throws MalformedDataException if the intent is null, the extra is missing or not a byte
 *     array, or the protocol buffer could not be parsed.
 */
@NonNull
public static <T extends MessageLite> T extract(
        @NonNull String extraName,
        @NonNull Parser<T> protoParser,
        @NonNull String failureDescription,
        @Nullable Intent intent)
        throws MalformedDataException {

    if (intent == null) {
        throw new MalformedDataException(failureDescription);
    }

    byte[] protoBytes = intent.getByteArrayExtra(extraName);
    if (protoBytes == null) {
        throw new MalformedDataException(failureDescription);
    }

    try {
        return protoParser.parseFrom(protoBytes);
    } catch (IOException ex) {
        throw new MalformedDataException(failureDescription, ex);
    }
}
 
Example 5
Source File: PartitionProcessor.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
private Message<? extends com.google.protobuf.Message> parseMessage() {
    Envelope envelope = null;

    try {
        envelope = Envelope.parseFrom(record.value());
    } catch (InvalidProtocolBufferException parseError) {
        markAsConsumed(record.offset());
        parsingFailed(envelope, parseError);
        return null;
    }

    try {
        MessageType type = new MessageType(envelope.getMessageType());

        Parser<com.google.protobuf.Message> parser = typeDictionary.parserFor(type);
        if (parser == null) {
            throw new UnknownMessageTypeException(type);
        }

        com.google.protobuf.Message innerMessage = parser.parseFrom(envelope.getInnerMessage());
        return Messages.fromKafka(innerMessage, envelope, record);
    } catch (InvalidProtocolBufferException | UnknownMessageTypeException unrecoverableParsingError) {
        markAsConsumed(record.offset());
        parsingFailed(envelope, unrecoverableParsingError);
        return null;
    }
}
 
Example 6
Source File: DescriptorGenerator.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private <T> T parseAny(Any value, Parser<T> parser) {
  try {
    return parser.parseFrom(value.getValue());
  } catch (InvalidProtocolBufferException e) {
    throw new RuntimeException(e);
  }
}
 
Example 7
Source File: RpcBus.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static <T> T get(ByteString pBody, Parser<T> parser) throws RpcException {
  try {
    return parser.parseFrom(pBody);
  } catch (InvalidProtocolBufferException e) {
    throw new RpcException(String.format("Failure while decoding message with parser of type. %s", parser.getClass().getCanonicalName()), e);
  }
}
 
Example 8
Source File: RpcBus.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static <T> T get(byte[] pBody, Parser<T> parser) throws RpcException {
  try {
    return parser.parseFrom(pBody);
  } catch (InvalidProtocolBufferException e) {
    throw new RpcException(String.format("Failure while decoding message with parser of type. %s", parser.getClass().getCanonicalName()), e);
  }
}
 
Example 9
Source File: RpcBus.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static <T> T get(ByteBuf pBody, Parser<T> parser) throws RpcException {
  try {
    ByteBufInputStream is = new ByteBufInputStream(pBody);
    return parser.parseFrom(is);
  } catch (InvalidProtocolBufferException e) {
    throw new RpcException(String.format("Failure while decoding message with parser of type. %s", parser.getClass().getCanonicalName()), e);
  }
}
 
Example 10
Source File: OutOfBandMessage.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public <T> T getPayload(Parser<T> parser) {
  try {
    T obj = parser.parseFrom(payload.bytes);
    if(!obj.getClass().getName().equals(payload.type)) {
      throw new IllegalArgumentException();
    }
    return obj;
  } catch (InvalidProtocolBufferException e) {
    throw new RuntimeException(e);
  }
}
 
Example 11
Source File: UserRPCServer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private <M extends Message> M parse(byte[] body, Parser<M> parser, Class<M> type) throws RpcException {

      try {
        return parser.parseFrom(body);
      } catch (InvalidProtocolBufferException e) {
        throw  new RpcException(String.format("Failure while decoding %s body.", type.getSimpleName()), e);
      }
    }
 
Example 12
Source File: NoticeFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends GeneratedMessage> T parseNotice(ByteString payload, Class<T> noticeClass) {
    try {
        Parser<T> parser = (Parser<T>) MessageConstants.MESSAGE_CLASS_TO_PARSER.get(noticeClass);
        return parser.parseFrom(payload);
    } catch (InvalidProtocolBufferException ex) {
        throw new CJCommunicationsException(ex);
    }
}
 
Example 13
Source File: RpcBus.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static <T> T get(ByteBuf pBody, Parser<T> parser) throws RpcException {
  try {
    ByteBufInputStream is = new ByteBufInputStream(pBody);
    return parser.parseFrom(is);
  } catch (InvalidProtocolBufferException e) {
    throw new RpcException(
        String.format("Failure while decoding message with parser of type. %s",
            parser.getClass().getCanonicalName()), e);
  }
}
 
Example 14
Source File: PolyglotUtil.java    From flink-statefun with Apache License 2.0 5 votes vote down vote up
public static <M extends Message> M parseProtobufOrThrow(Parser<M> parser, InputStream input) {
  try {
    return parser.parseFrom(input);
  } catch (IOException e) {
    throw new IllegalStateException("Unable to parse a Protobuf message", e);
  }
}
 
Example 15
Source File: MessagePayloadSerializerPb.java    From flink-statefun with Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(@Nonnull ClassLoader targetClassLoader, @Nonnull Payload payload) {
  try {
    Parser<? extends Message> parser =
        parserForClassName(targetClassLoader, payload.getClassName());
    return parser.parseFrom(payload.getPayloadBytes());
  } catch (InvalidProtocolBufferException | ClassNotFoundException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 16
Source File: MessagePayloadSerializerPb.java    From stateful-functions with Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(@Nonnull ClassLoader targetClassLoader, @Nonnull Payload payload) {
  try {
    Parser<? extends Message> parser =
        parserForClassName(targetClassLoader, payload.getClassName());
    return parser.parseFrom(payload.getPayloadBytes());
  } catch (InvalidProtocolBufferException | ClassNotFoundException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 17
Source File: ProtoBufSerializePerformanceTest.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
private static void codecTest(Message msg, int loopTimes, Map<Class<?>, Parser<? extends Message>> parserMap) throws IOException {
    final long start = System.currentTimeMillis();
    for (int index = 0; index < loopTimes; index++) {
        // 这里需要简单模拟下解码过程
        final CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(buffer);
        writeTypeId(msg, codedOutputStream);
        msg.writeTo(codedOutputStream);

        final CodedInputStream inputStream = CodedInputStream.newInstance(buffer, 0, codedOutputStream.getTotalBytesWritten());
        final Class<?> messageClass = readType(inputStream);
        final Parser<?> parser = parserMap.get(messageClass);
        final Object decodeMsg = parser.parseFrom(inputStream);
    }
    System.out.println("codec " + loopTimes + " times cost timeMs " + (System.currentTimeMillis() - start));
}
 
Example 18
Source File: ProtoBufSerializePerformanceTest.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
private static void equalsTest(p_test.p_testMsg msg) throws IOException {
    final Parser<p_test.p_testMsg> parser = msg.getParserForType();

    final CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(buffer);
    writeTypeId(msg, codedOutputStream);
    msg.writeTo(codedOutputStream);
    System.out.println("encode result bytes = " + codedOutputStream.getTotalBytesWritten());

    final CodedInputStream inputStream = CodedInputStream.newInstance(buffer, 0, codedOutputStream.getTotalBytesWritten());
    final Class<?> type = readType(inputStream);
    final Object decodeMsg = parser.parseFrom(inputStream);
    System.out.println("codec equals result = " + msg.equals(decodeMsg));
}
 
Example 19
Source File: CodedDataInputStream.java    From fastjgame with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T readMessage(@Nonnull Parser<T> parser) throws IOException {
    return parser.parseFrom(codedInputStream, ExtensionRegistryLite.getEmptyRegistry());
}
 
Example 20
Source File: AsyncMessageReader.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Parse a message.
 * 
 * @param messageClass
 *            class extending {@link GeneratedMessage}
 * @param buf
 *            message buffer
 * @return {@link GeneratedMessage}
 */
private GeneratedMessage parseMessage(Class<? extends GeneratedMessage> messageClass, ByteBuffer buf) {
    try {
        Parser<? extends GeneratedMessage> parser = MessageConstants.MESSAGE_CLASS_TO_PARSER.get(messageClass);
        return parser.parseFrom(CodedInputStream.newInstance(buf));
    } catch (InvalidProtocolBufferException ex) {
        throw AssertionFailedException.shouldNotHappen(ex);
    }
}