Java 类com.google.protobuf.Message 实例源码

项目:CloudLand-Server    文件:IdBasedProtobufEncoder.java   
@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));
}
项目:grain    文件:WSCodeUtil.java   
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;
    }
}
项目:angel    文件:NettyServer.java   
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();
}
项目:rejoiner    文件:QueryResponseToProto.java   
@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;
    }
  }
}
项目:sstore-soft    文件:ProtoServer.java   
@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;
}
项目:ja-micro    文件:JsonHandler.java   
@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;
}
项目:ditb    文件:CoprocessorRpcChannel.java   
@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);
  }
}
项目:ditb    文件:RpcServer.java   
@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;
}
项目:rejoiner    文件:GqlInputConverter.java   
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();
}
项目:saluki    文件:GrpcUtil.java   
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();
}
项目:jigsaw-payment    文件:JsonFormat.java   
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);
        }
    }
}
项目:seldon-core    文件:JsonFormat.java   
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);
}
项目:calcite-avatica    文件:Service.java   
@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);
}
项目:seldon-core    文件:JsonFormat.java   
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());
  }
}
项目:s-store    文件:ProtoServer.java   
@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;
}
项目:angel    文件:NettyTransceiver.java   
/**
 * 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;
}
项目:curiostack    文件:ProtobufRedisCodec.java   
private static void encodeTo(Message message, ByteBuf target) {
  try {
    message.writeTo(
        CodedOutputStream.newInstance(
            target.nioBuffer(target.writerIndex(), target.writableBytes())));
  } catch (IOException e) {
    throw new UncheckedIOException("Could not encode message.", e);
  }
}
项目:calcite-avatica    文件:Service.java   
@Override TypeInfoRequest deserialize(Message genericMsg) {
  final Requests.TypeInfoRequest msg = ProtobufService.castProtobufMessage(genericMsg,
      Requests.TypeInfoRequest.class);

  String connectionId = null;
  if (msg.hasField(CONNECTION_ID_DESCRIPTOR)) {
    connectionId = msg.getConnectionId();
  }

  return new TypeInfoRequest(connectionId);
}
项目:ditb    文件:HTableWrapper.java   
@Override
public <R extends Message> void batchCoprocessorService(MethodDescriptor methodDescriptor,
    Message request, byte[] startKey, byte[] endKey, R responsePrototype, Callback<R> callback)
    throws ServiceException, Throwable {
  table.batchCoprocessorService(methodDescriptor, request, startKey, endKey, responsePrototype,
    callback);
}
项目:wecard-server    文件:ClientManager.java   
/**
 * 广播一个消息
 * @param message
 */
private void broadcast(Message message) {
    logger.trace("ClientManager.broadcast");
    for( Map.Entry<Long, Client> en : clientMap.entrySet()) {
        en.getValue().send(message);
    }
}
项目:saluki    文件:GrpcStreamClientCall.java   
static void startCall(ClientCall<Message, Message> call,
    ClientCall.Listener<Message> responseListener, boolean streamingResponse) {
  call.start(responseListener, new Metadata());
  if (streamingResponse) {
    call.request(1);
  } else {
    call.request(2);
  }
}
项目:JavaNRPC    文件:NrpcServiceRegistry.java   
/**
 * Get request protobuf for the RPC method.
 */
public Message getRequestProto(com.google.protobuf.ByteString byteString,
                               Message requestPrototype) throws DecodeRequestException {
    Message.Builder builder;
    try {
        builder = requestPrototype.newBuilderForType().mergeFrom(byteString);
        if (!builder.isInitialized()) {
            throw new DecodeRequestException("Invalid request proto");
        }
    } catch (InvalidProtocolBufferException e) {
        throw new DecodeRequestException("Invalid request proto");
    }
    return builder.build();
}
项目:saluki    文件:GrpcHystrixCommand.java   
@Override
protected Object getFallback() {
  Class<?> responseType = this.request.getResponseType();
  Message response = GrpcUtil.createDefaultInstance(responseType);
  Object obj = this.transformMessage(response);
  collectLogExecutor.execute(new Runnable() {

    @Override
    public void run() {
      collect(serviceName, methodName, getRequestMessage(), response, true);
    }
  });
  return obj;
}
项目:ditb    文件:AbstractTestIPC.java   
/**
 * It is hard to verify the compression is actually happening under the wraps. Hope that if
 * unsupported, we'll get an exception out of some time (meantime, have to trace it manually to
 * confirm that compression is happening down in the client and server).
 * @throws IOException
 * @throws InterruptedException
 * @throws SecurityException
 * @throws NoSuchMethodException
 */
@Test
public void testCompressCellBlock() throws IOException, InterruptedException, SecurityException,
    NoSuchMethodException, ServiceException {
  Configuration conf = new Configuration(HBaseConfiguration.create());
  conf.set("hbase.client.rpc.compressor", GzipCodec.class.getCanonicalName());
  List<Cell> cells = new ArrayList<Cell>();
  int count = 3;
  for (int i = 0; i < count; i++) {
    cells.add(CELL);
  }
  AbstractRpcClient client = createRpcClient(conf);
  TestRpcServer rpcServer = new TestRpcServer();
  try {
    rpcServer.start();
    MethodDescriptor md = SERVICE.getDescriptorForType().findMethodByName("echo");
    EchoRequestProto param = EchoRequestProto.newBuilder().setMessage("hello").build();
    PayloadCarryingRpcController pcrc =
        new PayloadCarryingRpcController(CellUtil.createCellScanner(cells));
    InetSocketAddress address = rpcServer.getListenerAddress();
    if (address == null) {
      throw new IOException("Listener channel is closed");
    }
    Pair<Message, CellScanner> r =
        client.call(pcrc, md, param, md.getOutputType().toProto(), User.getCurrent(), address,
            new MetricsConnection.CallStats());
    int index = 0;
    while (r.getSecond().advance()) {
      assertTrue(CELL.equals(r.getSecond().current()));
      index++;
    }
    assertEquals(count, index);
  } finally {
    client.close();
    rpcServer.stop();
  }
}
项目:ditb    文件:RegionCoprocessorHost.java   
public void postEndpointInvocation(final Service service, final String methodName,
    final Message request, final Message.Builder responseBuilder) throws IOException {
  execOperation(coprocessors.isEmpty() ? null : new EndpointOperation() {
    @Override
    public void call(EndpointObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
        throws IOException {
      oserver.postEndpointInvocation(ctx, service, methodName, request, responseBuilder);
    }
  });
}
项目:saluki    文件:GrpcBlockingUnaryCommand.java   
/**
 * @see com.quancheng.saluki.core.grpc.client.internal.unary.GrpcHystrixCommand#run0(com.google.protobuf.Message,
 *      io.grpc.MethodDescriptor, java.lang.Integer,
 *      com.quancheng.saluki.core.grpc.client.internal.unary.GrpcUnaryClientCall)
 */
@Override
protected Message run0(Message req, MethodDescriptor<Message, Message> methodDesc,
    Integer timeOut, GrpcUnaryClientCall clientCall) {
  try {
    return clientCall.blockingUnaryResult(req, methodDesc);
  } catch (Throwable e) {
    logger.error(e.getMessage(), e);
    super.cacheCurrentServer();
    RpcServiceException rpcService =
        new RpcServiceException(e, RpcErrorMsgConstant.BIZ_DEFAULT_EXCEPTION);
    throw rpcService;
  }
}
项目:seldon-core    文件:JsonFormat.java   
private void mergeRepeatedField(
    FieldDescriptor field, JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  if (!(json instanceof JsonArray)) {
    throw new InvalidProtocolBufferException("Expect an array but found: " + json);
  }
  JsonArray array = (JsonArray) json;
  for (int i = 0; i < array.size(); ++i) {
    Object value = parseFieldValue(field, array.get(i), builder);
    if (value == null) {
      throw new InvalidProtocolBufferException("Repeated field elements cannot be null");
    }
    builder.addRepeatedField(field, value);
  }
}
项目:saluki    文件:GrpcHystrixCommand.java   
private Message getRequestMessage() {
  try {
    Object param = this.request.getRequestParam();
    return SerializerUtil.pojo2Protobuf(param);
  } catch (ProtobufException e) {
    RpcFrameworkException rpcFramwork = new RpcFrameworkException(e);
    throw rpcFramwork;
  }
}
项目:curiostack    文件:WellKnownTypeMarshaller.java   
@Override
public void doMerge(JsonParser parser, int currentDepth, Message.Builder messageBuilder)
    throws IOException {
  JsonToken token = parser.currentToken();
  if (token != JsonToken.START_ARRAY) {
    throw new InvalidProtocolBufferException("Expect an array but found: " + parser.getText());
  }
  ListValue.Builder builder = (ListValue.Builder) messageBuilder;
  while (parser.nextValue() != JsonToken.END_ARRAY) {
    Value.Builder valueBuilder = builder.addValuesBuilder();
    ValueMarshaller.INSTANCE.mergeValue(parser, currentDepth + 1, valueBuilder);
  }
}
项目:ditb    文件:ProtobufUtil.java   
/**
 * This version of protobuf's mergeDelimitedFrom avoids the hard-coded 64MB limit for decoding
 * buffers
 * @param builder current message builder
 * @param in Inputsream with delimited protobuf data
 * @throws IOException
 */
public static void mergeDelimitedFrom(Message.Builder builder, InputStream in)
  throws IOException {
  // This used to be builder.mergeDelimitedFrom(in);
  // but is replaced to allow us to bump the protobuf size limit.
  final int firstByte = in.read();
  if (firstByte != -1) {
    final int size = CodedInputStream.readRawVarint32(firstByte, in);
    final InputStream limitedInput = new LimitInputStream(in, size);
    final CodedInputStream codedInput = CodedInputStream.newInstance(limitedInput);
    codedInput.setSizeLimit(size);
    builder.mergeFrom(codedInput);
    codedInput.checkLastTagWas(0);
  }
}
项目:hadoop-oss    文件:Server.java   
private void doSaslReply(Message message) throws IOException {
  final Call saslCall = new Call(AuthProtocol.SASL.callId,
      RpcConstants.INVALID_RETRY_COUNT, null, this);
  final ByteArrayOutputStream saslResponse = new ByteArrayOutputStream();
  setupResponse(saslResponse, saslCall,
      RpcStatusProto.SUCCESS, null,
      new RpcResponseWrapper(message), null, null);
  saslCall.sendResponse();
}
项目:hadoop-oss    文件:Server.java   
/**
 * 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);
  }
}
项目:ditb    文件:AbstractRpcClient.java   
/**
 * Make a blocking call. Throws exceptions if there are network problems or if the remote code
 * threw an exception.
 *
 * @param ticket Be careful which ticket you pass. A new user will mean a new Connection.
 *               {@link UserProvider#getCurrent()} makes a new instance of User each time so
 *               will be a
 *               new Connection each time.
 * @return A pair with the Message response and the Cell data (if any).
 */
Message callBlockingMethod(Descriptors.MethodDescriptor md, PayloadCarryingRpcController pcrc,
    Message param, Message returnType, final User ticket, final InetSocketAddress isa)
    throws ServiceException {
  if (pcrc == null) {
    pcrc = new PayloadCarryingRpcController();
  }

  Pair<Message, CellScanner> val;
  try {
    final MetricsConnection.CallStats cs = MetricsConnection.newCallStats();
    cs.setStartTime(EnvironmentEdgeManager.currentTime());
    val = call(pcrc, md, param, returnType, ticket, isa, cs);
    // Shove the results into controller so can be carried across the proxy/pb service void.
    pcrc.setCellScanner(val.getSecond());

    cs.setCallTimeMs(EnvironmentEdgeManager.currentTime() - cs.getStartTime());
    if (metrics != null) {
      metrics.updateRpc(md, param, cs);
    }
    if (LOG.isTraceEnabled()) {
      LOG.trace("Call: " + md.getName() + ", callTime: " + cs.getCallTimeMs() + "ms");
    }
    return val.getFirst();
  } catch (Throwable e) {
    throw new ServiceException(e);
  }
}
项目:saluki    文件:GrpcUtil.java   
public static Message createDefaultInstance(Class<?> type) {
  Class<? extends Message> messageType;
  if (!Message.class.isAssignableFrom(type)) {
    ProtobufEntity entity =
        (ProtobufEntity) ReflectUtils.findAnnotationFromClass(type, ProtobufEntity.class);
    messageType = entity.value();
  } else {
    messageType = (Class<? extends Message>) type;
  }
  Object obj = ReflectUtils.classInstance(messageType);
  return (Message) obj;
}
项目:seldon-core    文件:JsonFormat.java   
private void mergeListValue(JsonElement json, Message.Builder builder)
    throws InvalidProtocolBufferException {
  Descriptor descriptor = builder.getDescriptorForType();
  FieldDescriptor field = descriptor.findFieldByName("values");
  if (field == null) {
    throw new InvalidProtocolBufferException("Invalid ListValue type.");
  }
  mergeRepeatedField(field, json, builder);
}
项目:seldon-core    文件:QuantityUtils.java   
private ByteString toByteString(MessageOrBuilder message) {
  if (message instanceof Message) {
    return ((Message) message).toByteString();
  } else {
    return ((Message.Builder) message).build().toByteString();
  }
}
项目:ditb    文件:AggregationClient.java   
<R, S, P extends Message, Q extends Message, T extends Message> AggregateRequest
validateArgAndGetPB(Scan scan, ColumnInterpreter<R,S,P,Q,T> ci, boolean canFamilyBeAbsent)
    throws IOException {
  validateParameters(scan, canFamilyBeAbsent);
  final AggregateRequest.Builder requestBuilder =
      AggregateRequest.newBuilder();
  requestBuilder.setInterpreterClassName(ci.getClass().getCanonicalName());
  P columnInterpreterSpecificData = null;
  if ((columnInterpreterSpecificData = ci.getRequestData())
     != null) {
    requestBuilder.setInterpreterSpecificBytes(columnInterpreterSpecificData.toByteString());
  }
  requestBuilder.setScan(ProtobufUtil.toScan(scan));
  return requestBuilder.build();
}
项目:ja-micro    文件:ProtobufHandler.java   
private void sendSuccessfulResponse(HttpServletResponse response,
                                    RpcEnvelope.Request rpcRequest,
                                    Message pbResponse) throws IOException {
    response.setStatus(HttpServletResponse.SC_OK);

    RpcEnvelope.Response rpcResponse = RpcEnvelope.Response.newBuilder().
            setServiceMethod(rpcRequest.getServiceMethod()).
            setSequenceNumber(rpcRequest.getSequenceNumber()).build();
    byte responseHeader[] = rpcResponse.toByteArray();
    byte responseBody[];
    if (pbResponse == null) {
        responseBody = new byte[0];
    } else {
        responseBody = pbResponse.toByteArray();
    }

    try {
        ServletOutputStream out = response.getOutputStream();

        out.write(Ints.toByteArray(responseHeader.length));
        out.write(responseHeader);

        out.write(Ints.toByteArray(responseBody.length));
        out.write(responseBody);
    } catch (IOException ioex) {
        //there is nothing we can do, client probably went away
        logger.debug("Caught IOException, assuming client disconnected");
    }
}
项目:jigsaw-payment    文件:XmlJavaxFormat.java   
/**
 * Outputs a Smile representation of the Protocol Message supplied into the parameter output.
 * (This representation is the new version of the classic "ProtocolPrinter" output from the
 * original Protocol Buffer system)
 */
public void print(Message message, XMLStreamWriter generator) throws IOException {
    try {
        final String messageName = message.getDescriptorForType().getName();
        generator.writeStartElement(messageName);       
        printMessage(message, generator);
        generator.writeEndElement();
        generator.flush();
    } catch (XMLStreamException e) {
        throw new IOException(e);
    }
}
项目:outland    文件:Protobuf3MessageBodyProvider.java   
@Override
public long getSize(final Message m,
    final Class<?> type,
    final Type genericType,
    final Annotation[] annotations,
    final MediaType mediaType
) {
  return -1; // as per jax-rs 2 guidance, this value is ignored by runtimes.
}