com.google.protobuf.Parser#parseFrom ( )源码实例Demo

下面列出了com.google.protobuf.Parser#parseFrom ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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);
  }
}
 
@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);
  }
}
 
源代码3 项目: xrpc   文件: ProtoDecoder.java
/**
 * 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);
  }
}
 
/**
 * 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);
    }
}
 
源代码5 项目: Bats   文件: RpcBus.java
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);
  }
}
 
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));
}
 
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));
}
 
@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);
  }
}
 
@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);
  }
}
 
源代码10 项目: flink-statefun   文件: PolyglotUtil.java
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);
  }
}
 
源代码11 项目: ja-micro   文件: PartitionProcessor.java
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;
    }
}
 
源代码12 项目: lams   文件: NoticeFactory.java
@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);
    }
}
 
源代码13 项目: dremio-oss   文件: UserRPCServer.java
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);
      }
    }
 
源代码14 项目: dremio-oss   文件: OutOfBandMessage.java
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);
  }
}
 
源代码15 项目: dremio-oss   文件: RpcBus.java
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);
  }
}
 
源代码16 项目: dremio-oss   文件: RpcBus.java
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);
  }
}
 
源代码17 项目: dremio-oss   文件: RpcBus.java
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);
  }
}
 
源代码18 项目: api-compiler   文件: DescriptorGenerator.java
private <T> T parseAny(Any value, Parser<T> parser) {
  try {
    return parser.parseFrom(value.getValue());
  } catch (InvalidProtocolBufferException e) {
    throw new RuntimeException(e);
  }
}
 
源代码19 项目: fastjgame   文件: CodedDataInputStream.java
@Override
public <T> T readMessage(@Nonnull Parser<T> parser) throws IOException {
    return parser.parseFrom(codedInputStream, ExtensionRegistryLite.getEmptyRegistry());
}
 
源代码20 项目: lams   文件: AsyncMessageReader.java
/**
 * 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);
    }
}
 
 方法所在类
 同类方法