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

The following examples show how to use com.google.protobuf.Any#unpack() . 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: Actions.java    From bazel-buildfarm with Apache License 2.0 8 votes vote down vote up
public static boolean isRetriable(Status status) {
  if (status == null
      || status.getCode() != Code.FAILED_PRECONDITION.getNumber()
      || status.getDetailsCount() == 0) {
    return false;
  }
  for (Any details : status.getDetailsList()) {
    try {
      PreconditionFailure f = details.unpack(PreconditionFailure.class);
      if (f.getViolationsCount() == 0) {
        return false; // Generally shouldn't happen
      }
      for (Violation v : f.getViolationsList()) {
        if (!v.getType().equals(Errors.VIOLATION_TYPE_MISSING)) {
          return false;
        }
      }
    } catch (InvalidProtocolBufferException protoEx) {
      return false;
    }
  }
  return true; // if *all* > 0 violations have type MISSING
}
 
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: 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 5
Source File: JsonMapperProviderTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleMapping() throws JsonGenerationException, JsonMappingException, IOException {
    ObjectMapper m = new JsonMapperProvider().get();
    assertTrue(m.canSerialize(Any.class));

    Struct struct1 = Struct.newBuilder().putFields(
            "some-key", Value.newBuilder().setStringValue("some-value").build()
    ).build();

    Any source = Any.pack(struct1);

    StringWriter buf = new StringWriter();
    m.writer().writeValue(buf, source);

    Any dest = m.reader().forType(Any.class).readValue(buf.toString());
    assertEquals(source.getTypeUrl(), dest.getTypeUrl());

    Struct struct2 = dest.unpack(Struct.class);
    assertTrue(struct2.containsFields("some-key"));
    assertEquals(
            struct1.getFieldsOrThrow("some-key").getStringValue(),
            struct2.getFieldsOrThrow("some-key").getStringValue()
    );
}
 
Example 6
Source File: GrpcClient.java    From JavaInterview with Apache License 2.0 6 votes vote down vote up
public void greet() throws IOException {
    GreeterOuterClass.Request request = GreeterOuterClass.Request
            .newBuilder()
            .setName("aaa")
            .build();

    try {
        GreeterOuterClass.Response response = this.blockingStub.hello(request);
        System.out.println(response.getMsg());
    } catch (StatusRuntimeException e){
        System.out.println(e.toString());
        System.out.println(e.getStatus().getCode());
        Metadata metadata = e.getTrailers();
        com.google.rpc.Status status = metadata.get(Metadata.Key.of("grpc-status-details-bin",
                ProtoLiteUtils.metadataMarshaller(com.google.rpc.Status.getDefaultInstance())));
        if(status.getDetailsCount() > 0){
            Any any = status.getDetails(0);
            GreeterOuterClass.Request req = any.unpack(GreeterOuterClass.Request.class);
            System.out.println(req.getName());
        }


    }
}
 
Example 7
Source File: DefaultDriver.java    From twister2 with Apache License 2.0 6 votes vote down vote up
@Override
public void workerMessageReceived(Any anyMessage, int senderWorkerID) {
  try {
    JobExecutionState.WorkerJobState message =
        anyMessage.unpack(JobExecutionState.WorkerJobState.class);
    if (state != DriverJobState.FAILED) {
      if (message.getFailure()) {
        state = DriverJobState.FAILED;
      }
    }
    workerMessages.put(senderWorkerID, message);
  } catch (InvalidProtocolBufferException e) {
    LOG.log(Level.SEVERE, "Unable to unpack received protocol"
        + " buffer message as broadcast", e);
  }
}
 
Example 8
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 9
Source File: GrpcClientErrorUtils.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public static <D extends MessageOrBuilder> Optional<D> getDetail(StatusRuntimeException error, Class<D> detailType) {
    Status status = getStatus(error);
    for (Any any : status.getDetailsList()) {
        Descriptors.Descriptor descriptor = any.getDescriptorForType();
        Descriptors.FieldDescriptor typeUrlField = descriptor.findFieldByName("type_url");
        String typeUrl = (String) any.getField(typeUrlField);

        Class type;
        if (typeUrl.contains(DebugInfo.class.getSimpleName())) {
            type = DebugInfo.class;
        } else if (typeUrl.contains(BadRequest.class.getSimpleName())) {
            type = BadRequest.class;
        } else {
            return Optional.empty();
        }
        if (type == detailType) {
            Message unpack;
            try {
                unpack = any.unpack(type);
            } catch (InvalidProtocolBufferException e) {
                throw new IllegalArgumentException("Cannot unpack error details", e);
            }
            return Optional.of((D) unpack);
        }
    }
    return Optional.empty();
}
 
Example 10
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());
	}
}
 
Example 11
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 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 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 14
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 15
Source File: CDFWRuntime.java    From twister2 with Apache License 2.0 5 votes vote down vote up
private boolean handleExecuteMessage(Any msg) {
  ISenderToDriver senderToDriver = JMWorkerAgent.getJMWorkerAgent().getDriverAgent();
  CDFWJobAPI.ExecuteMessage executeMessage;
  ExecutionPlan executionPlan;
  CDFWJobAPI.ExecuteCompletedMessage completedMessage = null;
  try {
    executeMessage = msg.unpack(CDFWJobAPI.ExecuteMessage.class);
    // get the subgraph from the map
    CDFWJobAPI.SubGraph subGraph = executeMessage.getGraph();
    ComputeGraph taskGraph = (ComputeGraph) serializer.deserialize(
        subGraph.getGraphSerialized().toByteArray());
    if (taskGraph == null) {
      LOG.severe(workerId + " Unable to find the subgraph " + subGraph.getName());
      return true;
    }

    // use the taskexecutor to create the execution plan
    executionPlan = taskExecutor.plan(taskGraph);
    taskExecutor.execute(taskGraph, executionPlan);

    //reuse the task executor execute
    completedMessage = CDFWJobAPI.ExecuteCompletedMessage.newBuilder()
        .setSubgraphName(subGraph.getName()).build();

    if (!senderToDriver.sendToDriver(completedMessage)) {
      LOG.severe("Unable to send the subgraph completed message :" + completedMessage);
    }
  } catch (InvalidProtocolBufferException e) {
    LOG.log(Level.SEVERE, "Unable to unpack received message ", e);
  }
  return false;
}
 
Example 16
Source File: ContractWrapper.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static TriggerSmartContract getTriggerContractFromTransaction(Transaction trx) {
    try {
        Any any = trx.getRawData().getContract(0).getParameter();
        TriggerSmartContract contractTriggerContract = any.unpack(TriggerSmartContract.class);
        return contractTriggerContract;
    } catch (InvalidProtocolBufferException e) {
        return null;
    }
}
 
Example 17
Source File: ContractWrapper.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static CreateSmartContract getSmartContractFromTransaction(Transaction trx) {
    try {
        Any any = trx.getRawData().getContract(0).getParameter();
        CreateSmartContract createSmartContract = any.unpack(CreateSmartContract.class);
        return createSmartContract;
    } catch (InvalidProtocolBufferException e) {
        return null;
    }
}
 
Example 18
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 19
Source File: WriteResponseImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
private void unpackP4Error(int index, Any any, boolean reconcilable) {
    final P4RuntimeOuterClass.Error p4Error;
    try {
        p4Error = any.unpack(P4RuntimeOuterClass.Error.class);
    } catch (InvalidProtocolBufferException e) {
        final String unpackErr = format(
                "P4Runtime Error message format not recognized [%s]",
                TextFormat.shortDebugString(any));
        if (reconcilable) {
            setFailure(index, unpackErr, EntityUpdateStatus.OTHER_ERROR);
        } else {
            log.warn(unpackErr);
        }
        return;
    }
    // Map gRPC status codes to our WriteResponseStatus codes.
    final Status.Code p4Code = Status.fromCodeValue(
            p4Error.getCanonicalCode()).getCode();
    final EntityUpdateStatus ourCode;
    switch (p4Code) {
        case OK:
            if (reconcilable) {
                setSuccess(index);
            }
            return;
        case NOT_FOUND:
            ourCode = EntityUpdateStatus.NOT_FOUND;
            break;
        case ALREADY_EXISTS:
            ourCode = EntityUpdateStatus.ALREADY_EXIST;
            break;
        default:
            ourCode = EntityUpdateStatus.OTHER_ERROR;
            break;
    }
    // Put the p4Code in the explanation only if ourCode is OTHER_ERROR.
    final String explanationCode = ourCode == EntityUpdateStatus.OTHER_ERROR
            ? p4Code.name() + " " : "";
    final String details = p4Error.hasDetails()
            ? ", " + p4Error.getDetails().toString() : "";
    final String explanation = format(
            "%s%s%s (%s:%d)", explanationCode, p4Error.getMessage(),
            details, p4Error.getSpace(), p4Error.getCode());
    if (reconcilable) {
        setFailure(index, explanation, ourCode);
    } else {
        log.warn("P4Runtime write error: {}", explanation);
    }
}
 
Example 20
Source File: AbstractErrorUtils.java    From google-ads-java with Apache License 2.0 2 votes vote down vote up
/**
 * Unpacks a single {@link GoogleAdsFailureT} from an {@link Any} instance.
 *
 * @throws InvalidProtocolBufferException if {@link GoogleAdsFailureT} is not able to unpack the
 *     protocol buffer. This is most likely due to using the wrong version of <code>ErrorUtils
 *     </code> being used.
 */
public GoogleAdsFailureT getGoogleAdsFailure(Any detail) throws InvalidProtocolBufferException {
  return detail.unpack(getGoogleAdsFailureClass());
}