use of com.google.protobuf.Message.Builder in project grpc-java by grpc.
the class ProtoUtils method jsonMarshaller.
/**
* Create a {@code Marshaller} for json protos of the same type as {@code defaultInstance}.
*
* <p>This is an unstable API and has not been optimized yet for performance.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1786")
public static <T extends Message> Marshaller<T> jsonMarshaller(final T defaultInstance, final Parser parser, final Printer printer) {
final Charset charset = Charset.forName("UTF-8");
return new Marshaller<T>() {
@Override
public InputStream stream(T value) {
try {
return new ByteArrayInputStream(printer.print(value).getBytes(charset));
} catch (InvalidProtocolBufferException e) {
throw Status.INTERNAL.withCause(e).withDescription("Unable to print json proto").asRuntimeException();
}
}
@SuppressWarnings("unchecked")
@Override
public T parse(InputStream stream) {
Builder builder = defaultInstance.newBuilderForType();
Reader reader = new InputStreamReader(stream, charset);
T proto;
try {
parser.merge(reader, builder);
proto = (T) builder.build();
reader.close();
} catch (InvalidProtocolBufferException e) {
throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence").withCause(e).asRuntimeException();
} catch (IOException e) {
// Same for now, might be unavailable
throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence").withCause(e).asRuntimeException();
}
return proto;
}
};
}
use of com.google.protobuf.Message.Builder in project camel by apache.
the class ProtobufDataFormat method unmarshal.
/*
* (non-Javadoc)
* @see org.apache.camel.spi.DataFormat#unmarshal(org.apache.camel.Exchange,
* java.io.InputStream)
*/
public Object unmarshal(final Exchange exchange, final InputStream inputStream) throws Exception {
ObjectHelper.notNull(defaultInstance, "defaultInstance or instanceClassName must be set", this);
Builder builder = defaultInstance.newBuilderForType().mergeFrom(inputStream);
if (!builder.isInitialized()) {
// TODO which exception should be thrown here?
throw new InvalidPayloadException(exchange, defaultInstance.getClass());
}
return builder.build();
}
Aggregations