com.google.protobuf.MessageLite Java Examples

The following examples show how to use com.google.protobuf.MessageLite. 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: ProtoDecoder.java    From xrpc with Apache License 2.0 6 votes vote down vote up
/**
 * Decode a ByteBuf body from protobuf format to an object of designated Class type.
 *
 * @param body current http request
 * @param clazz target class for decoding
 * @return object of type clazz
 */
@Override
@SuppressWarnings("unchecked")
public <T> T decode(ByteBuf body, CharSequence contentType, Class<T> clazz) throws IOException {
  // TODO (AD): given a Content-Type of application/protobuf; proto=org.some.Message,
  // we currently ignore the 2nd part, but should at least validate it in the future.

  if (!MessageLite.class.isAssignableFrom(clazz)) {
    throw new IllegalArgumentException(
        String.format("%s does not extend from MessageLite", clazz.getName()));
  }

  MessageLite message = protoDefaultInstances.get(clazz);
  Parser<?> parser = message.getParserForType();
  try (ByteBufInputStream stream = new ByteBufInputStream(body)) {
    return (T) parser.parseFrom(stream);
  }
}
 
Example #2
Source File: AndroidServiceAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Returns the {@code field} from {@code message}. */
@Override
@SuppressWarnings("unchecked")
public Object getField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  AndroidSchedulerEvent message = (AndroidSchedulerEvent) rawMessage;
  if (field == VERSION) {
    return message.getVersion();
  }
  if (field == EVENT_NAME) {
    return message.getEventName();
  }
  if (field == TICL_ID) {
    return message.getTiclId();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #3
Source File: ClientProtocolAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Returns the {@code field} from {@code message}. */
@Override
@SuppressWarnings("unchecked")
public Object getField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  InitializeMessage message = (InitializeMessage) rawMessage;
  if (field == CLIENT_TYPE) {
    return message.getClientType();
  }
  if (field == NONCE) {
    return message.getNonce();
  }
  if (field == APPLICATION_CLIENT_ID) {
    return message.getApplicationClientId();
  }
  if (field == DIGEST_SERIALIZATION_TYPE) {
    return message.getDigestSerializationType();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
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: ClientProtocolAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Returns whether {@code field} is present in {@code message}. */
@Override
@SuppressWarnings("unchecked")
public boolean hasField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  ClientVersion message = (ClientVersion) rawMessage;
  if (field == VERSION) {
    return message.hasVersion();
  }
  if (field == PLATFORM) {
    return message.hasPlatform();
  }
  if (field == LANGUAGE) {
    return message.hasLanguage();
  }
  if (field == APPLICATION_INFO) {
    return message.hasApplicationInfo();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #6
Source File: AndroidServiceAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Returns whether {@code field} is present in {@code message}. */
@Override
@SuppressWarnings("unchecked")
public boolean hasField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  InternalDowncall message = (InternalDowncall) rawMessage;
  if (field == VERSION) {
    return message.hasVersion();
  }
  if (field == SERVER_MESSAGE) {
    return message.hasServerMessage();
  }
  if (field == NETWORK_STATUS) {
    return message.hasNetworkStatus();
  }
  if (field == NETWORK_ADDR_CHANGE) {
    return message.hasNetworkAddrChange();
  }
  if (field == CREATE_CLIENT) {
    return message.hasCreateClient();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #7
Source File: RpcCompatibilityEncoder.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext context, OutboundRpcMessage message, List<Object> out) throws Exception {
  if (message.mode != RpcMode.RESPONSE_FAILURE) {
    out.add(message);
    return;
  }

  final MessageLite pBody = message.pBody;
  if (!(pBody instanceof DremioPBError)) {
    out.add(message);
    return;
  }

  DremioPBError error = (DremioPBError) pBody;
  DremioPBError newError = ErrorCompatibility.convertIfNecessary(error);

  out.add(new OutboundRpcMessage(message.mode, message.rpcType, message.coordinationId, newError, message.dBodies));
}
 
Example #8
Source File: ClientProtocolAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Returns whether {@code field} is present in {@code message}. */
@Override
@SuppressWarnings("unchecked")
public boolean hasField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  InitializeMessage message = (InitializeMessage) rawMessage;
  if (field == CLIENT_TYPE) {
    return message.hasClientType();
  }
  if (field == NONCE) {
    return message.hasNonce();
  }
  if (field == APPLICATION_CLIENT_ID) {
    return message.hasApplicationClientId();
  }
  if (field == DIGEST_SERIALIZATION_TYPE) {
    return message.hasDigestSerializationType();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #9
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 #10
Source File: AndroidServiceAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Returns the {@code field} from {@code message}. */
@Override
@SuppressWarnings("unchecked")
public Object getField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  InternalDowncall message = (InternalDowncall) rawMessage;
  if (field == VERSION) {
    return message.getVersion();
  }
  if (field == SERVER_MESSAGE) {
    return message.getServerMessage();
  }
  if (field == NETWORK_STATUS) {
    return message.getNetworkStatus();
  }
  if (field == NETWORK_ADDR_CHANGE) {
    return message.getNetworkAddrChange();
  }
  if (field == CREATE_CLIENT) {
    return message.getCreateClient();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #11
Source File: AndroidServiceAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Returns whether {@code field} is present in {@code message}. */
@Override
@SuppressWarnings("unchecked")
public boolean hasField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  CreateClient message = (CreateClient) rawMessage;
  if (field == CLIENT_TYPE) {
    return message.hasClientType();
  }
  if (field == CLIENT_NAME) {
    return message.hasClientName();
  }
  if (field == CLIENT_CONFIG) {
    return message.hasClientConfig();
  }
  if (field == SKIP_START_FOR_TEST) {
    return message.hasSkipStartForTest();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #12
Source File: MyClusterMessageListener.java    From sctalk with Apache License 2.0 6 votes vote down vote up
/**
 * @param commandId
 * @param clusterMessage
 * @since 1.0
 */
private void doGroup(short commandId, MyClusterMessage clusterMessage) {
    logger.debug("MyClusterMessageListener#doSwitch");
    IMHeader header = clusterMessage.getHeader();
    try {
        MessageLite body = clusterMessage.getMessage();
        switch (commandId) {
            case GroupCmdID.CID_GROUP_CHANGE_MEMBER_NOTIFY_VALUE:// todebug
                groupChangeMemberNotify(header, body);
                break;
            default:
                logger.warn("Unsupport command id {}", commandId);
                break;
        }
    } catch (IOException e) {
        logger.error("decode failed.", e);
    }
}
 
Example #13
Source File: DatastoreRpcService.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private <Req extends MessageLite, Resp extends MessageLite, T extends SendEndpointCreator<Req, Resp>>
SendEndpoint<Req, Resp> newEndpoint(T creator) throws RpcException {
  NodeEndpoint masterNode = master.get();
  if (masterNode == null) {
    throw new RpcException("master node is down");
  }
  return creator.getEndpoint(masterNode.getAddress(), masterNode.getFabricPort());
}
 
Example #14
Source File: BlockchainIntegrationTest.java    From exonum-java-binding with Apache License 2.0 5 votes vote down vote up
private static TransactionMessage createTestTransactionMessage(int txId, MessageLite payload) {
  return TransactionMessage.builder()
      .serviceId(SERVICE_ID)
      .transactionId(txId)
      .payload(payload)
      .sign(KEY_PAIR);
}
 
Example #15
Source File: Util.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** Assert that two messages are equal, producing a useful message if not. */
@SuppressWarnings("LiteProtoToString")
public static void assertEquals(MessageLite expected, MessageLite actual) {
  if (expected == null || actual == null) {
    Assert.assertEquals(expected, actual);
  } else {
    if (!expected.equals(actual)) {
      // This assertEquals should always complete.
      Assert.assertEquals(expected.toString(), actual.toString());
      // But if it doesn't, then this should.
      Assert.assertEquals(expected, actual);
      Assert.fail("Messages not equal, but assertEquals didn't throw");
    }
  }
}
 
Example #16
Source File: ClientProtocolAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns whether {@code field} is present in {@code message}. */
@Override
@SuppressWarnings("unchecked")
public boolean hasField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  ClientToServerMessage message = (ClientToServerMessage) rawMessage;
  if (field == HEADER) {
    return message.hasHeader();
  }
  if (field == INITIALIZE_MESSAGE) {
    return message.hasInitializeMessage();
  }
  if (field == REGISTRATION_MESSAGE) {
    return message.hasRegistrationMessage();
  }
  if (field == REGISTRATION_SYNC_MESSAGE) {
    return message.hasRegistrationSyncMessage();
  }
  if (field == INVALIDATION_ACK_MESSAGE) {
    return message.hasInvalidationAckMessage();
  }
  if (field == INFO_MESSAGE) {
    return message.hasInfoMessage();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #17
Source File: ProtobufEncoder.java    From getty with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(SocketChannel socketChannel, Object obj) throws Exception {

    byte[] bytes = null;
    if (obj instanceof MessageLite) {
        bytes = ((MessageLite) obj).toByteArray();
    }
    if (obj instanceof MessageLite.Builder) {
        bytes = ((MessageLite.Builder) obj).build().toByteArray();
    }
    super.encode(socketChannel, bytes);
}
 
Example #18
Source File: AndroidServiceAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns whether {@code field} is present in {@code message}. */
@Override
@SuppressWarnings("unchecked")
public boolean hasField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  RegistrationDowncall message = (RegistrationDowncall) rawMessage;
  if (field == REGISTRATIONS) {
    return message.getRegistrationsCount() > 0;
  }
  if (field == UNREGISTRATIONS) {
    return message.getUnregistrationsCount() > 0;
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #19
Source File: MessageLiteCodec.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public MessageLite deserialize(DeserializationContext unusedContext, CodedInputStream codedIn)
    throws IOException, SerializationException {
  // Don't hold on to full byte array when constructing this proto.
  codedIn.enableAliasing(false);
  try {
    MessageLite.Builder builder = builderSupplier.get();
    codedIn.readMessage(builder, ExtensionRegistryLite.getEmptyRegistry());
    return builder.build();
  } catch (InvalidProtocolBufferException e) {
    throw new SerializationException("Failed to parse proto of type " + type, e);
  } finally {
    codedIn.enableAliasing(true);
  }
}
 
Example #20
Source File: UserClient.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override protected MessageLite getResponseDefaultInstance(int rpcType) throws RpcException {
  switch (rpcType) {
    case RpcType.ACK_VALUE:
      return Ack.getDefaultInstance();
    case RpcType.HANDSHAKE_VALUE:
      return BitToUserHandshake.getDefaultInstance();
    case RpcType.QUERY_HANDLE_VALUE:
      return QueryId.getDefaultInstance();
    case RpcType.QUERY_RESULT_VALUE:
      return QueryResult.getDefaultInstance();
    case RpcType.QUERY_DATA_VALUE:
      return QueryData.getDefaultInstance();
    case RpcType.QUERY_PLAN_FRAGMENTS_VALUE:
      return QueryPlanFragments.getDefaultInstance();
    case RpcType.CATALOGS_VALUE:
      return GetCatalogsResp.getDefaultInstance();
    case RpcType.SCHEMAS_VALUE:
      return GetSchemasResp.getDefaultInstance();
    case RpcType.TABLES_VALUE:
      return GetTablesResp.getDefaultInstance();
    case RpcType.COLUMNS_VALUE:
      return GetColumnsResp.getDefaultInstance();
    case RpcType.PREPARED_STATEMENT_VALUE:
      return CreatePreparedStatementResp.getDefaultInstance();
    case RpcType.SASL_MESSAGE_VALUE:
      return SaslMessage.getDefaultInstance();
    case RpcType.SERVER_META_VALUE:
      return GetServerMetaResp.getDefaultInstance();
  }
  throw new RpcException(String.format("Unable to deal with RpcType of %d", rpcType));
}
 
Example #21
Source File: AndroidServiceAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns whether {@code field} is present in {@code message}. */
@Override
@SuppressWarnings("unchecked")
public boolean hasField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  StopDowncall message = (StopDowncall) rawMessage;
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #22
Source File: DataDefaultInstanceHandler.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static MessageLite getResponseDefaultInstanceServer(int rpcType) throws RpcException {
  switch (rpcType) {
  case RpcType.ACK_VALUE:
    return Ack.getDefaultInstance();
  case RpcType.HANDSHAKE_VALUE:
    return BitClientHandshake.getDefaultInstance();
  case RpcType.REQ_RECORD_BATCH_VALUE:
    return FragmentRecordBatch.getDefaultInstance();
  case RpcType.SASL_MESSAGE_VALUE:
    return SaslMessage.getDefaultInstance();

  default:
    throw new UnsupportedOperationException();
  }
}
 
Example #23
Source File: DataDefaultInstanceHandler.java    From Bats with Apache License 2.0 5 votes vote down vote up
public static MessageLite getResponseDefaultInstanceClient(int rpcType) throws RpcException {
  switch (rpcType) {
  case RpcType.ACK_VALUE:
    return Ack.getDefaultInstance();
  case RpcType.HANDSHAKE_VALUE:
    return BitServerHandshake.getDefaultInstance();
  case RpcType.SASL_MESSAGE_VALUE:
    return SaslMessage.getDefaultInstance();

  default:
    throw new UnsupportedOperationException();
  }
}
 
Example #24
Source File: AndroidServiceAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns the {@code field} from {@code message}. */
@Override
@SuppressWarnings("unchecked")
public Object getField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  AckDowncall message = (AckDowncall) rawMessage;
  if (field == ACK_HANDLE) {
    return message.getAckHandle();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #25
Source File: ClientProtocolAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns whether {@code field} is present in {@code message}. */
@Override
@SuppressWarnings("unchecked")
public boolean hasField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  ApplicationClientIdP message = (ApplicationClientIdP) rawMessage;
  if (field == CLIENT_TYPE) {
    return message.hasClientType();
  }
  if (field == CLIENT_NAME) {
    return message.hasClientName();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #26
Source File: ClientProtocolAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns the {@code field} from {@code message}. */
@Override
@SuppressWarnings("unchecked")
public Object getField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  PropertyRecord message = (PropertyRecord) rawMessage;
  if (field == NAME) {
    return message.getName();
  }
  if (field == VALUE) {
    return message.getValue();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #27
Source File: ClientUser.java    From sctalk with Apache License 2.0 5 votes vote down vote up
public void broadcastWithOutMobile(IMProtoMessage<MessageLite> message, ChannelHandlerContext fromCtx) {
    for (ChannelHandlerContext conn: connMap.values()) {
        if (conn != fromCtx && CommonUtils.isPc(conn.attr(CLIENT_TYPE).get())) {
            logger.trace("发送消息> {}", conn.channel().remoteAddress());
            conn.writeAndFlush(message);
        }
    }
}
 
Example #28
Source File: ProtoUtils.java    From openrtb with Apache License 2.0 5 votes vote down vote up
/**
 * Given a message-or-builder, returns a message, invoking the builder if necessary.
 */
@SuppressWarnings("unchecked")
public static <I extends MessageLiteOrBuilder, O extends MessageLite> O built(@Nullable I msg) {
  return msg instanceof MessageLite.Builder
      ? (O) ((MessageLite.Builder) msg).build()
      : (O) msg;
}
 
Example #29
Source File: AndroidServiceAccessor.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Returns the {@code field} from {@code message}. */
@Override
@SuppressWarnings("unchecked")
public Object getField(MessageLite rawMessage, Descriptor field) {
  Preconditions.checkNotNull(rawMessage);
  Preconditions.checkNotNull(field);
  ServerMessage message = (ServerMessage) rawMessage;
  if (field == DATA) {
    return message.getData();
  }
  throw new IllegalArgumentException("Bad descriptor: " + field);
}
 
Example #30
Source File: IMWebrtcHandlerImpl.java    From sctalk with Apache License 2.0 5 votes vote down vote up
@Override
    public void initiateReq(IMHeader header, MessageLite body, ChannelHandlerContext ctx) {
        IMAVCallInitiateReq msg = (IMAVCallInitiateReq)body;
        long fromId = msg.getFromId();
        long toId = msg.getToId();
//        // long callId = msg.getCallId();
//        // FIXME: ?sdp msg.getAttachData()
//        
//        // IMBaseDefine.ClientType nType = msg.getCallerClientType();
//        // logger.debug("webrtc initiate request {} {} {} {}", fromId, toId, callId, nType);
//
//        ClientUser toClientUser = ClientUserManager.getUserById(toId);
//        if (toClientUser != null ){
//            IMHeader hdRequest = header.clone();
//            hdRequest.setSeqnum(0);
//            IMProtoMessage<MessageLite>  msgCancel = new IMProtoMessage<MessageLite>(hdRequest, body);
//            toClientUser.broadcast(msgCancel, ctx);
//        }
// 
//        messageServerCluster.send(header, body);
        ListenableFuture<?> future = messageServerCluster.webrtcInitateCallReq(fromId, toId, super.getHandleId(ctx));
        future.addCallback((result) -> {
            messageServerCluster.sendToUser(toId, header, body);
        }, (throwable) -> {
            // TODO 发起失败
        });
    }