當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。