本文整理汇总了Java中com.google.protobuf.Message类的典型用法代码示例。如果您正苦于以下问题:Java Message类的具体用法?Java Message怎么用?Java Message使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Message类属于com.google.protobuf包,在下文中一共展示了Message类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: encode
import com.google.protobuf.Message; //导入依赖的package包/类
@Override
protected void encode(ChannelHandlerContext ctx, MessageOrBuilder in, List<Object> out)
throws Exception {
Message msg = in instanceof Message ? (Message) in : ((Message.Builder) in).build();
int typeId = register.getTypeId(msg.getClass());
if (typeId == Integer.MIN_VALUE) {
throw new IllegalArgumentException("Unrecognisable message type, maybe not registered! ");
}
byte[] messageData = msg.toByteArray();
if (messageData.length <= 0) {
out.add(ByteBufAllocator.DEFAULT.heapBuffer().writeInt(typeId)
.writeInt(0));
return;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream def = new GZIPOutputStream(bos);
def.write(messageData);
def.flush();
def.close();
byte[] compressedData = bos.toByteArray();
out.add(ByteBufAllocator.DEFAULT.heapBuffer().writeInt(typeId).writeInt(compressedData.length)
.writeBytes(compressedData));
}
示例2: decodeJson
import com.google.protobuf.Message; //导入依赖的package包/类
public static WsPacket decodeJson(String stringResult) {
try {
JSONObject jsObj = JSONObject.fromObject(stringResult);
String wsOpCode = jsObj.getString(WSOPCODE);
if (wsOpCode == null) {
if (WSManager.log != null) {
WSManager.log.warn("数据为:" + stringResult + ",无wsOpCode");
}
return null;
}
if (!WSManager.wsOpCodeMap.containsKey(wsOpCode)) {
if (WSManager.log != null) {
WSManager.log.warn("wsOpCode为:" + wsOpCode + "无对应解析,请及时解决");
}
return null;
}
Class<?> className = WSManager.wsOpCodeMap.get(wsOpCode);
Method buildM = className.getDeclaredMethod("newBuilder");
AbstractMessage.Builder<?> builder = (Builder<?>) buildM.invoke(null);
Message data = PacketUtils.jsonToProtoBuf(stringResult, builder);
WsPacket wsPacket = new WsPacket(wsOpCode, data);
return wsPacket;
} catch (Exception e) {
if (WSManager.log != null) {
WSManager.log.error("json转换成protobuf异常", e);
}
return null;
}
}
示例3: mergeMapField
import com.google.protobuf.Message; //导入依赖的package包/类
private void mergeMapField(FieldDescriptor field, JsonElement json, Message.Builder builder)
throws InvalidProtocolBufferException {
if (!(json instanceof JsonObject)) {
throw new InvalidProtocolBufferException("Expect a map object but found: " + json);
}
Descriptor type = field.getMessageType();
FieldDescriptor keyField = type.findFieldByName("key");
FieldDescriptor valueField = type.findFieldByName("value");
if (keyField == null || valueField == null) {
throw new InvalidProtocolBufferException("Invalid map field: " + field.getFullName());
}
JsonObject object = (JsonObject) json;
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
Message.Builder entryBuilder = builder.newBuilderForField(field);
Object key = parseFieldValue(keyField, new JsonPrimitive(entry.getKey()), entryBuilder);
Object value = parseFieldValue(valueField, entry.getValue(), entryBuilder);
if (value == null) {
throw new InvalidProtocolBufferException("Map value cannot be null.");
}
entryBuilder.setField(keyField, key);
entryBuilder.setField(valueField, value);
builder.addRepeatedField(field, entryBuilder.build());
}
}
示例4: prepareResponse
import com.google.protobuf.Message; //导入依赖的package包/类
protected List<ByteBuffer> prepareResponse(Object value, Status status, String errorClass,
String error) {
ByteBufferOutputStream buf = new ByteBufferOutputStream();
DataOutputStream out = new DataOutputStream(buf);
try {
RpcResponseHeader.Builder builder = RpcResponseHeader.newBuilder();
builder.setStatus(status);
builder.build().writeDelimitedTo(out);
if (error != null) {
RpcException.Builder b = RpcException.newBuilder();
b.setExceptionName(errorClass);
b.setStackTrace(error);
b.build().writeDelimitedTo(out);
} else {
if (value != null) {
((Message) value).writeDelimitedTo(out);
}
}
} catch (IOException e) {
LOG.warn("Exception while creating response " + e);
}
return buf.getBufferList();
}
示例5: buildValue
import com.google.protobuf.Message; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private static Object buildValue(
Message.Builder parentBuilder, FieldDescriptor field, Object value) {
if (field.getType() == FieldDescriptor.Type.MESSAGE) {
if (field.isRepeated()) {}
Message.Builder fieldBuilder = parentBuilder.newBuilderForField(field);
return buildMessage(fieldBuilder, (Map<String, Object>) value);
} else if (field.getType() == FieldDescriptor.Type.ENUM) {
return field.getEnumType().findValueByName((String) value);
} else {
switch (field.getType()) {
case FLOAT: // float is a special case
return Float.valueOf(value.toString());
default:
return value;
}
}
}
示例6: run
import com.google.protobuf.Message; //导入依赖的package包/类
@Override
public void run(Message response) {
if (eventLoopCallback == null) {
throw new IllegalStateException("response callback must only be called once");
}
RpcResponse.Builder responseMessage = RpcResponse.newBuilder();
responseMessage.setSequenceNumber(sequence);
assert controller.status != Protocol.Status.INVALID;
responseMessage.setStatus(controller.status);
if (response != null) {
responseMessage.setResponse(response.toByteString());
} else {
// No message: we must have failed
assert controller.status != Protocol.Status.OK;
}
if (controller.errorReason != null) {
assert controller.status != Protocol.Status.OK;
responseMessage.setErrorReason(controller.errorReason);
}
eventLoopCallback.writeResponse(responseMessage.build());
eventLoopCallback = null;
}
示例7: dispatchJsonRpcRequest
import com.google.protobuf.Message; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private JsonRpcResponse dispatchJsonRpcRequest(JsonRpcRequest rpcRequest, OrangeContext cxt) {
ServiceMethodHandler handler = handlers.getMethodHandler(rpcRequest.getMethod());
Message innerRequest = convertJsonToProtobuf(handler, rpcRequest);
JsonRpcResponse jsonResponse = new JsonRpcResponse(rpcRequest.getId(), JsonNull.INSTANCE,
JsonNull.INSTANCE, HttpServletResponse.SC_OK);
JsonElement idElement = rpcRequest.getId();
if (idElement == null) {
jsonResponse.setId(new JsonPrimitive(-1));
}
try {
Message innerResponse = invokeHandlerChain(rpcRequest.getMethod(), handler, innerRequest, cxt);
jsonResponse.setResult(ProtobufUtil.protobufToJson(innerResponse));
} catch (RpcCallException rpcEx) {
logger.debug("Error processing request", rpcEx);
jsonResponse.setError(rpcEx.toJson());
jsonResponse.setStatusCode(rpcEx.getCategory().getHttpStatus());
} catch (Exception ex) {
logger.warn("Error processing request", ex);
if (ex.getMessage() != null) {
jsonResponse.setError(new JsonPrimitive(ex.getMessage()));
}
jsonResponse.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
return jsonResponse;
}
示例8: callMethod
import com.google.protobuf.Message; //导入依赖的package包/类
@Override
@InterfaceAudience.Private
public void callMethod(Descriptors.MethodDescriptor method,
RpcController controller,
Message request, Message responsePrototype,
RpcCallback<Message> callback) {
Message response = null;
try {
response = callExecService(controller, method, request, responsePrototype);
} catch (IOException ioe) {
LOG.warn("Call failed on IOException", ioe);
ResponseConverter.setControllerException(controller, ioe);
}
if (callback != null) {
callback.run(response);
}
}
示例9: Call
import com.google.protobuf.Message; //导入依赖的package包/类
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NP_NULL_ON_SOME_PATH",
justification="Can't figure why this complaint is happening... see below")
Call(int id, final BlockingService service, final MethodDescriptor md, RequestHeader header,
Message param, CellScanner cellScanner, Connection connection, Responder responder,
long size, TraceInfo tinfo, final InetAddress remoteAddress) {
this.id = id;
this.service = service;
this.md = md;
this.header = header;
this.param = param;
this.cellScanner = cellScanner;
this.connection = connection;
this.timestamp = System.currentTimeMillis();
this.response = null;
this.responder = responder;
this.isError = false;
this.size = size;
this.tinfo = tinfo;
this.user = connection == null? null: connection.user; // FindBugs: NP_NULL_ON_SOME_PATH
this.remoteAddress = remoteAddress;
this.retryImmediatelySupported =
connection == null? null: connection.retryImmediatelySupported;
}
示例10: createProtoBuf
import com.google.protobuf.Message; //导入依赖的package包/类
Message createProtoBuf(
Descriptor descriptor, Message.Builder builder, Map<String, Object> input) {
if (input == null) {
return builder.build();
}
for (FieldDescriptor field : descriptor.getFields()) {
String fieldName = field.getName();
if (!input.containsKey(fieldName)) {
// TODO: validate required fields
continue;
}
if (field.isRepeated()) {
List<Object> values = (List<Object>) input.get(fieldName);
for (Object value : values) {
builder.addRepeatedField(field, getValueForField(field, value, builder));
}
} else {
builder.setField(field, getValueForField(field, input.get(fieldName), builder));
}
}
return builder.build();
}
示例11: createMethodDescriptor
import com.google.protobuf.Message; //导入依赖的package包/类
public static io.grpc.MethodDescriptor<Message, Message> createMethodDescriptor(Class<?> clzz,
Method method) {
String clzzName = clzz.getName();
String methodName = method.getName();
GrpcMethodType grpcMethodType = method.getAnnotation(GrpcMethodType.class);
Message argsReq = createDefaultInstance(grpcMethodType.requestType());
Message argsRep = createDefaultInstance(grpcMethodType.responseType());
return io.grpc.MethodDescriptor.<Message, Message>newBuilder()
.setType(grpcMethodType.methodType())//
.setFullMethodName(io.grpc.MethodDescriptor.generateFullMethodName(clzzName, methodName))//
.setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(argsReq))//
.setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller(argsRep))//
.setSafe(false)//
.setIdempotent(false)//
.build();
}
示例12: handleValue
import com.google.protobuf.Message; //导入依赖的package包/类
private void handleValue(Tokenizer tokenizer,
ExtensionRegistry extensionRegistry,
Message.Builder builder,
FieldDescriptor field,
ExtensionRegistry.ExtensionInfo extension,
boolean unknown) throws ParseException {
Object value = null;
if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
value = handleObject(tokenizer, extensionRegistry, builder, field, extension, unknown);
} else {
value = handlePrimitive(tokenizer, field);
}
if (value != null) {
if (field.isRepeated()) {
builder.addRepeatedField(field, value);
} else {
builder.setField(field, value);
}
}
}
示例13: merge
import com.google.protobuf.Message; //导入依赖的package包/类
private void merge(JsonElement json, Message.Builder builder)
throws InvalidProtocolBufferException {
if (typeParsers.containsKey(builder.getDescriptorForType().getFullName()))
{
typeParsers.get(builder.getDescriptorForType().getFullName()).merge(json, builder);
return;
}
WellKnownTypeParser specialParser =
wellKnownTypeParsers.get(builder.getDescriptorForType().getFullName());
if (specialParser != null) {
specialParser.merge(this, json, builder);
return;
}
mergeMessage(json, builder, false);
}
示例14: deserialize
import com.google.protobuf.Message; //导入依赖的package包/类
@Override ExecuteResponse deserialize(Message genericMsg) {
final Responses.ExecuteResponse msg = ProtobufService.castProtobufMessage(genericMsg,
Responses.ExecuteResponse.class);
List<Responses.ResultSetResponse> msgResults = msg.getResultsList();
List<ResultSetResponse> copiedResults = new ArrayList<>(msgResults.size());
for (Responses.ResultSetResponse msgResult : msgResults) {
copiedResults.add(ResultSetResponse.fromProto(msgResult));
}
RpcMetadataResponse metadata = null;
if (msg.hasField(METADATA_DESCRIPTOR)) {
metadata = RpcMetadataResponse.fromProto(msg.getMetadata());
}
return new ExecuteResponse(copiedResults, msg.getMissingStatement(), metadata);
}
示例15: call
import com.google.protobuf.Message; //导入依赖的package包/类
/**
* Make a call, passing <code>param</code>, to the IPC server running at <code>address</code>
* which is servicing the <code>protocol</code> protocol, with the <code>ticket</code>
* credentials, returning the value. Throws exceptions if there are network problems or if the
* remote code threw an exception.
*/
public Message call(RpcRequestBody requestBody, Class<? extends VersionedProtocol> protocol,
int rpcTimeout, Callback<Message> callback) throws Exception {
ConnectionHeader.Builder builder = ConnectionHeader.newBuilder();
builder.setProtocol(protocol == null ? "" : protocol.getName());
ConnectionHeader connectionHeader = builder.build();
RpcRequestHeader.Builder headerBuilder = RPCProtos.RpcRequestHeader.newBuilder();
RpcRequestHeader rpcHeader = headerBuilder.build();
ByteBufferOutputStream bbo = new ByteBufferOutputStream();
connectionHeader.writeDelimitedTo(bbo);
rpcHeader.writeDelimitedTo(bbo);
requestBody.writeDelimitedTo(bbo);
CallFuture<Message> future = new CallFuture<Message>(callback);
if (LOG.isDebugEnabled()) {
LOG.debug("send message, " + requestBody.getMethodName() + " , channel: " + channel);
}
transceive(bbo.getBufferList(), new TransceiverCallback<Message>(requestBody, protocol, future));
if (callback == null) {
try {
return future.get(conf.getLong(AngelConf.ANGEL_READ_TIMEOUT_SEC,
AngelConf.DEFAULT_ANGEL_READ_TIMEOUT_SEC), TimeUnit.SECONDS);
} catch (java.util.concurrent.TimeoutException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("timeout for: send message, " + requestBody.getMethodName() + " , channel: "
+ channel);
}
disconnect(this.channel, true, true, e);
throw e;
}
}
return null;
}