Java Code Examples for com.google.protobuf.Message#toByteArray()

The following examples show how to use com.google.protobuf.Message#toByteArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PersisterHelper.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static void writeToStreamWithHeader( MarshallerWriteContext context,
                                            Message payload ) throws IOException {
    ProtobufMessages.Header.Builder _header = ProtobufMessages.Header.newBuilder();
    _header.setVersion( ProtobufMessages.Version.newBuilder()
                                        .setVersionMajor( Drools.getMajorVersion() )
                                        .setVersionMinor( Drools.getMinorVersion() )
                                        .setVersionRevision( Drools.getRevisionVersion() )
                        .build() );
    
    writeStrategiesIndex( context, _header );

    writeRuntimeDefinedClasses( context, _header );

    byte[] buff = payload.toByteArray();
    sign( _header, buff );
    _header.setPayload( ByteString.copyFrom( buff ) );

    context.stream.write( _header.build().toByteArray() );
}
 
Example 2
Source File: RRServer.java    From twister2 with Apache License 2.0 6 votes vote down vote up
protected TCPMessage sendMessage(Message message, RequestID requestID, SocketChannel channel) {
  byte[] data = message.toByteArray();
  String messageType = message.getDescriptorForType().getFullName();

  // lets serialize the message
  int capacity = requestID.getId().length + data.length + messageType.getBytes().length + 8;
  ByteBuffer buffer = ByteBuffer.allocate(capacity);
  // we send message id, worker id and data
  buffer.put(requestID.getId());
  // pack the name of the message
  ByteUtils.packString(messageType, buffer);
  // pack the worker id
  buffer.putInt(serverID);
  // pack data
  buffer.put(data);

  TCPMessage send = server.send(channel, buffer, capacity, 0);
  if (send != null) {
    pendingSendCount++;
  }
  return send;
}
 
Example 3
Source File: MsgUtil.java    From game-server with MIT License 6 votes vote down vote up
/**
 * 转换为游戏客户端发送的iobuff
 * 
 * @note portobuf长度对于服务器多余了,服务器进行了大小端转换
 * @param message
 * @return 【length|msgid|protobuf_length|data】
 */
   public static IoBuffer toGameClientIobuffer(final Message message) {
	int msgID = getMessageID(message);
	byte[] msgData = message.toByteArray();
	int protobufLength = msgData.length;
	IoBuffer buf = IoBuffer.allocate(10 + protobufLength); // 消息长度2字节 mid
															// 4字节
															// protobuf长度4字节

	// 消息长度
	byte[] lengthBytes = IntUtil.short2Bytes((short) (protobufLength + 8), ByteOrder.LITTLE_ENDIAN);
	buf.put(lengthBytes);
	// buf.putInt(protobufLength + 8);
	// 消息ID
	buf.put(IntUtil.writeIntToBytesLittleEnding(msgID));
	// buf.putInt(msgID);
	// protobuf长度
	buf.put(IntUtil.writeIntToBytesLittleEnding(protobufLength));
	// buf.putInt(protobufLength);
	buf.put(msgData); // 真实数据
	buf.rewind();
	return buf;
}
 
Example 4
Source File: KieModuleCacheHelper.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static void writeToStreamWithHeader( OutputStream stream,
                                            Message payload ) throws IOException {
    KieModuleCache.Header.Builder _header = KieModuleCache.Header.newBuilder();
    // need to automate this version numbering somehow
    _header.setVersion( KieModuleCache.Version.newBuilder()
                        .setVersionMajor( Drools.getMajorVersion() )
                        .setVersionMinor( Drools.getMinorVersion() )
                        .setVersionRevision( Drools.getRevisionVersion() )
                        .build() );
    
    byte[] buff = payload.toByteArray();
    sign( _header, buff );
    _header.setPayload( ByteString.copyFrom( buff ) );

    stream.write( _header.build().toByteArray() );
}
 
Example 5
Source File: WebSocketEncoder.java    From game-server with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    boolean isHandshakeResponse = message instanceof WebSocketHandShakeResponse;
    boolean isDataFramePacket = message instanceof WebSocketCodecPacket;
    boolean isRemoteWebSocket = session.containsAttribute(WebSocketUtils.SessionAttribute) && (true==(Boolean)session.getAttribute(WebSocketUtils.SessionAttribute));
    IoBuffer resultBuffer;
    if(isHandshakeResponse){
        WebSocketHandShakeResponse response = (WebSocketHandShakeResponse)message;
        resultBuffer = buildWSResponseBuffer(response);
    }
    else if(isDataFramePacket){
        WebSocketCodecPacket packet = (WebSocketCodecPacket)message;
        resultBuffer = isRemoteWebSocket ? buildWSDataFrameBuffer(packet.getPacket()) : packet.getPacket();
    }else if(message instanceof Message) {	//自定义protobuf,消息头只有ID,无长度,和app客户端不一致
    	Message msg=(Message)message;
    	int msgId=MsgUtil.getMessageID(msg);
    	byte[] msgData=msg.toByteArray();
    	IoBuffer iobuffer = IoBuffer.allocate(4+msgData.length);
    	iobuffer.putInt(msgId);
    	iobuffer.put(msgData);
    	iobuffer.rewind();
    	resultBuffer=isRemoteWebSocket?buildWSDataFrameBuffer(iobuffer):iobuffer;
    }else if(message instanceof byte[]) {  //已经包含消息ID
    	 byte[] data = (byte[]) message;
         IoBuffer buf = IoBuffer.allocate(data.length);
         buf.put(data);
         buf.rewind();
         resultBuffer=isRemoteWebSocket?buildWSDataFrameBuffer(buf):buf;
    }
    else{
        throw (new Exception("message not a websocket type"));
    }
    
    out.write(resultBuffer);
}
 
Example 6
Source File: RRClient.java    From twister2 with Apache License 2.0 5 votes vote down vote up
public RequestID sendRequest(Message message) {
  if (!client.isConnected()) {
    return null;
  }
  String messageType = message.getDescriptorForType().getFullName();
  if (!messageBuilders.containsKey(messageType)) {
    throw new RuntimeException("Message without a message builder");
  }

  RequestID id = RequestID.generate();
  byte[] data = message.toByteArray();

  // lets serialize the message
  int capacity = id.getId().length + data.length + 4 + messageType.getBytes().length + 4;
  ByteBuffer buffer = ByteBuffer.allocate(capacity);
  // we send message id, worker id and data
  buffer.put(id.getId());
  // pack the name of the message
  ByteUtils.packString(messageType, buffer);
  // pack the worker id
  buffer.putInt(workerID);
  // pack data
  buffer.put(data);

  TCPMessage request = client.send(channel, buffer, capacity, 0);
  if (request != null) {
    loop.wakeup();
    return id;
  } else {
    return null;
  }
}
 
Example 7
Source File: ProtobufHandler.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
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");
    }
}
 
Example 8
Source File: ClientTest.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 发送消息
 *
 * @param msg
 * @param mid
 */
private void sendMsg(Message msg, MID mid) {
	byte[] b = msg.toByteArray();
	int len = 8 + b.length;// (len = mid_int_len + protobuf_int_len +
	// protobuf_body_bytes_len)

	IoBuffer buf = IoBuffer.allocate(len + 2);// (total_len = len + short_len)
	byte[] shorBytes = IntUtil.short2Bytes((short) len, ByteOrder.LITTLE_ENDIAN);
	// 写入字节长度
	buf.put(shorBytes);
	// 写入mid
	buf.put(IntUtil.writeIntToBytesLittleEnding(mid.getNumber()));
	// 写入protobuf长度
	buf.put(IntUtil.writeIntToBytesLittleEnding(b.length));

	buf.put(b);
	ByteBuffer writeBuffer = ByteBuffer.wrap(buf.array());

	try {
		 Thread.sleep(1000);
		getClient().socketChannel.write(writeBuffer);
		getClient().socketChannel.register(getClient().getSelector(), SelectionKey.OP_READ);
	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example 9
Source File: MsgUtil.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 转换为未携带消息长度的iobuff
 *
 * @param message
 * @return 【msgid|data】
 */
   public static IoBuffer toIobufferWithoutLength(final Message message) {
	int msgID = getMessageID(message);
	byte[] msgData = message.toByteArray();
	if (msgData.length < 1) {
		return null;
	}
	IoBuffer buf = IoBuffer.allocate(4 + msgData.length);
	buf.putInt(msgID);
	buf.put(msgData);
	buf.rewind();
	return buf;
}
 
Example 10
Source File: MsgUtil.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 转换为发送的iobuff
 *
 * @param message
 * @param id
 * @return 【length|msgid|data】
 */
   public static IoBuffer toIobufferWithID(final Message message, long id) {
	int msgID = getMessageID(message);
	byte[] msgData = message.toByteArray();
	int msgDataLength = msgData.length;
	IoBuffer buf = IoBuffer.allocate(16 + msgDataLength);
	buf.putInt(msgDataLength + 12);
	buf.putLong(id);
	buf.putInt(msgID);
	buf.put(msgData);
	buf.rewind();
	return buf;
}
 
Example 11
Source File: MsgUtil.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 转换为发送的iobuff
 *
 * @param message
 * @return 【length|msgid|data】
 */
   public static IoBuffer toIobuffer(final Message message) {
	int msgID = getMessageID(message);
	byte[] msgData = message.toByteArray();
	int msgDataLength = msgData.length;
	IoBuffer buf = IoBuffer.allocate(8 + msgDataLength);
	buf.putInt(msgDataLength + 4);
	buf.putInt(msgID);
	buf.put(msgData);
	buf.rewind();
	return buf;
}
 
Example 12
Source File: MinaRpcChannel.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 * Call the actual RPC logic.
 * @return
 */
private final Callback doCallMethod(MethodDescriptor method, RpcController controller,
		Message request, Message responsePrototype, RpcCallback<Message> done) {
	
	RpcMessage.Builder rpcReqBuilder = RpcMessage.newBuilder();
	rpcReqBuilder.setId(rpcIdCounter.getAndIncrement());
	String serviceName = method.getService().getFullName();
	String methodName = method.getName();
	String className = void.class.getName();
	byte[] content = Constant.EMPTY_BYTES;
	if ( request != null ) {
		className = request.getClass().getName();
		content = request.toByteArray();
	}
	logger.debug("callMethod className: {}, methodName: {}", className, methodName);
	rpcReqBuilder.setClassName(className);
	rpcReqBuilder.setType(Type.REQUEST);
	rpcReqBuilder.setService(serviceName);
	rpcReqBuilder.setMethod(methodName);
	rpcReqBuilder.setPayload(ByteString.copyFrom(content));
	RpcMessage req = rpcReqBuilder.build();
	
	//Save the callback
	Callback callback = new Callback(done, responsePrototype);
	resultMap.put(req.getId(), callback);
	
	//Send this RpcRequest method to server.
	simpleClient.sendMessageToServer(req);
	
	return callback;
}
 
Example 13
Source File: MessageBodyConverter.java    From dorado with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] writeMessageBody(Message t) {
	return t.toByteArray();
}
 
Example 14
Source File: ObjectSerializer.java    From dorado with Apache License 2.0 4 votes vote down vote up
@Override
public byte[] serialize(Object t) {
	Message message = (Message) t;
	return message.toByteArray();
}
 
Example 15
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 4 votes vote down vote up
private ImmutableMap<String, String> encodeProto(Message proto)
    throws InvalidProtocolBufferException {
  byte[] protoBytes = proto.toByteArray();
  String base64BinaryString = Base64.getEncoder().encodeToString(protoBytes);
  return ImmutableMap.of(PROTO_FIELD, base64BinaryString);
}
 
Example 16
Source File: DynamicMessageRecordSerializer.java    From fdb-record-layer with Apache License 2.0 4 votes vote down vote up
@Nonnull
protected byte[] serializeToBytes(@Nonnull Message storedRecord) {
    return storedRecord.toByteArray();
}
 
Example 17
Source File: ProtoUtils.java    From julongchain with Apache License 2.0 4 votes vote down vote up
public static byte[] marshalOrPanic(Message message) {
    return message.toByteArray();
}
 
Example 18
Source File: Utils.java    From julongchain with Apache License 2.0 4 votes vote down vote up
public static byte[] marshalOrPanic(Message pb) {
    byte[] data = pb.toByteArray();
    return data;
}
 
Example 19
Source File: HttpPBPacket.java    From PeonyFramwork with Apache License 2.0 4 votes vote down vote up
public HttpPBPacket(int opcode, Builder<?> builder) {
		this.opcode = opcode;
		Message msg = builder.build();
//		log.info("[HttpPBPacket][new] \nopode:{}, message:\n[\n{}]" , opcode,  msg);
		this.data = msg.toByteArray();
	}
 
Example 20
Source File: OperationLauncher.java    From aliyun-tablestore-java-sdk with Apache License 2.0 4 votes vote down vote up
protected void asyncInvokePost(
    OTSUri actionURI,
    Map<String, String> queryParameters,
    Message message,
    TraceLogger traceLogger,
    ResponseConsumer<Res> consumer,
    FutureCallback<Res> callback)
{
    URI uri = buildURI(actionURI, queryParameters);
    HttpPost request = new HttpPost(uri);

    if (logger.isDebugEnabled()) {
        logger.debug("Operation: {}, PBRequestMessage: {}, TraceId: {}",
            actionURI, message.toString(), traceLogger.getTraceId());
    }

    byte[] content = message.toByteArray();

    if (config.isEnableRequestCompression() && content != null && content.length > 0) {
        int contentLength = content.length;
        try {
            content = CompressUtil.compress(
                new ByteArrayInputStream(content),
                new Deflater());
            request.addHeader(OTS_HEADER_REQUEST_COMPRESS_TYPE, OTS_COMPRESS_TYPE);
            request.addHeader(
                OTS_HEADER_REQUEST_COMPRESS_SIZE, Integer.toString(contentLength));
        } catch (IOException e) {
            throw new ClientException("RequestCompressFail: " + e.getMessage());
        }
    }

    if (content == null) {
        content = new byte[0];
    }

    request.setEntity(new ByteArrayEntity(content));

    String contentMd5 = Base64.toBase64String(BinaryUtil.calculateMd5(content));

    // build a wrapper for HttpRequestBase to store additional information
    RequestMessage requestMessage = new RequestMessage(request);
    requestMessage.setActionUri(actionURI);
    requestMessage.setContentMd5(contentMd5);
    requestMessage.setContentLength(content.length);

    addRequiredHeaders(requestMessage, contentMd5, traceLogger.getTraceId());

    ServiceCredentials credentials = crdsProvider.getCredentials();
    ExecutionContext ctx = createContext(
        actionURI, instanceName, credentials, config);
    client.asyncSendRequest(requestMessage, ctx, consumer, callback, traceLogger);
}