Java 类com.google.protobuf.Any 实例源码

项目:core-java    文件:RejectionBusAdapter.java   
@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));
}
项目:curiostack    文件:WellKnownTypeMarshaller.java   
@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();
}
项目:curiostack    文件:MessageMarshallerTest.java   
@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());
}
项目:bazel-buildfarm    文件:MemoryInstance.java   
@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();
}
项目:bazel-buildfarm    文件:StubInstance.java   
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
  }
}
项目:todo-list    文件:TodoListEnrichmentsTest.java   
@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()));
}
项目:todo-list    文件:TodoListEnrichmentsTest.java   
@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()));
}
项目:api-compiler    文件:TextFormatForTest.java   
/**
 * 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;
}
项目:core-java    文件:StandShould.java   
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());
        }
    };
}
项目:core-java    文件:QueryBuilder.java   
@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;
}
项目:core-java    文件:TopicFactoryShould.java   
@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));
    }
}
项目:core-java    文件:QueryBuilderShould.java   
@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);
}
项目:seldon-server    文件:ClientRPCStoreTest.java   
@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);
}
项目:core-java    文件:HandlerMethod.java   
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;
        }
    });
}
项目:core-java    文件:EntityQueryMatcherShould.java   
@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));
}
项目:core-java    文件:IteratingCommandRouter.java   
/**
 * 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();
}
项目:core-java    文件:Field.java   
/**
 * 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);
}
项目:core-java    文件:EntityQueryMatcher.java   
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;
}
项目:core-java    文件:TenantRecords.java   
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;
}
项目:core-java    文件:EntityQueryProcessor.java   
@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;
}
项目:core-java    文件:Stand.java   
/**
 * Reads a particular set of items from the read-side of the application and
 * feed the result into an instance.
 *
 * <p>{@link Query} defines the query target and the expected detail level for response.
 *
 * <p>The query results are fed to an instance
 * of {@link StreamObserver}&lt;{@link QueryResponse}&gt;.
 *
 * @param query            an instance of query
 * @param responseObserver an observer to feed the query results to.
 */
public void execute(final Query query,
                    final StreamObserver<QueryResponse> responseObserver) {
    queryValidator.validate(query, responseObserver);

    final TypeUrl type = Queries.typeOf(query);
    final QueryProcessor queryProcessor = processorFor(type);

    final QueryOperation op = new QueryOperation(query) {
        @Override
        public void run() {
            final ImmutableCollection<Any> readResult = queryProcessor.process(query());
            final QueryResponse response = QueryResponse.newBuilder()
                                                        .addAllMessages(readResult)
                                                        .setResponse(Responses.ok())
                                                        .build();
            responseObserver.onNext(response);
            responseObserver.onCompleted();
        }
    };
    op.execute();
}
项目:core-java    文件:Stand.java   
/**
 * Creates the subscribers notification action.
 *
 * <p>The resulting action retrieves the {@linkplain EntityUpdateCallback subscriber callback}
 * and invokes it with the given Entity ID and state.
 *
 * @param subscriptionRecord the attributes of the target subscription
 * @param id                 the ID of the updated Entity
 * @param entityState        the new state of the updated Entity
 * @return a routine delivering the subscription update to the target subscriber
 */
private static Runnable notifySubscriptionAction(final SubscriptionRecord subscriptionRecord,
                                                 final Object id, final Any entityState) {
    final Runnable result = new Runnable() {
        @Override
        public void run() {
            final EntityUpdateCallback callback = subscriptionRecord.getCallback();
            checkNotNull(callback, "Notifying by a non-activated subscription.");
            final Any entityId = toAny(id);
            final EntityStateUpdate stateUpdate = EntityStateUpdate.newBuilder()
                                                                   .setId(entityId)
                                                                   .setState(entityState)
                                                                   .build();
            callback.onStateChanged(stateUpdate);
        }
    };
    return result;
}
项目:core-java    文件:ProjectionStorageShould.java   
@SuppressWarnings("MethodWithMultipleLoops")
@Test
public void read_all_messages_with_field_mask() {
    final List<ProjectId> ids = fillStorage(5);

    final String projectDescriptor = Project.getDescriptor()
                                            .getFullName();
    @SuppressWarnings("DuplicateStringLiteralInspection")       // clashes with non-related tests.
    final FieldMask fieldMask = maskForPaths(projectDescriptor + ".id", projectDescriptor + ".name");

    final Iterator<EntityRecord> read = storage.readAll(fieldMask);
    final Collection<EntityRecord> readRecords = newArrayList(read);
    assertSize(ids.size(), readRecords);
    for (EntityRecord record : readRecords) {
        final Any packedState = record.getState();
        final Project state = AnyPacker.unpack(packedState);
        assertMatchesMask(state, fieldMask);
    }
}
项目:core-java    文件:ProjectionStorageShould.java   
@SuppressWarnings("ConstantConditions") // Converter nullability issues
private List<ProjectId> fillStorage(int count) {
    final List<ProjectId> ids = new LinkedList<>();

    for (int i = 0; i < count; i++) {
        final ProjectId id = newId();
        final Project state = Given.project(id, format("project-%d", i));
        final Any packedState = AnyPacker.pack(state);

        final EntityRecord record = EntityRecord.newBuilder()
                                                .setState(packedState)
                                                .setVersion(
                                                        GivenVersion.withNumber(1))
                                                .build();
        storage.write(id, record);
        ids.add(id);
    }

    return ids;
}
项目:core-java    文件:ProjectionStorageShould.java   
@SuppressWarnings("BreakStatement")
private static Project checkProjectIdIsInList(EntityRecord project, List<ProjectId> ids) {
    final Any packedState = project.getState();
    final Project state = AnyPacker.unpack(packedState);
    final ProjectId id = state.getId();

    boolean isIdPresent = false;
    for (ProjectId genericId : ids) {
        isIdPresent = genericId.equals(id);
        if (isIdPresent) {
            break;
        }
    }
    assertTrue(isIdPresent);

    return state;
}
项目:core-java    文件:StandShould.java   
@Test
public void trigger_subscription_callback_upon_update_of_projection() {
    final Stand stand = prepareStandWithAggregateRepo(mock(StandStorage.class));
    final Topic allProjects = requestFactory.topic().allOf(Project.class);

    final MemoizeEntityUpdateCallback memoizeCallback = new MemoizeEntityUpdateCallback();
    subscribeAndActivate(stand, allProjects, memoizeCallback);
    assertNull(memoizeCallback.newEntityState);

    final Map.Entry<ProjectId, Project> sampleData = fillSampleProjects(1).entrySet()
                                                                          .iterator()
                                                                          .next();
    final ProjectId projectId = sampleData.getKey();
    final Project project = sampleData.getValue();
    final Version stateVersion = GivenVersion.withNumber(1);
    stand.update(asEnvelope(projectId, project, stateVersion));

    final Any packedState = AnyPacker.pack(project);
    assertEquals(packedState, memoizeCallback.newEntityState);
}
项目:core-java    文件:AggregateStorageShould.java   
@Test
public void not_store_enrichment_for_origin_of_RejectionContext_type() {
    final RejectionContext origin = RejectionContext.newBuilder()
                                                    .setEnrichment(withOneAttribute())
                                                    .build();
    final EventContext context = EventContext.newBuilder()
                                             .setRejectionContext(origin)
                                             .build();
    final Event event = Event.newBuilder()
                             .setId(newEventId())
                             .setContext(context)
                             .setMessage(Any.getDefaultInstance())
                             .build();
    storage.writeEvent(id, event);
    final RejectionContext loadedOrigin = storage.read(newReadRequest(id))
                                                 .get()
                                                 .getEvent(0)
                                                 .getContext()
                                                 .getRejectionContext();
    assertTrue(isDefault(loadedOrigin.getEnrichment()));
}
项目:core-java    文件:BoundedContextShould.java   
@Test
public void not_notify_integration_event_subscriber_if_event_is_invalid() {
    final BoundedContext boundedContext = BoundedContext.newBuilder()
                                                        .setMultitenant(true)
                                                        .build();

    // Unsupported message.
    final Any invalidMsg = AnyPacker.pack(BcProjectCreated.getDefaultInstance());
    final IntegrationEvent event =
            Given.AnIntegrationEvent.projectCreated()
                                    .toBuilder()
                                    .setMessage(invalidMsg)
                                    .build();

    final MemoizingObserver<Ack> observer = memoizingObserver();
    boundedContext.notify(event, observer);

    assertEquals(ERROR, observer.firstResponse().getStatus().getStatusCase());
}
项目:core-java    文件:StandShould.java   
@Test
public void retrieve_collection_fields_if_required() {
    requestSampleCustomer(
            new int[]{Customer.NICKNAMES_FIELD_NUMBER - 1},
            new MemoizeQueryResponseObserver() {
                @Override
                public void onNext(QueryResponse value) {
                    super.onNext(value);

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

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

                    assertFalse(customer.hasName());
                    assertFalse(customer.hasId());
                }
            }
    );
}
项目:core-java    文件:ERepositoryShould.java   
@Test
public void convert_type_query_to_EntityFilters() {
    final String typeName = " com.example.EventType ";
    final EventFilter validFilter = filterForType(typeName);
    final EventFilter invalidFilter = filterForType("   ");
    final EventStreamQuery query = EventStreamQuery.newBuilder()
                                                   .addFilter(validFilter)
                                                   .addFilter(invalidFilter)
                                                   .build();
    final EntityFilters entityFilters = toEntityFilters(query);
    assertEquals(1, entityFilters.getFilterCount());

    final CompositeColumnFilter compositeFilter = entityFilters.getFilter(0);
    final List<ColumnFilter> columnFilters = compositeFilter.getFilterList();
    assertEquals(CompositeOperator.EITHER, compositeFilter.getOperator());
    assertEquals(1, columnFilters.size());
    final Any typeNameAsAny = columnFilters.get(0)
                                           .getValue();
    assertEquals(typeName, toObject(typeNameAsAny, String.class));
}
项目:core-java    文件:StandShould.java   
@Test
public void retrieve_all_requested_fields() {
    requestSampleCustomer(
            new int[]{ Customer.NICKNAMES_FIELD_NUMBER - 1,
                    Customer.ID_FIELD_NUMBER - 1 },
            new MemoizeQueryResponseObserver() {
                @Override
                public void onNext(QueryResponse value) {
                    super.onNext(value);

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

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

                    assertFalse(customer.hasName());
                    assertTrue(customer.hasId());
                }
            }
    );
}
项目:core-java    文件:IteratingCommandRouterShould.java   
@Test
public void return_CommandRouted_from_routeFirst() throws Exception {
    final CommandRouted commandRouted = router().routeFirst();

    assertSource(commandRouted);

    // Test that only only one command was produced by `routeFirst()`.
    assertEquals(1, commandRouted.getProducedCount());

    // Test that there's only one produced command and it has correct message.
    final Command produced = commandRouted.getProduced(0);
    final StringValue commandMessage = Commands.getMessage(produced);
    assertEquals(messages().get(0), commandMessage);

    assertActorAndTenant(produced);

    // Test that the event contains messages to follow.
    assertEquals(messages().size() - 1, commandRouted.getMessageToFollowCount());

    final List<Any> messageToFollow = commandRouted.getMessageToFollowList();
    assertArrayEquals(messages().subList(1, messages().size()).toArray(),
                      unpackAll(messageToFollow).toArray());
}
项目:curiostack    文件:WellKnownTypeMarshaller.java   
@Override
public void doMerge(JsonParser parser, int currentDepth, Message.Builder messageBuilder)
    throws IOException {
  JsonToken token = parser.nextValue();
  if (token == JsonToken.END_OBJECT) {
    return;
  }
  Any.Builder builder = (Any.Builder) messageBuilder;
  if (!parser.getCurrentName().equals("@type")) {
    throw new InvalidProtocolBufferException(
        "MessageMarshaller requires @type to must be the "
            + "first field of an Any. If you need to support @type in any location, use "
            + "upstream JsonFormat. Found: "
            + parser.getText());
  }
  String typeUrl = ParseSupport.parseString(parser);
  TypeSpecificMarshaller<?> contentMarshaller = marshallerRegistry.findByTypeUrl(typeUrl);
  builder.setTypeUrl(typeUrl);
  if (contentMarshaller instanceof WellKnownTypeMarshaller) {
    parser.nextValue();
    if (parser.getCurrentName().equals("value")) {
      builder.setValue(contentMarshaller.readValue(parser, currentDepth).toByteString());
    }
    // Well-known types will not finish parsing the current object (they don't readValue
    // objects),
    // so we close it here.
    if (parser.nextValue() != JsonToken.END_OBJECT) {
      throw new InvalidProtocolBufferException(
          "Expected end of object, got: " + parser.getText());
    }
  } else {
    builder.setValue(
        contentMarshaller
            .parseRemainingFieldsOfObjectAsMessage(parser, currentDepth + 1)
            .toByteString());
  }
}
项目:curiostack    文件:MessageMarshallerTest.java   
@Test
public void parserUnexpectedTypeUrl() throws Exception {
  Any.Builder builder = Any.newBuilder();
  assertThatThrownBy(
          () ->
              mergeFromJson(
                  "{\n"
                      + "  \"@type\": \"type.googleapis.com/json_test.TestAllTypes\",\n"
                      + "  \"optionalInt32\": 12345\n"
                      + "}",
                  builder))
      .isInstanceOf(InvalidProtocolBufferException.class);
}
项目:curiostack    文件:MessageMarshallerTest.java   
@Test
public void emptyWrapperTypesInAny() throws Exception {
  Any.Builder builder = Any.newBuilder();
  mergeFromJson(
      "{\n"
          + "  \"@type\": \"type.googleapis.com/google.protobuf.BoolValue\",\n"
          + "  \"value\": false\n"
          + "}\n",
      builder,
      TestAllTypes.getDefaultInstance());
  Any any = builder.build();
  assertEquals(0, any.getValue().size());
}
项目:bazel-buildfarm    文件:AbstractServerInstance.java   
protected void expireOperation(Operation operation) {
  Action action = expectAction(operation);
  Digest actionDigest = Digests.computeDigest(action);
  // one last chance to get partial information from worker
  ActionResult actionResult = action.getDoNotCache()
      ? null
      : getActionResult(actionDigest);
  boolean cachedResult = actionResult != null;
  if (!cachedResult) {
    actionResult = ActionResult.newBuilder()
        .setExitCode(-1)
        .setStderrRaw(ByteString.copyFromUtf8(
            "[BUILDFARM]: Action timed out with no response from worker"))
        .build();
    if (!action.getDoNotCache()) {
      putActionResult(actionDigest, actionResult);
    }
  }
  putOperation(operation.newBuilder()
      .setDone(true)
      .setMetadata(Any.pack(ExecuteOperationMetadata.newBuilder()
          .setStage(ExecuteOperationMetadata.Stage.COMPLETED)
          .build()))
      .setResponse(Any.pack(ExecuteResponse.newBuilder()
          .setResult(actionResult)
          .setCachedResult(cachedResult)
          .build()))
      .build());
}
项目:todo-list    文件:TodoClientImpl.java   
@Override
public MyListView getMyListView() {
    final Query query = requestFactory.query()
                                      .all(MyListView.class);
    final List<Any> messages = queryService.read(query)
                                           .getMessagesList();
    return messages.isEmpty()
           ? MyListView.getDefaultInstance()
           : AnyPacker.unpack(messages.get(0));
}
项目:todo-list    文件:TodoClientImpl.java   
@Override
public List<LabelledTasksView> getLabelledTasksView() {
    final Query query = requestFactory.query()
                                      .all(LabelledTasksView.class);
    final List<Any> messages = queryService.read(query)
                                           .getMessagesList();
    final List<LabelledTasksView> result = messages
            .stream()
            .map(AnyPacker::<LabelledTasksView>unpack)
            .collect(toList());

    return result;
}
项目:todo-list    文件:TodoClientImpl.java   
@Override
public DraftTasksView getDraftTasksView() {
    final Query query = requestFactory.query()
                                      .all(DraftTasksView.class);
    final List<Any> messages = queryService.read(query)
                                           .getMessagesList();
    return messages.isEmpty()
           ? DraftTasksView.getDefaultInstance()
           : AnyPacker.unpack(messages.get(0));
}
项目:todo-list    文件:TodoClientImpl.java   
/**
 * Retrieves all the messages of the given type.
 *
 * @param cls the class of the desired messages
 * @param <M> the compile-time type of the desired messages
 * @return all the messages of the given type present in the system
 */
private <M extends Message> List<M> getByType(Class<M> cls) {
    final Query query = requestFactory.query()
                                      .all(cls);
    final List<Any> messages = queryService.read(query)
                                           .getMessagesList();
    final List<M> result = messages.stream()
                                   .map(AnyPacker::<M>unpack)
                                   .collect(toList());
    return result;
}