Java Code Examples for com.google.protobuf.Any#is()

The following examples show how to use com.google.protobuf.Any#is() . 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: TransactionAppendix.java    From burstkit4j with Apache License 2.0 8 votes vote down vote up
public static TransactionAppendix fromProtobuf(Any protobuf) {
    try {
        if (protobuf.is(BrsApi.EncryptedMessageAppendix.class)) {
            return EncryptedMessageAppendix.fromProtobuf(protobuf.unpack(BrsApi.EncryptedMessageAppendix.class));
        } else if (protobuf.is(BrsApi.MessageAppendix.class)) {
            return new PlaintextMessageAppendix(protobuf.unpack(BrsApi.MessageAppendix.class));
        } else {
            return null; // If we do not support that appendix
        }
    } catch (InvalidProtocolBufferException e) {
        return null;
    }
}
 
Example 2
Source File: TransactionAttachment.java    From burstkit4j with Apache License 2.0 6 votes vote down vote up
public static TransactionAttachment fromProtobuf(Any protobuf, int transactionVersion) {
    try {
        if (protobuf.is(BrsApi.AccountInfoAttachment.class)) {
            return new AccountInfoAttachment(protobuf.unpack(BrsApi.AccountInfoAttachment.class));
        } else if (protobuf.is(BrsApi.ATCreationAttachment.class)) {
            return new ATCreationAttachment(protobuf.unpack(BrsApi.ATCreationAttachment.class));
        } else if (protobuf.is(BrsApi.MultiOutAttachment.class)) {
            return new MultiOutAttachment(protobuf.unpack(BrsApi.MultiOutAttachment.class));
        } else if (protobuf.is(BrsApi.MultiOutSameAttachment.class)) {
            return new MultiOutSameAttachment(protobuf.unpack(BrsApi.MultiOutSameAttachment.class));
        } else if (protobuf.is(BrsApi.RewardRecipientAssignmentAttachment.class)) {
            return new RewardRecipientAssignmentAttachment(protobuf.unpack(BrsApi.RewardRecipientAssignmentAttachment.class).getVersion());
        } else if (protobuf.is(BrsApi.OrdinaryPaymentAttachment.class)) {
            return new OrdinaryPaymentAttachment(transactionVersion);
        } else {
            return null; // If we do not support that attachment
        }
    } catch (InvalidProtocolBufferException e) {
        return null;
    }
}
 
Example 3
Source File: AnyTest.java    From jprotobuf with Apache License 2.0 6 votes vote down vote up
/**
 * Test use any.
 *
 * @throws InvalidProtocolBufferException the invalid protocol buffer exception
 */
@Test
public void testUseOriginAny() throws InvalidProtocolBufferException {

    StringMessage message = StringMessage.newBuilder().setList("hello world").build();

    InterClassName message2 = InterClassName.newBuilder().setInt32F(1333).build();

    AnyObject any = AnyObject.newBuilder().addDetails(Any.pack(message)).addDetails(Any.pack(message2)).build();

    byte[] byteArray = any.toByteArray();

    AnyObject anyObject = AnyProtos.AnyObject.parseFrom(byteArray);

    List<Any> detailsList = anyObject.getDetailsList();
    for (Any any2 : detailsList) {
        if (any2.is(StringMessage.class)) {
            StringMessage unpack = any2.unpack(StringMessage.class);

            Assert.assertEquals(message.getList(), unpack.getList());
        }
    }
}
 
Example 4
Source File: AnyTest.java    From jprotobuf with Apache License 2.0 6 votes vote down vote up
/**
 * Test use any.
 * 
 * @throws IOException
 */
@Test
public void testDecodeUseOriginAny() throws IOException {

    StringTypePOJOClass pojo = new StringTypePOJOClass();
    pojo.setStr("hello world");

    com.baidu.bjf.remoting.protobuf.Any any =
            com.baidu.bjf.remoting.protobuf.Any.pack(pojo, StringMessage.class.getName());

    Codec<com.baidu.bjf.remoting.protobuf.Any> codec =
            ProtobufProxy.create(com.baidu.bjf.remoting.protobuf.Any.class);
    byte[] byteArray = codec.encode(any);

    AnyObject anyObject = AnyProtos.AnyObject.parseFrom(byteArray);

    List<Any> detailsList = anyObject.getDetailsList();

    for (Any any2 : detailsList) {
        if (any2.is(StringMessage.class)) {
            StringMessage unpack = any2.unpack(StringMessage.class);

            Assert.assertEquals(pojo.getStr(), unpack.getList());
        }
    }
}
 
Example 5
Source File: GenericKinesisEgressSerializer.java    From flink-statefun with Apache License 2.0 5 votes vote down vote up
private static KinesisEgressRecord asKinesisEgressRecord(Any message) {
  if (!message.is(KinesisEgressRecord.class)) {
    throw new IllegalStateException(
        "The generic Kinesis egress expects only messages of type "
            + KinesisEgressRecord.class.getName());
  }
  try {
    return message.unpack(KinesisEgressRecord.class);
  } catch (InvalidProtocolBufferException e) {
    throw new RuntimeException(
        "Unable to unpack message as a " + KinesisEgressRecord.class.getName(), e);
  }
}
 
Example 6
Source File: GenericKafkaEgressSerializer.java    From flink-statefun with Apache License 2.0 5 votes vote down vote up
private static KafkaProducerRecord asKafkaProducerRecord(Any message) {
  if (!message.is(KafkaProducerRecord.class)) {
    throw new IllegalStateException(
        "The generic Kafka egress expects only messages of type "
            + KafkaProducerRecord.class.getName());
  }
  try {
    return message.unpack(KafkaProducerRecord.class);
  } catch (InvalidProtocolBufferException e) {
    throw new RuntimeException(
        "Unable to unpack message as a " + KafkaProducerRecord.class.getName(), e);
  }
}
 
Example 7
Source File: BasicK8sWorker.java    From twister2 with Apache License 2.0 5 votes vote down vote up
/**
 * test scaling up and down workers in the job
 * after each scaleup event, all workers wait in a barrier
 */
private void testScalingMessaging(IWorkerController workerController) {

  // we assume the worker is doing some computation
  // we simulate the computation by sleeping the worker for some time

  while (true) {

    // do some computation
    sleepRandomTime(300);

    // check for scaled up event
    if (scaledUp) {
      // reset the flag
      scaledUp = false;

      List<JobMasterAPI.WorkerInfo> workerList = initSynch(workerController);
      if (workerList == null) {
        return;
      }
    }

    // if received some messages, send the same messages back to the driver
    while (messages.size() != 0) {

      Any anyMessage = messages.remove(0);
      if (anyMessage.is(JobMasterAPI.WorkerStateChange.class)) {
        // finish execution
        LOG.info("Received following message. Finishing execution: " + anyMessage);
        return;
      } else {
        senderToDriver.sendToDriver(anyMessage);
      }
    }

  }

}
 
Example 8
Source File: CDFWRuntime.java    From twister2 with Apache License 2.0 5 votes vote down vote up
/**
 * execute
 */
public boolean execute() {
  Any msg;
  while (true) {
    msg = executeMessageQueue.peek();
    if (msg == null) {
      if (scaleUpRequest.get()) {
        communicator.close();
        List<JobMasterAPI.WorkerInfo> workerInfoList = initSynch(controller);

        // create the channel
        LOG.info("Existing workers calling barrier");
        channel = Network.initializeChannel(config, controller);
        String persistent = null;

        // create the communicator
        communicator = new Communicator(config, channel, persistent);
        taskExecutor = new TaskExecutor(config, workerId, workerInfoList, communicator, null);
      }
      scaleUpRequest.set(false);
      //scaleDownRequest.set(false);
      continue;
    }
    msg = executeMessageQueue.poll();
    if (msg.is(CDFWJobAPI.ExecuteMessage.class)) {
      if (handleExecuteMessage(msg)) {
        return false;
      }
    } else if (msg.is(CDFWJobAPI.CDFWJobCompletedMessage.class)) {
      LOG.log(Level.INFO, workerId + "Received CDFW job completed message. Leaving execution "
          + "loop");
      break;
    }
  }
  LOG.log(Level.INFO, workerId + " Execution Completed");
  return true;
}
 
Example 9
Source File: JobsRpcUtils.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given {@link Status} to a {@link UserException}, if possible.
 *
 * @param statusProto status runtime exception
 * @return user exception if one is passed as part of the details
 */
public static Optional<UserException> fromStatus(Status statusProto) {
  for (Any details : statusProto.getDetailsList()) {
    if (details.is(DremioPBError.class)) {
      try {
        return Optional.of(UserRemoteException.create(details.unpack(DremioPBError.class)));
      } catch (InvalidProtocolBufferException e) {
        logger.warn("Received an invalid UserException, ignoring", e);
        return Optional.empty();
      }
    }
  }

  return Optional.empty();
}
 
Example 10
Source File: AbstractServerInstance.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
protected void logFailedStatus(Digest actionDigest, com.google.rpc.Status status) {
  String message =
      format(
          "%s: %s: %s\n",
          DigestUtil.toString(actionDigest),
          Code.forNumber(status.getCode()),
          status.getMessage());
  for (Any detail : status.getDetailsList()) {
    if (detail.is(PreconditionFailure.class)) {
      message += "  PreconditionFailure:\n";
      PreconditionFailure preconditionFailure;
      try {
        preconditionFailure = detail.unpack(PreconditionFailure.class);
        for (Violation violation : preconditionFailure.getViolationsList()) {
          message +=
              format(
                  "    Violation: %s %s: %s\n",
                  violation.getType(), violation.getSubject(), violation.getDescription());
        }
      } catch (InvalidProtocolBufferException e) {
        message += "  " + e.getMessage();
      }
    } else {
      message += "  Unknown Detail\n";
    }
  }
  getLogger().info(message);
}
 
Example 11
Source File: AbstractServerInstance.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
protected static QueuedOperationMetadata maybeQueuedOperationMetadata(String name, Any metadata) {
  if (metadata.is(QueuedOperationMetadata.class)) {
    try {
      return metadata.unpack(QueuedOperationMetadata.class);
    } catch (InvalidProtocolBufferException e) {
      logger.log(Level.SEVERE, format("invalid executing operation metadata %s", name), e);
    }
  }
  return null;
}
 
Example 12
Source File: AbstractServerInstance.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
protected static ExecutingOperationMetadata maybeExecutingOperationMetadata(
    String name, Any metadata) {
  if (metadata.is(ExecutingOperationMetadata.class)) {
    try {
      return metadata.unpack(ExecutingOperationMetadata.class);
    } catch (InvalidProtocolBufferException e) {
      logger.log(Level.SEVERE, format("invalid executing operation metadata %s", name), e);
    }
  }
  return null;
}
 
Example 13
Source File: AbstractServerInstance.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
protected static CompletedOperationMetadata maybeCompletedOperationMetadata(
    String name, Any metadata) {
  if (metadata.is(CompletedOperationMetadata.class)) {
    try {
      return metadata.unpack(CompletedOperationMetadata.class);
    } catch (InvalidProtocolBufferException e) {
      logger.log(Level.SEVERE, format("invalid completed operation metadata %s", name), e);
    }
  }
  return null;
}
 
Example 14
Source File: Cat.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private static void printStatus(com.google.rpc.Status status)
    throws InvalidProtocolBufferException {
  System.out.println("  Code: " + Code.forNumber(status.getCode()));
  if (!status.getMessage().isEmpty()) {
    System.out.println("  Message: " + status.getMessage());
  }
  if (status.getDetailsCount() > 0) {
    System.out.println("  Details:");
    for (Any detail : status.getDetailsList()) {
      if (detail.is(RetryInfo.class)) {
        RetryInfo retryInfo = detail.unpack(RetryInfo.class);
        System.out.println(
            "    RetryDelay: "
                + (retryInfo.getRetryDelay().getSeconds()
                    + retryInfo.getRetryDelay().getNanos() / 1000000000.0f));
      } else if (detail.is(PreconditionFailure.class)) {
        PreconditionFailure preconditionFailure = detail.unpack(PreconditionFailure.class);
        System.out.println("    PreconditionFailure:");
        for (PreconditionFailure.Violation violation : preconditionFailure.getViolationsList()) {
          System.out.println("      Violation: " + violation.getType());
          System.out.println("        Subject: " + violation.getSubject());
          System.out.println("        Description: " + violation.getDescription());
        }
      } else {
        System.out.println("    Unknown Detail: " + detail.getTypeUrl());
      }
    }
  }
}
 
Example 15
Source File: ProtobufClient.java    From protobuf-converter with MIT License 5 votes vote down vote up
private <T extends Message> T extractResponseData(final Response response, final Class<T> clazz) throws
		ClientException {
	Any data = response.getData();
	try {
		if (data.is(Failure.class)) {
			throw new ClientException(data.unpack(Failure.class).getCause());
		}
		return data.unpack(clazz);
	} catch (InvalidProtocolBufferException e) {
		throw new ClientException(e.getMessage());
	}
}