当前位置: 首页>>代码示例>>Java>>正文


Java Message类代码示例

本文整理汇总了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));
}
 
开发者ID:CloudLandGame,项目名称:CloudLand-Server,代码行数:27,代码来源:IdBasedProtobufEncoder.java

示例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;
	}
}
 
开发者ID:dianbaer,项目名称:grain,代码行数:32,代码来源:WSCodeUtil.java

示例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());
  }
}
 
开发者ID:SeldonIO,项目名称:seldon-core,代码行数:25,代码来源:JsonFormat.java

示例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();
}
 
开发者ID:Tencent,项目名称:angel,代码行数:24,代码来源:NettyServer.java

示例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;
    }
  }
}
 
开发者ID:google,项目名称:rejoiner,代码行数:19,代码来源:QueryResponseToProto.java

示例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;
}
 
开发者ID:s-store,项目名称:sstore-soft,代码行数:25,代码来源:ProtoServer.java

示例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;
}
 
开发者ID:Sixt,项目名称:ja-micro,代码行数:27,代码来源:JsonHandler.java

示例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);
  }
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:18,代码来源:CoprocessorRpcChannel.java

示例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;
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:24,代码来源:RpcServer.java

示例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();
}
 
开发者ID:google,项目名称:rejoiner,代码行数:27,代码来源:GqlInputConverter.java

示例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();
}
 
开发者ID:venus-boot,项目名称:saluki,代码行数:17,代码来源:GrpcUtil.java

示例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);
        }
    }
}
 
开发者ID:jigsaw-projects,项目名称:jigsaw-payment,代码行数:22,代码来源:JsonFormat.java

示例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);
}
 
开发者ID:SeldonIO,项目名称:seldon-core,代码行数:19,代码来源:JsonFormat.java

示例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);
}
 
开发者ID:apache,项目名称:calcite-avatica,代码行数:19,代码来源:Service.java

示例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;
}
 
开发者ID:Tencent,项目名称:angel,代码行数:43,代码来源:NettyTransceiver.java


注:本文中的com.google.protobuf.Message类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。