Java Code Examples for com.google.protobuf.MessageLite#getSerializedSize()

The following examples show how to use com.google.protobuf.MessageLite#getSerializedSize() . 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: ProtoBufSerializationProvider.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(final Object toSerialize, final Buffer destination) {
    if (!(toSerialize instanceof MessageLite)) {
        throw new SerializationException("Unknown type to serialize (expected MessageLite): " +
                toSerialize.getClass().getName());
    }
    final MessageLite msg = (MessageLite) toSerialize;
    final int size = msg.getSerializedSize();
    // TODO (nkant) : handle compression
    destination.writeByte(0);
    destination.writeInt(size);
    destination.ensureWritable(size);

    final int writerIdx = destination.writerIndex();
    final int writableBytes = destination.writableBytes();
    final CodedOutputStream out = destination.hasArray() ?
            newInstance(destination.array(), destination.arrayOffset() + writerIdx, writableBytes) :
            newInstance(destination.toNioBuffer(writerIdx, writableBytes));
    try {
        msg.writeTo(out);
    } catch (IOException e) {
        throw new SerializationException(e);
    }
    destination.writerIndex(writerIdx + size);
}
 
Example 2
Source File: SyncMessageSender.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Send a message.
 *
 * @param msg
 *            the message to send
 * @throws CJCommunicationsException
 *             to wrap any occurring IOException
 */
public void send(XMessage message) {
    MessageLite msg = message.getMessage();
    try {
        int type = MessageConstants.getTypeForMessageClass(msg.getClass());
        int size = 1 + msg.getSerializedSize();
        if (this.maxAllowedPacket > 0 && size > this.maxAllowedPacket) {
            throw new CJPacketTooBigException(Messages.getString("PacketTooBigException.1", new Object[] { size, this.maxAllowedPacket }));
        }
        // for debugging
        // System.err.println("Initiating write of message (size=" + size + ", tag=" + ClientMessages.Type.valueOf(type) + ")");
        byte[] sizeHeader = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(size).array();
        this.outputStream.write(sizeHeader);
        this.outputStream.write(type);
        msg.writeTo(this.outputStream);
        this.outputStream.flush();
        this.lastPacketSentTime = System.currentTimeMillis();
    } catch (IOException ex) {
        throw new CJCommunicationsException("Unable to write message", ex);
    }
}
 
Example 3
Source File: AsyncMessageSender.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Asynchronously write a message with a notification being delivered to <code>callback</code> upon completion of write of entire message.
 *
 * @param message
 *            message extending {@link XMessage}
 * @param callback
 *            an optional callback to receive notification of when the message is completely written
 */
public void writeAsync(XMessage message, CompletionHandler<Long, Void> callback) {
    MessageLite msg = message.getMessage();
    int type = MessageConstants.getTypeForMessageClass(msg.getClass());
    int size = msg.getSerializedSize();
    int payloadSize = size + 1;
    // we check maxAllowedPacket against payloadSize as that's considered the "packet size" (not including 4 byte size header)
    if (this.maxAllowedPacket > 0 && payloadSize > this.maxAllowedPacket) {
        throw new CJPacketTooBigException(Messages.getString("PacketTooBigException.1", new Object[] { size, this.maxAllowedPacket }));
    }
    // for debugging
    //System.err.println("Initiating write of message (size=" + payloadSize + ", tag=" + com.mysql.cj.mysqlx.protobuf.Mysqlx.ClientMessages.Type.valueOf(type) + ")");
    ByteBuffer messageBuf = ByteBuffer.allocate(HEADER_LEN + size).order(ByteOrder.LITTLE_ENDIAN).putInt(payloadSize);
    messageBuf.put((byte) type);
    try {
        // directly access the ByteBuffer's backing array as protobuf's CodedOutputStream.newInstance(ByteBuffer) is giving a stream that doesn't actually
        // write any data
        msg.writeTo(CodedOutputStream.newInstance(messageBuf.array(), HEADER_LEN, size + HEADER_LEN));
        messageBuf.position(messageBuf.limit());
    } catch (IOException ex) {
        throw new CJCommunicationsException("Unable to write message", ex);
    }
    messageBuf.flip();
    this.bufferWriter.queueBuffer(messageBuf, callback);
}
 
Example 4
Source File: SyncMessageSender.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public void send(XMessage message) {
    synchronized (this.waitingAsyncOperationMonitor) {
        MessageLite msg = message.getMessage();
        try {
            int type = MessageConstants.getTypeForMessageClass(msg.getClass());
            int size = 1 + msg.getSerializedSize();
            if (this.maxAllowedPacket > 0 && size > this.maxAllowedPacket) {
                throw new CJPacketTooBigException(Messages.getString("PacketTooBigException.1", new Object[] { size, this.maxAllowedPacket }));
            }
            // for debugging
            // System.err.println("Initiating write of message (size=" + size + ", tag=" + ClientMessages.Type.valueOf(type) + ")");
            byte[] sizeHeader = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(size).array();
            this.outputStream.write(sizeHeader);
            this.outputStream.write(type);
            msg.writeTo(this.outputStream);
            this.outputStream.flush();
            this.previousPacketSentTime = this.lastPacketSentTime;
            this.lastPacketSentTime = System.currentTimeMillis();
        } catch (IOException ex) {
            throw new CJCommunicationsException("Unable to write message", ex);
        }
    }
}
 
Example 5
Source File: AsyncMessageSender.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public void send(XMessage message, CompletionHandler<Long, Void> callback) {
    MessageLite msg = message.getMessage();
    int type = MessageConstants.getTypeForMessageClass(msg.getClass());
    int size = msg.getSerializedSize();
    int payloadSize = size + 1;
    // we check maxAllowedPacket against payloadSize as that's considered the "packet size" (not including 4 byte size header)
    if (this.maxAllowedPacket > 0 && payloadSize > this.maxAllowedPacket) {
        throw new CJPacketTooBigException(Messages.getString("PacketTooBigException.1", new Object[] { size, this.maxAllowedPacket }));
    }
    // for debugging
    //System.err.println("Initiating write of message (size=" + payloadSize + ", tag=" + com.mysql.cj.mysqlx.protobuf.Mysqlx.ClientMessages.Type.valueOf(type) + ")");
    ByteBuffer messageBuf = ByteBuffer.allocate(HEADER_LEN + size).order(ByteOrder.LITTLE_ENDIAN).putInt(payloadSize);
    messageBuf.put((byte) type);
    try {
        // directly access the ByteBuffer's backing array as protobuf's CodedOutputStream.newInstance(ByteBuffer) is giving a stream that doesn't actually
        // write any data
        msg.writeTo(CodedOutputStream.newInstance(messageBuf.array(), HEADER_LEN, size));
        messageBuf.position(messageBuf.limit());
    } catch (IOException ex) {
        throw new CJCommunicationsException("Unable to write message", ex);
    }
    messageBuf.flip();
    this.bufferWriter.queueBuffer(messageBuf, callback);
}
 
Example 6
Source File: SyncMessageSender.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public void send(XMessage message, CompletionHandler<Long, Void> callback) {
    synchronized (this.waitingAsyncOperationMonitor) {
        MessageLite msg = message.getMessage();
        try {
            send(message);
            long result = 4 + 1 + msg.getSerializedSize();
            callback.completed(result, null);
        } catch (Throwable t) {
            callback.failed(t, null);
        }
    }
}
 
Example 7
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
/**
 * Check information recorded by Census.
 */
private void checkCensus(MetricsRecord record, boolean isServer,
    Collection<? extends MessageLite> requests, Collection<? extends MessageLite> responses) {
  int uncompressedRequestsSize = 0;
  for (MessageLite request : requests) {
    uncompressedRequestsSize += request.getSerializedSize();
  }
  int uncompressedResponsesSize = 0;
  for (MessageLite response : responses) {
    uncompressedResponsesSize += response.getSerializedSize();
  }
  if (isServer) {
    assertEquals(
        requests.size(),
        record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_REQUEST_COUNT));
    assertEquals(
        responses.size(),
        record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_RESPONSE_COUNT));
    assertEquals(
        uncompressedRequestsSize,
        record.getMetricAsLongOrFail(
            DeprecatedCensusConstants.RPC_SERVER_UNCOMPRESSED_REQUEST_BYTES));
    assertEquals(
        uncompressedResponsesSize,
        record.getMetricAsLongOrFail(
            DeprecatedCensusConstants.RPC_SERVER_UNCOMPRESSED_RESPONSE_BYTES));
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_SERVER_LATENCY));
    // It's impossible to get the expected wire sizes because it may be compressed, so we just
    // check if they are recorded.
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_REQUEST_BYTES));
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_RESPONSE_BYTES));
  } else {
    assertEquals(
        requests.size(),
        record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_COUNT));
    assertEquals(
        responses.size(),
        record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_COUNT));
    assertEquals(
        uncompressedRequestsSize,
        record.getMetricAsLongOrFail(
            DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
    assertEquals(
        uncompressedResponsesSize,
        record.getMetricAsLongOrFail(
            DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES));
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_ROUNDTRIP_LATENCY));
    // It's impossible to get the expected wire sizes because it may be compressed, so we just
    // check if they are recorded.
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_BYTES));
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_BYTES));
  }
}
 
Example 8
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
/**
 * Check information recorded by Census.
 */
private void checkCensus(MetricsRecord record, boolean isServer,
    Collection<? extends MessageLite> requests, Collection<? extends MessageLite> responses) {
  int uncompressedRequestsSize = 0;
  for (MessageLite request : requests) {
    uncompressedRequestsSize += request.getSerializedSize();
  }
  int uncompressedResponsesSize = 0;
  for (MessageLite response : responses) {
    uncompressedResponsesSize += response.getSerializedSize();
  }
  if (isServer) {
    assertEquals(
        requests.size(),
        record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_REQUEST_COUNT));
    assertEquals(
        responses.size(),
        record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_SERVER_RESPONSE_COUNT));
    assertEquals(
        uncompressedRequestsSize,
        record.getMetricAsLongOrFail(
            DeprecatedCensusConstants.RPC_SERVER_UNCOMPRESSED_REQUEST_BYTES));
    assertEquals(
        uncompressedResponsesSize,
        record.getMetricAsLongOrFail(
            DeprecatedCensusConstants.RPC_SERVER_UNCOMPRESSED_RESPONSE_BYTES));
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_SERVER_LATENCY));
    // It's impossible to get the expected wire sizes because it may be compressed, so we just
    // check if they are recorded.
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_REQUEST_BYTES));
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_SERVER_RESPONSE_BYTES));
  } else {
    assertEquals(
        requests.size(),
        record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_COUNT));
    assertEquals(
        responses.size(),
        record.getMetricAsLongOrFail(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_COUNT));
    assertEquals(
        uncompressedRequestsSize,
        record.getMetricAsLongOrFail(
            DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
    assertEquals(
        uncompressedResponsesSize,
        record.getMetricAsLongOrFail(
            DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES));
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_ROUNDTRIP_LATENCY));
    // It's impossible to get the expected wire sizes because it may be compressed, so we just
    // check if they are recorded.
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_REQUEST_BYTES));
    assertNotNull(record.getMetric(DeprecatedCensusConstants.RPC_CLIENT_RESPONSE_BYTES));
  }
}