本文整理匯總了Java中com.google.protobuf.Message.Builder.build方法的典型用法代碼示例。如果您正苦於以下問題:Java Builder.build方法的具體用法?Java Builder.build怎麽用?Java Builder.build使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.google.protobuf.Message.Builder
的用法示例。
在下文中一共展示了Builder.build方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: buildMessage
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
private static Object buildMessage(Builder builder, Map<String, Object> fields) {
Descriptor descriptor = builder.getDescriptorForType();
for (Map.Entry<String, Object> entry : fields.entrySet()) {
if (entry.getValue() == null) {
continue;
}
FieldDescriptor field = getField(descriptor, entry.getKey());
if (entry.getValue() instanceof List<?>) {
List<Object> values = (List<Object>) entry.getValue();
for (Object value : values) {
builder.addRepeatedField(field, buildValue(builder, field, value));
}
} else {
builder.setField(field, buildValue(builder, field, entry.getValue()));
}
}
return builder.build();
}
示例2: convertJsonToProto
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
public <T extends Message> T convertJsonToProto(T prototype, String json, String extensionName) {
try {
Builder builder = prototype.newBuilderForType();
JsonFormat.parser().merge(json, builder);
return (T) builder.build();
} catch (InvalidProtocolBufferException ex) {
diagCollector.addDiag(
Diag.error(
new SimpleLocation(extensionName),
"Extension %s cannot be converted into proto type %s. Details: %s",
extensionName,
prototype.getDescriptorForType().getFullName(),
ex.getMessage()));
return prototype;
}
}
示例3: decode
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
throws Exception {
ByteBufInputStream in = new ByteBufInputStream(msg);
RequestHeader.Builder hbuilder = RequestHeader.newBuilder();
hbuilder.mergeDelimitedFrom(in);
RequestHeader header = hbuilder.build();
BlockingService service = RaftRpcService.create().getService();
MethodDescriptor md = service.getDescriptorForType().findMethodByName(header.getRequestName());
Builder builder = service.getRequestPrototype(md).newBuilderForType();
Message body = null;
if (builder != null) {
if(builder.mergeDelimitedFrom(in)) {
body = builder.build();
} else {
LOG.error("Parsing packet failed!");
}
}
RpcCall call = new RpcCall(header.getId(), header, body, md);
out.add(call);
}
示例4: decode
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
throws Exception {
ByteBufInputStream in = new ByteBufInputStream(msg);
ResponseHeader.Builder hbuilder = ResponseHeader.newBuilder();
hbuilder.mergeDelimitedFrom(in);
ResponseHeader header = hbuilder.build();
BlockingService service = RaftRpcService.create().getService();
MethodDescriptor md = service.getDescriptorForType().findMethodByName(header.getResponseName());
Builder builder = service.getResponsePrototype(md).newBuilderForType();
Message body = null;
if (builder != null) {
if(builder.mergeDelimitedFrom(in)) {
body = builder.build();
} else {
LOG.error("Parse packet failed!!");
}
}
RpcCall call = new RpcCall(header.getId(), header, body, md);
out.add(call);
}
示例5: generate
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
/**
* Generates a random protocol buffer, filling in all required fields but
* with a p chance of not setting an optional field and p chance of having
* an empty repeated field.
*/
@SuppressWarnings("unchecked")
public E generate(double p) {
Builder builder = instance.newBuilderForType();
Descriptor descriptor = instance.getDescriptorForType();
for (FieldDescriptor field : descriptor.getFields()) {
if (!field.isRequired() && random.nextDouble() < p) {
continue;
}
builder.setField(field, getRandomValue(field, p));
}
return (E) builder.build();
}
示例6: buildKey
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
public T buildKey(T data) {
Builder b = data.newBuilderForType();
for (FieldDescriptor field : fields) {
if (!data.hasField(field)) {
if (requireFields) {
throw new IllegalStateException("Field not set: " + field.getFullName());
} else {
continue;
}
}
Object value = data.getField(field);
b.setField(field, value);
}
return (T) b.build();
}
示例7: decodeProtobufFromStream
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
/**
* Decode the a protobuf from the given input stream
* @param builder - Builder of the protobuf to decode
* @param dis - DataInputStream to read the protobuf
* @return Message - decoded protobuf
* @throws WrappedRpcServerException - deserialization failed
*/
@SuppressWarnings("unchecked")
private <T extends Message> T decodeProtobufFromStream(Builder builder,
DataInputStream dis) throws WrappedRpcServerException {
try {
builder.mergeDelimitedFrom(dis);
return (T)builder.build();
} catch (Exception ioe) {
Class<?> protoClass = builder.getDefaultInstanceForType().getClass();
throw new WrappedRpcServerException(
RpcErrorCodeProto.FATAL_DESERIALIZING_REQUEST,
"Error decoding " + protoClass.getSimpleName() + ": "+ ioe);
}
}
示例8: unmarshal
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
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();
}
示例9: parse
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
@Override
@SuppressWarnings("unchecked")
public <T extends Message> T parse(T template) throws Exception {
Builder builder = template.newBuilderForType();
JsonFormat.merge(json, builder);
return (T) builder.build();
}
示例10: decode
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
throws Exception {
//System.out.println("size:" + msg.capacity());
long t = System.currentTimeMillis();
// System.out.println("ispooled:" + msg.)
ByteBufInputStream in = new ByteBufInputStream(msg);
RequestHeader.Builder hbuilder = RequestHeader.newBuilder();
hbuilder.mergeDelimitedFrom(in);
RequestHeader header = hbuilder.build();
//System.out.println("header:" + header);
BlockingService service = RaftRpcService.create().getService();
MethodDescriptor md = service.getDescriptorForType().findMethodByName(header.getRequestName());
Builder builder = service.getRequestPrototype(md).newBuilderForType();
Message body = null;
if (builder != null) {
if(builder.mergeDelimitedFrom(in)) {
body = builder.build();
//System.out.println("body parsed");
} else {
//System.out.println("parse failed");
}
}
RpcCall call = new RpcCall(header.getId(), header, body, md);
// System.out.println("Parse Rpc request from socket: " + call.getCallId()
// + ", takes" + (System.currentTimeMillis() -t) + " ms");
out.add(call);
}
示例11: decode
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
@Override
public Object decode(ProtocolHandlerIoSession mySession) throws DecodeException {
ObjectProtocolCacheBean bean = (ObjectProtocolCacheBean) mySession.protocolAttachment;
if (bean.checkPos >= 0) {
readSize(bean);
if (bean.checkPos >= 0) {
return null;
}
}
if (bean.recieveSize >= bean.curPackageSize) {
// int index = getIndex(bean);
// if(map[index] == null){
// throw new DecodeException("The message is not registered to protocol! id:" + index);
// }
try {
Builder b = generatedMessage.newBuilderForType().mergeFrom(
new IoBufferArrayInputStream(bean.buff.toArray(new IoBuffer[bean.buff.size()]), bean.curPackageSize));
bean.recieveSize -= bean.curPackageSize;
bean.curPackageSize = 0;
bean.checkPos = 0;
// remove and close IoBuffer that has been unuseful.
while (bean.buff.size() > 0 && !bean.buff.getFirst().getByteBuffer().hasRemaining()) {
bean.buff.removeFirst().close();
}
return b.build();
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("bean.recieveSize" + bean.recieveSize + " bean.curPackageSize:" + bean.curPackageSize);
}
throw new DecodeException(e);
}
}
return null;
}
示例12: readResponse
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
protected void readResponse() {
if (shouldCloseConnection.get()) return;
Call call = null;
boolean expectedCall = false;
try {
// See HBaseServer.Call.setResponse for where we write out the response.
// Total size of the response. Unused. But have to read it in anyways.
int totalSize = in.readInt();
// Read the header
ResponseHeader responseHeader = ResponseHeader.parseDelimitedFrom(in);
int id = responseHeader.getCallId();
call = calls.remove(id); // call.done have to be set before leaving this method
expectedCall = (call != null && !call.done);
if (!expectedCall) {
// So we got a response for which we have no corresponding 'call' here on the client-side.
// We probably timed out waiting, cleaned up all references, and now the server decides
// to return a response. There is nothing we can do w/ the response at this stage. Clean
// out the wire of the response so its out of the way and we can get other responses on
// this connection.
int readSoFar = IPCUtil.getTotalSizeWhenWrittenDelimited(responseHeader);
int whatIsLeftToRead = totalSize - readSoFar;
IOUtils.skipFully(in, whatIsLeftToRead);
if (call != null) {
call.callStats.setResponseSizeBytes(totalSize);
call.callStats.setCallTimeMs(
EnvironmentEdgeManager.currentTime() - call.callStats.getStartTime());
}
return;
}
if (responseHeader.hasException()) {
ExceptionResponse exceptionResponse = responseHeader.getException();
RemoteException re = createRemoteException(exceptionResponse);
call.setException(re);
call.callStats.setResponseSizeBytes(totalSize);
call.callStats.setCallTimeMs(
EnvironmentEdgeManager.currentTime() - call.callStats.getStartTime());
if (isFatalConnectionException(exceptionResponse)) {
markClosed(re);
}
} else {
Message value = null;
if (call.responseDefaultType != null) {
Builder builder = call.responseDefaultType.newBuilderForType();
ProtobufUtil.mergeDelimitedFrom(builder, in);
value = builder.build();
}
CellScanner cellBlockScanner = null;
if (responseHeader.hasCellBlockMeta()) {
int size = responseHeader.getCellBlockMeta().getLength();
byte [] cellBlock = new byte[size];
IOUtils.readFully(this.in, cellBlock, 0, cellBlock.length);
cellBlockScanner = ipcUtil.createCellScanner(this.codec, this.compressor, cellBlock);
}
call.setResponse(value, cellBlockScanner);
call.callStats.setResponseSizeBytes(totalSize);
call.callStats.setCallTimeMs(
EnvironmentEdgeManager.currentTime() - call.callStats.getStartTime());
}
} catch (IOException e) {
if (expectedCall) call.setException(e);
if (e instanceof SocketTimeoutException) {
// Clean up open calls but don't treat this as a fatal condition,
// since we expect certain responses to not make it by the specified
// {@link ConnectionId#rpcTimeout}.
if (LOG.isTraceEnabled()) LOG.trace("ignored", e);
} else {
// Treat this as a fatal condition and close this connection
markClosed(e);
}
} finally {
cleanupCalls(false);
}
}
示例13: readResponse
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
protected void readResponse() {
if (shouldCloseConnection.get()) return;
Call call = null;
boolean expectedCall = false;
try {
// See HBaseServer.Call.setResponse for where we write out the response.
// Total size of the response. Unused. But have to read it in anyways.
int totalSize = in.readInt();
// Read the header
ResponseHeader responseHeader = ResponseHeader.parseDelimitedFrom(in);
int id = responseHeader.getCallId();
call = calls.remove(id); // call.done have to be set before leaving this method
expectedCall = (call != null && !call.done);
if (!expectedCall) {
// So we got a response for which we have no corresponding 'call' here on the client-side.
// We probably timed out waiting, cleaned up all references, and now the server decides
// to return a response. There is nothing we can do w/ the response at this stage. Clean
// out the wire of the response so its out of the way and we can get other responses on
// this connection.
int readSoFar = IPCUtil.getTotalSizeWhenWrittenDelimited(responseHeader);
int whatIsLeftToRead = totalSize - readSoFar;
IOUtils.skipFully(in, whatIsLeftToRead);
return;
}
if (responseHeader.hasException()) {
ExceptionResponse exceptionResponse = responseHeader.getException();
RemoteException re = createRemoteException(exceptionResponse);
call.setException(re);
if (isFatalConnectionException(exceptionResponse)) {
markClosed(re);
}
} else {
Message value = null;
if (call.responseDefaultType != null) {
Builder builder = call.responseDefaultType.newBuilderForType();
builder.mergeDelimitedFrom(in);
value = builder.build();
}
CellScanner cellBlockScanner = null;
if (responseHeader.hasCellBlockMeta()) {
int size = responseHeader.getCellBlockMeta().getLength();
byte [] cellBlock = new byte[size];
IOUtils.readFully(this.in, cellBlock, 0, cellBlock.length);
cellBlockScanner = ipcUtil.createCellScanner(this.codec, this.compressor, cellBlock);
}
call.setResponse(value, cellBlockScanner);
}
} catch (IOException e) {
if (expectedCall) call.setException(e);
if (e instanceof SocketTimeoutException) {
// Clean up open calls but don't treat this as a fatal condition,
// since we expect certain responses to not make it by the specified
// {@link ConnectionId#rpcTimeout}.
if (LOG.isTraceEnabled()) LOG.trace("ignored", e);
} else {
// Treat this as a fatal condition and close this connection
markClosed(e);
}
} finally {
cleanupCalls(false);
}
}
示例14: readResponse
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
protected void readResponse() {
if (shouldCloseConnection.get()) return;
touch();
int totalSize = -1;
try {
// See HBaseServer.Call.setResponse for where we write out the response.
// Total size of the response. Unused. But have to read it in anyways.
totalSize = in.readInt();
// Read the header
ResponseHeader responseHeader = ResponseHeader.parseDelimitedFrom(in);
int id = responseHeader.getCallId();
if (LOG.isDebugEnabled()) {
LOG.debug(getName() + ": got response header " +
TextFormat.shortDebugString(responseHeader) + ", totalSize: " + totalSize + " bytes");
}
Call call = calls.get(id);
if (call == null) {
// So we got a response for which we have no corresponding 'call' here on the client-side.
// We probably timed out waiting, cleaned up all references, and now the server decides
// to return a response. There is nothing we can do w/ the response at this stage. Clean
// out the wire of the response so its out of the way and we can get other responses on
// this connection.
int readSoFar = IPCUtil.getTotalSizeWhenWrittenDelimited(responseHeader);
int whatIsLeftToRead = totalSize - readSoFar;
LOG.debug("Unknown callId: " + id + ", skipping over this response of " +
whatIsLeftToRead + " bytes");
IOUtils.skipFully(in, whatIsLeftToRead);
}
if (responseHeader.hasException()) {
ExceptionResponse exceptionResponse = responseHeader.getException();
RemoteException re = createRemoteException(exceptionResponse);
if (isFatalConnectionException(exceptionResponse)) {
markClosed(re);
} else {
if (call != null) call.setException(re);
}
} else {
Message value = null;
// Call may be null because it may have timedout and been cleaned up on this side already
if (call != null && call.responseDefaultType != null) {
Builder builder = call.responseDefaultType.newBuilderForType();
builder.mergeDelimitedFrom(in);
value = builder.build();
}
CellScanner cellBlockScanner = null;
if (responseHeader.hasCellBlockMeta()) {
int size = responseHeader.getCellBlockMeta().getLength();
byte [] cellBlock = new byte[size];
IOUtils.readFully(this.in, cellBlock, 0, cellBlock.length);
cellBlockScanner = ipcUtil.createCellScanner(this.codec, this.compressor, cellBlock);
}
// it's possible that this call may have been cleaned up due to a RPC
// timeout, so check if it still exists before setting the value.
if (call != null) call.setResponse(value, cellBlockScanner);
}
if (call != null) calls.remove(id);
} catch (IOException e) {
if (e instanceof SocketTimeoutException && remoteId.rpcTimeout > 0) {
// Clean up open calls but don't treat this as a fatal condition,
// since we expect certain responses to not make it by the specified
// {@link ConnectionId#rpcTimeout}.
closeException = e;
} else {
// Treat this as a fatal condition and close this connection
markClosed(e);
}
} finally {
if (remoteId.rpcTimeout > 0) {
cleanupCalls(remoteId.rpcTimeout);
}
}
}
示例15: readResponse
import com.google.protobuf.Message.Builder; //導入方法依賴的package包/類
protected void readResponse() {
if (shouldCloseConnection.get()) return;
Call call = null;
boolean expectedCall = false;
try {
// See HBaseServer.Call.setResponse for where we write out the response.
// Total size of the response. Unused. But have to read it in anyways.
int totalSize = in.readInt();
// Read the header
ResponseHeader responseHeader = ResponseHeader.parseDelimitedFrom(in);
int id = responseHeader.getCallId();
if (LOG.isDebugEnabled()) {
LOG.debug(getName() + ": got response header " +
TextFormat.shortDebugString(responseHeader) + ", totalSize: " + totalSize + " bytes");
}
call = calls.remove(id); // call.done have to be set before leaving this method
expectedCall = (call != null && !call.done);
if (!expectedCall) {
// So we got a response for which we have no corresponding 'call' here on the client-side.
// We probably timed out waiting, cleaned up all references, and now the server decides
// to return a response. There is nothing we can do w/ the response at this stage. Clean
// out the wire of the response so its out of the way and we can get other responses on
// this connection.
int readSoFar = IPCUtil.getTotalSizeWhenWrittenDelimited(responseHeader);
int whatIsLeftToRead = totalSize - readSoFar;
LOG.debug("Unknown callId: " + id + ", skipping over this response of " +
whatIsLeftToRead + " bytes");
IOUtils.skipFully(in, whatIsLeftToRead);
}
if (responseHeader.hasException()) {
ExceptionResponse exceptionResponse = responseHeader.getException();
RemoteException re = createRemoteException(exceptionResponse);
if (expectedCall) call.setException(re);
if (isFatalConnectionException(exceptionResponse)) {
markClosed(re);
}
} else {
Message value = null;
// Call may be null because it may have timeout and been cleaned up on this side already
if (expectedCall && call.responseDefaultType != null) {
Builder builder = call.responseDefaultType.newBuilderForType();
builder.mergeDelimitedFrom(in);
value = builder.build();
}
CellScanner cellBlockScanner = null;
if (responseHeader.hasCellBlockMeta()) {
int size = responseHeader.getCellBlockMeta().getLength();
byte [] cellBlock = new byte[size];
IOUtils.readFully(this.in, cellBlock, 0, cellBlock.length);
cellBlockScanner = ipcUtil.createCellScanner(this.codec, this.compressor, cellBlock);
}
// it's possible that this call may have been cleaned up due to a RPC
// timeout, so check if it still exists before setting the value.
if (expectedCall) call.setResponse(value, cellBlockScanner);
}
} catch (IOException e) {
if (expectedCall) call.setException(e);
if (e instanceof SocketTimeoutException) {
// Clean up open calls but don't treat this as a fatal condition,
// since we expect certain responses to not make it by the specified
// {@link ConnectionId#rpcTimeout}.
} else {
// Treat this as a fatal condition and close this connection
markClosed(e);
}
} finally {
cleanupCalls(false);
if (expectedCall && !call.done) {
LOG.warn("Coding error: code should be true for callId=" + call.id +
", server=" + getRemoteAddress() +
", shouldCloseConnection=" + shouldCloseConnection.get());
}
}
}