• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java Any类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中com.google.protobuf.Any的典型用法代码示例。如果您正苦于以下问题:Java Any类的具体用法?Java Any怎么用?Java Any使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Any类属于com.google.protobuf包,在下文中一共展示了Any类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: markExternal

import com.google.protobuf.Any; //导入依赖的package包/类
@Override
ExternalMessageEnvelope markExternal(ExternalMessage externalMsg) {
    final Any packedEvent = externalMsg.getOriginalMessage();
    final Rejection rejection = AnyPacker.unpack(packedEvent);
    final Rejection.Builder rejectionBuilder = rejection.toBuilder();
    final RejectionContext modifiedContext = rejectionBuilder.getContext()
                                                             .toBuilder()
                                                             .setExternal(true)
                                                             .build();

    final Rejection marked = rejectionBuilder.setContext(modifiedContext)
                                             .build();
    final ExternalMessage result = ExternalMessages.of(marked,
                                                       externalMsg.getBoundedContextName());
    return ExternalMessageEnvelope.of(result, Rejections.getMessage(rejection));
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:17,代码来源:RejectionBusAdapter.java


示例2: writeValue

import com.google.protobuf.Any; //导入依赖的package包/类
@Override
public void writeValue(Any message, JsonGenerator gen) throws IOException {
  if (message.equals(Any.getDefaultInstance())) {
    // Note: empty Any is not indented the same way as an empty message, this is likely an
    // upstream bug.
    gen.writeRaw(": {}");
    return;
  }
  gen.writeStartObject();
  String typeUrl = message.getTypeUrl();
  TypeSpecificMarshaller<?> serializer = marshallerRegistry.findByTypeUrl(typeUrl);
  gen.writeFieldName("@type");
  gen.writeString(typeUrl);
  if (serializer instanceof WellKnownTypeMarshaller) {
    gen.writeFieldName("value");
    serializer.writeValue(message.getValue(), gen);
  } else {
    serializer.doWrite(message.getValue(), gen);
  }
  gen.writeEndObject();
}
 
开发者ID:curioswitch,项目名称:curiostack,代码行数:22,代码来源:WellKnownTypeMarshaller.java


示例3: anyInMaps

import com.google.protobuf.Any; //导入依赖的package包/类
@Test
public void anyInMaps() throws Exception {
  TestAny.Builder testAny = TestAny.newBuilder();
  testAny.putAnyMap("int32_wrapper", Any.pack(Int32Value.newBuilder().setValue(123).build()));
  testAny.putAnyMap("int64_wrapper", Any.pack(Int64Value.newBuilder().setValue(456).build()));
  testAny.putAnyMap("timestamp", Any.pack(Timestamps.parse("1969-12-31T23:59:59Z")));
  testAny.putAnyMap("duration", Any.pack(Durations.parse("12345.1s")));
  testAny.putAnyMap("field_mask", Any.pack(FieldMaskUtil.fromString("foo.bar,baz")));
  Value numberValue = Value.newBuilder().setNumberValue(1.125).build();
  Struct.Builder struct = Struct.newBuilder();
  struct.putFields("number", numberValue);
  testAny.putAnyMap("struct", Any.pack(struct.build()));
  Value nullValue = Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build();
  testAny.putAnyMap(
      "list_value",
      Any.pack(ListValue.newBuilder().addValues(numberValue).addValues(nullValue).build()));
  testAny.putAnyMap("number_value", Any.pack(numberValue));
  testAny.putAnyMap("any_value_number", Any.pack(Any.pack(numberValue)));
  testAny.putAnyMap("any_value_default", Any.pack(Any.getDefaultInstance()));
  testAny.putAnyMap("default", Any.getDefaultInstance());

  assertMatchesUpstream(testAny.build(), TestAllTypes.getDefaultInstance());
}
 
开发者ID:curioswitch,项目名称:curiostack,代码行数:24,代码来源:MessageMarshallerTest.java


示例4: createOperation

import com.google.protobuf.Any; //导入依赖的package包/类
@Override
protected Operation createOperation(Action action) {
  String name = createOperationName(UUID.randomUUID().toString());

  watchers.put(name, new ArrayList<Function<Operation, Boolean>>());

  Digest actionDigest = Digests.computeDigest(action.toByteString());

  ExecuteOperationMetadata metadata = ExecuteOperationMetadata.newBuilder()
      .setActionDigest(actionDigest)
      .build();

  Operation.Builder operationBuilder = Operation.newBuilder()
      .setName(name)
      .setDone(false)
      .setMetadata(Any.pack(metadata));

  return operationBuilder.build();
}
 
开发者ID:bazelbuild,项目名称:bazel-buildfarm,代码行数:20,代码来源:MemoryInstance.java


示例5: requeue

import com.google.protobuf.Any; //导入依赖的package包/类
private void requeue(Operation operation) {
  try {
    ExecuteOperationMetadata metadata =
        operation.getMetadata().unpack(ExecuteOperationMetadata.class);

    ExecuteOperationMetadata executingMetadata = metadata.toBuilder()
        .setStage(ExecuteOperationMetadata.Stage.QUEUED)
        .build();

    operation = operation.toBuilder()
        .setMetadata(Any.pack(executingMetadata))
        .build();
    putOperation(operation);
  } catch(InvalidProtocolBufferException ex) {
    // operation is dropped on the floor
  }
}
 
开发者ID:bazelbuild,项目名称:bazel-buildfarm,代码行数:18,代码来源:StubInstance.java


示例6: enricherDefaultsTest

import com.google.protobuf.Any; //导入依赖的package包/类
@Test
@DisplayName("create EventEnricher that defaults absent Task or TaskLabels to default message")
void enricherDefaultsTest() {
    final TaskDraftFinalized eventMsg = TaskDraftFinalized.newBuilder()
                                                          .setTaskId(randomTaskId())
                                                          .build();
    final EventEnvelope envelope = enricher.enrich(of(event(eventMsg)));
    final EventEnvelope enriched = enricher.enrich(envelope);
    final Enrichment enrichment = enriched.getEnrichment();

    final TypeName labelsEnrName = TypeName.from(LabelsListEnrichment.getDescriptor());
    final Any labelIds = enrichment.getContainer()
                                   .getItemsMap()
                                   .get(labelsEnrName.value());
    final LabelsListEnrichment labelIdsEnr = unpack(labelIds);
    assertTrue(labelIdsEnr.getLabelIdsList().getIdsList().isEmpty());

    final TypeName taskTypeName = TypeName.from(TaskEnrichment.getDescriptor());
    final Any task = enrichment.getContainer()
                               .getItemsMap()
                               .get(taskTypeName.value());
    final TaskEnrichment taskEnr = unpack(task);
    assertTrue(isDefault(taskEnr.getTask()));
}
 
开发者ID:SpineEventEngine,项目名称:todo-list,代码行数:25,代码来源:TodoListEnrichmentsTest.java


示例7: moreEnricherDefaultsTest

import com.google.protobuf.Any; //导入依赖的package包/类
@Test
@DisplayName("create EventEnricher that defaults absent Label to default message")
void moreEnricherDefaultsTest() {
    final LabelledTaskRestored eventMsg = LabelledTaskRestored.newBuilder()
                                                              .setLabelId(randomLabelId())
                                                              .build();
    final EventEnvelope envelope = enricher.enrich(of(event(eventMsg)));
    final EventEnvelope enriched = enricher.enrich(envelope);
    final Enrichment enrichment = enriched.getEnrichment();

    final TypeName enrTypeName = TypeName.from(DetailsEnrichment.getDescriptor());
    final Any packerEnr = enrichment.getContainer()
                                   .getItemsMap()
                                   .get(enrTypeName.value());
    final DetailsEnrichment enr = unpack(packerEnr);
    assertTrue(isDefault(enr.getLabelDetails()));
    assertTrue(isDefault(enr.getTaskDetails()));
}
 
开发者ID:SpineEventEngine,项目名称:todo-list,代码行数:19,代码来源:TodoListEnrichmentsTest.java


示例8: maybeUnpackAnyType

import com.google.protobuf.Any; //导入依赖的package包/类
/**
 * Attempt to unpack if its an any instance. Returns null if not unpacked.
 */
@Nullable private Message maybeUnpackAnyType(FieldDescriptor field, Object value) {
  if (field.getType() == FieldDescriptor.Type.MESSAGE
      && field.getMessageType().getFullName().equals(Any.getDescriptor().getFullName())) {
    Any any = (Any) value;
    Message defaultInstance = anyConverterRegistry.get(any.getTypeUrl());
    if (defaultInstance != null) {
      try {
        return defaultInstance.toBuilder().mergeFrom(any.getValue()).build();
      } catch (InvalidProtocolBufferException e) {
        throw new RuntimeException(e);
      }
    }
  }
  return null;
}
 
开发者ID:googleapis,项目名称:api-compiler,代码行数:19,代码来源:TextFormatForTest.java


示例9: getDuplicateCostumerStreamObserver

import com.google.protobuf.Any; //导入依赖的package包/类
private static MemoizeQueryResponseObserver getDuplicateCostumerStreamObserver() {
    return new MemoizeQueryResponseObserver() {
        @Override
        public void onNext(QueryResponse value) {
            super.onNext(value);

            final List<Any> messages = value.getMessagesList();
            assertFalse(messages.isEmpty());

            final Customer customer = unpack(messages.get(0));
            final Customer sampleCustomer = getSampleCustomer();

            assertEquals(sampleCustomer.getName(), customer.getName());
            assertEquals(sampleCustomer.getNicknamesList(), customer.getNicknamesList());
            assertTrue(customer.hasId());
        }
    };
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:19,代码来源:StandShould.java


示例10: composeIdPredicate

import com.google.protobuf.Any; //导入依赖的package包/类
@Nullable
private Set<Any> composeIdPredicate() {
    if (ids == null || ids.isEmpty()) {
        return null;
    }
    final Collection<Any> entityIds = transform(ids, new Function<Object, Any>() {
        @Nullable
        @Override
        public Any apply(@Nullable Object o) {
            checkNotNull(o);
            final Any id = Identifier.pack(o);
            return id;
        }
    });
    final Set<Any> result = newHashSet(entityIds);
    return result;
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:18,代码来源:QueryBuilder.java


示例11: create_topic_for_some_entities_of_kind

import com.google.protobuf.Any; //导入依赖的package包/类
@Test
public void create_topic_for_some_entities_of_kind() {

    final Set<TestEntityId> ids = newHashSet(entityId(1), entityId(2),
                                             entityId(3));
    final Topic topic = factory().topic().someOf(TARGET_ENTITY_CLASS, ids);

    verifyTargetAndContext(topic);

    final List<EntityId> actualIds = topic.getTarget()
                                          .getFilters()
                                          .getIdFilter()
                                          .getIdsList();
    assertEquals(ids.size(), actualIds.size());
    for (EntityId actualId : actualIds) {
        final Any rawId = actualId.getId();
        final TestEntityId unpackedId = AnyPacker.unpack(rawId);
        assertTrue(ids.contains(unpackedId));
    }
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:21,代码来源:TopicFactoryShould.java


示例12: create_queries_with_param

import com.google.protobuf.Any; //导入依赖的package包/类
@Test
public void create_queries_with_param() {
    final String columnName = "myImaginaryColumn";
    final Object columnValue = 42;

    final Query query = factory().query()
                                 .select(TestEntity.class)
                                 .where(eq(columnName, columnValue))
                                 .build();
    assertNotNull(query);
    final Target target = query.getTarget();
    assertFalse(target.getIncludeAll());

    final EntityFilters entityFilters = target.getFilters();
    final List<CompositeColumnFilter> aggregatingColumnFilters = entityFilters.getFilterList();
    assertSize(1, aggregatingColumnFilters);
    final CompositeColumnFilter aggregatingColumnFilter = aggregatingColumnFilters.get(0);
    final Collection<ColumnFilter> columnFilters = aggregatingColumnFilter.getFilterList();
    assertSize(1, columnFilters);
    final Any actualValue = findByName(columnFilters, columnName).getValue();
    assertNotNull(columnValue);
    final Int32Value messageValue = AnyPacker.unpack(actualValue);
    final int actualGenericValue = messageValue.getValue();
    assertEquals(columnValue, actualGenericValue);
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:26,代码来源:QueryBuilderShould.java


示例13: testRequestToJSON

import com.google.protobuf.Any; //导入依赖的package包/类
@Test 
public void testRequestToJSON() throws JsonParseException, IOException, NoSuchMethodException, SecurityException
{
	mockClientConfigHandler.addListener((ClientConfigUpdateListener) EasyMock.anyObject());
	EasyMock.expectLastCall().once();
	replay(mockClientConfigHandler);
	final String client = "test";
	ClientRpcStore store = new ClientRpcStore(mockClientConfigHandler);
	CustomPredictRequest customRequest =  CustomPredictRequest.newBuilder().addData(1.0f).build();
	store.add(client, customRequest.getClass(), null,customRequest.getClass().getMethod("newBuilder"),null);
	Any anyMsg = Any.pack(customRequest);
	ClassificationRequestMeta meta = ClassificationRequestMeta.newBuilder().setPuid("1234").build();
	ClassificationRequest request = ClassificationRequest.newBuilder().setMeta(meta).setData(anyMsg).build();
	JsonNode json = store.getJSONForRequest(client, request);
	Assert.assertNotNull(json);
	System.out.println(json);
	ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser parser = factory.createParser(json.toString());
    JsonNode actualObj = mapper.readTree(parser);
    ClassificationRequest req = store.getPredictRequestFromJson(client, actualObj);
    Assert.assertNotNull(req);
}
 
开发者ID:SeldonIO,项目名称:seldon-server,代码行数:24,代码来源:ClientRPCStoreTest.java


示例14: toEvents

import com.google.protobuf.Any; //导入依赖的package包/类
public static List<Event> toEvents(final Any producerId,
                                   @Nullable final Version version,
                                   final List<? extends Message> eventMessages,
                                   final MessageEnvelope origin) {
    checkNotNull(producerId);
    checkNotNull(eventMessages);
    checkNotNull(origin);

    final EventFactory eventFactory =
            EventFactory.on(origin, producerId);

    return Lists.transform(eventMessages, new Function<Message, Event>() {
        @Override
        public Event apply(@Nullable Message eventMessage) {
            checkNotNull(eventMessage);
            final Event result = eventFactory.createEvent(eventMessage, version);
            return result;
        }
    });
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:21,代码来源:HandlerMethod.java


示例15: not_match_by_wrong_field_name

import com.google.protobuf.Any; //导入依赖的package包/类
@Test
public void not_match_by_wrong_field_name() {
    final String wrongName = "wrong";
    final EntityColumn target = mock(EntityColumn.class);

    final Multimap<EntityColumn, ColumnFilter> filters = of(target,
                                                            eq(wrongName, "any"));
    final CompositeQueryParameter parameter = createParams(filters, EITHER);
    final QueryParameters params = QueryParameters.newBuilder()
                                                  .add(parameter)
                                                  .build();
    final EntityQuery<?> query = createQuery(Collections.emptyList(), params);
    final EntityQueryMatcher<?> matcher = new EntityQueryMatcher<>(query);

    final EntityRecord record = EntityRecord.newBuilder()
                                            .setEntityId(Any.getDefaultInstance())
                                            .build();
    final EntityRecordWithColumns recordWithColumns = of(record);
    assertFalse(matcher.apply(recordWithColumns));
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:21,代码来源:EntityQueryMatcherShould.java


示例16: routeFirst

import com.google.protobuf.Any; //导入依赖的package包/类
/**
 * Routes the first of the messages and returns the message
 * to be associated with the source command.
 *
 * <p>The rest of the messages are stored and those to follow.
 *
 * @return {@code CommandRouted} message with
 * <ul>
 *     <li>the source command,
 *     <li>the first produced command,
 *     <li>the command messages for the commands that will be posted by the router later
 * </ul>
 * @see CommandRouted#getMessageToFollowList()
 */
protected CommandRouted routeFirst() {
    final CommandRouted.Builder result = CommandRouted.newBuilder();
    result.setSource(getSource());

    final Message message = next();
    final Command command = route(message);
    result.addProduced(command);

    final Iterable<Any> iterable = new Iterable<Any>() {
        @Override
        public Iterator<Any> iterator() {
            return AnyPacker.pack(commandMessages());
        }
    };
    result.addAllMessageToFollow(iterable);

    return result.build();
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:33,代码来源:IteratingCommandRouter.java


示例17: getValue

import com.google.protobuf.Any; //导入依赖的package包/类
/**
 * Obtains the value of the field in the passed object.
 *
 * <p>If the corresponding field is of type {@code Any} it will be unpacked.
 *
 * @return field value or unpacked field value, or
 *         {@code Optional.absent()} if the field is a default {@code Any}
 * @throws IllegalStateException if getting the field value caused an exception.
 *                               The root cause will be available from the thrown instance.
 */
public Optional<Message> getValue(Message object) {
    final Message fieldValue;
    final Message result;
    try {
        fieldValue = (Message) getter.invoke(object);
        if (fieldValue instanceof Any) {
            final Any any = (Any)fieldValue;
            if (isDefault(any)) {
                return Optional.absent();
            }
            result = AnyPacker.unpack(any);
        } else {
            result = fieldValue;
        }
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw illegalStateWithCauseOf(e);
    }

    return Optional.fromNullable(result);
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:31,代码来源:Field.java


示例18: checkSingleParameter

import com.google.protobuf.Any; //导入依赖的package包/类
private static boolean checkSingleParameter(ColumnFilter filter,
                                            @Nullable MemoizedValue actualValue) {
    if (actualValue == null) {
        return false;
    }
    final Object value;
    final Any wrappedValue = filter.getValue();
    final Class<?> sourceClass = actualValue.getSourceColumn()
                                            .getType();
    if (sourceClass != Any.class) {
        value = toObject(wrappedValue, sourceClass);
    } else {
        value = wrappedValue;
    }
    final boolean result = eval(actualValue.getValue(), filter.getOperator(), value);
    return result;
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:18,代码来源:EntityQueryMatcher.java


示例19: findAndApplyFieldMask

import com.google.protobuf.Any; //导入依赖的package包/类
EntityRecord findAndApplyFieldMask(I givenId, FieldMask fieldMask) {
    EntityRecord matchingResult = null;
    for (I recordId : filtered.keySet()) {
        if (recordId.equals(givenId)) {
            final Optional<EntityRecordWithColumns> record = get(recordId);
            if (!record.isPresent()) {
                continue;
            }
            EntityRecord.Builder matchingRecord = record.get()
                                                        .getRecord()
                                                        .toBuilder();
            final Any state = matchingRecord.getState();
            final TypeUrl typeUrl = TypeUrl.parse(state.getTypeUrl());
            final Message wholeState = unpack(state);
            final Message maskedState = applyMask(fieldMask, wholeState, typeUrl);
            final Any processed = pack(maskedState);

            matchingRecord.setState(processed);
            matchingResult = matchingRecord.build();
        }
    }
    return matchingResult;
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:24,代码来源:TenantRecords.java


示例20: process

import com.google.protobuf.Any; //导入依赖的package包/类
@Override
public ImmutableCollection<Any> process(Query query) {
    final ImmutableList.Builder<Any> resultBuilder = ImmutableList.builder();

    final Target target = query.getTarget();
    final FieldMask fieldMask = query.getFieldMask();

    final Iterator<? extends Entity> entities;
    if (target.getIncludeAll() && fieldMask.getPathsList()
                                           .isEmpty()) {
        entities = repository.loadAll();
    } else {
        final EntityFilters filters = target.getFilters();
        entities = repository.find(filters, fieldMask);
    }
    while (entities.hasNext()) {
        final Entity entity = entities.next();
        final Message state = entity.getState();
        final Any packedState = AnyPacker.pack(state);
        resultBuilder.add(packedState);
    }
    final ImmutableList<Any> result = resultBuilder.build();
    return result;
}
 
开发者ID:SpineEventEngine,项目名称:core-java,代码行数:25,代码来源:EntityQueryProcessor.java



注:本文中的com.google.protobuf.Any类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java TextDelimited类代码示例发布时间:2022-05-21
下一篇:
Java Property类代码示例发布时间:2022-05-21
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap