com.google.protobuf.Any#unpack ( )源码实例Demo

下面列出了com.google.protobuf.Any#unpack ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: burstkit4j   文件: TransactionAppendix.java
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;
    }
}
 
源代码2 项目: burstkit4j   文件: TransactionAttachment.java
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;
    }
}
 
源代码3 项目: JavaInterview   文件: GrpcClient.java
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());
        }


    }
}
 
源代码4 项目: twister2   文件: DefaultDriver.java
@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);
  }
}
 
源代码5 项目: jprotobuf   文件: AnyTest.java
/**
 * 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());
        }
    }
}
 
源代码6 项目: bazel-buildfarm   文件: Actions.java
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
}
 
源代码7 项目: conductor   文件: JsonMapperProviderTest.java
@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()
    );
}
 
源代码8 项目: jprotobuf   文件: AnyTest.java
/**
 * 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());
        }
    }
}
 
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);
  }
}
 
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);
  }
}
 
源代码11 项目: gsc-core   文件: ContractWrapper.java
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;
    }
}
 
源代码12 项目: gsc-core   文件: ContractWrapper.java
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;
    }
}
 
源代码13 项目: twister2   文件: CDFWRuntime.java
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;
}
 
源代码14 项目: titus-control-plane   文件: GrpcClientErrorUtils.java
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();
}
 
源代码15 项目: bazel-buildfarm   文件: AbstractServerInstance.java
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;
}
 
源代码16 项目: bazel-buildfarm   文件: AbstractServerInstance.java
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;
}
 
源代码17 项目: bazel-buildfarm   文件: AbstractServerInstance.java
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;
}
 
源代码18 项目: protobuf-converter   文件: ProtobufClient.java
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());
	}
}
 
源代码19 项目: onos   文件: WriteResponseImpl.java
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);
    }
}
 
源代码20 项目: google-ads-java   文件: AbstractErrorUtils.java
/**
 * 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());
}