@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()); }
/** * Cloud Datastore system tables with statistics are periodically updated. This method fetches * the latest timestamp (in microseconds) of statistics update using the {@code __Stat_Total__} * table. */ private static long queryLatestStatisticsTimestamp(Datastore datastore, @Nullable String namespace) throws DatastoreException { Query.Builder query = Query.newBuilder(); // Note: namespace either being null or empty represents the default namespace, in which // case we treat it as not provided by the user. if (Strings.isNullOrEmpty(namespace)) { query.addKindBuilder().setName("__Stat_Total__"); } else { query.addKindBuilder().setName("__Stat_Ns_Total__"); } query.addOrder(makeOrder("timestamp", DESCENDING)); query.setLimit(Int32Value.newBuilder().setValue(1)); RunQueryRequest request = makeRequest(query.build(), namespace); RunQueryResponse response = datastore.runQuery(request); QueryResultBatch batch = response.getBatch(); if (batch.getEntityResultsCount() == 0) { throw new NoSuchElementException( "Datastore total statistics unavailable"); } Entity entity = batch.getEntityResults(0).getEntity(); return entity.getProperties().get("timestamp").getTimestampValue().getSeconds() * 1000000; }
/** * Tests {@link DatastoreV1.Read.SplitQueryFn} when the query has a user specified limit. */ @Test public void testSplitQueryFnWithQueryLimit() throws Exception { Query queryWithLimit = QUERY.toBuilder() .setLimit(Int32Value.newBuilder().setValue(1)) .build(); SplitQueryFn splitQueryFn = new SplitQueryFn(V_1_OPTIONS, 10, mockDatastoreFactory); DoFnTester<Query, Query> doFnTester = DoFnTester.of(splitQueryFn); doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); List<Query> queries = doFnTester.processBundle(queryWithLimit); assertEquals(queries.size(), 1); verifyNoMoreInteractions(mockDatastore); verifyNoMoreInteractions(mockQuerySplitter); }
/** Tests that {@link ReadFn} retries after an error. */ @Test public void testReadFnRetriesErrors() throws Exception { // An empty query to read entities. Query query = Query.newBuilder().setLimit( Int32Value.newBuilder().setValue(1)).build(); // Use mockResponseForQuery to generate results. when(mockDatastore.runQuery(any(RunQueryRequest.class))) .thenThrow( new DatastoreException("RunQuery", Code.DEADLINE_EXCEEDED, "", null)) .thenAnswer(new Answer<RunQueryResponse>() { @Override public RunQueryResponse answer(InvocationOnMock invocationOnMock) throws Throwable { Query q = ((RunQueryRequest) invocationOnMock.getArguments()[0]).getQuery(); return mockResponseForQuery(q); } }); ReadFn readFn = new ReadFn(V_1_OPTIONS, mockDatastoreFactory); DoFnTester<Query, Entity> doFnTester = DoFnTester.of(readFn); doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); List<Entity> entities = doFnTester.processBundle(query); }
private Iterator<EntityResult> getIteratorAndMoveCursor() throws DatastoreException { Query.Builder query = this.query.toBuilder(); query.setLimit(Int32Value.newBuilder().setValue(QUERY_BATCH_LIMIT)); if (currentBatch != null && !currentBatch.getEndCursor().isEmpty()) { query.setStartCursor(currentBatch.getEndCursor()); } RunQueryRequest request = makeRequest(query.build(), namespace); RunQueryResponse response = datastore.runQuery(request); currentBatch = response.getBatch(); int numFetch = currentBatch.getEntityResultsCount(); // All indications from the API are that there are/may be more results. moreResults = ((numFetch == QUERY_BATCH_LIMIT) || (currentBatch.getMoreResults() == NOT_FINISHED)); // May receive a batch of 0 results if the number of records is a multiple // of the request limit. if (numFetch == 0) { return null; } return currentBatch.getEntityResultsList().iterator(); }
@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); }
@Test public void expose_playing_events_to_the_package() { final TestEventFactory eventFactory = TestEventFactory.newInstance(getClass()); final StringValue strValue = StringValue.newBuilder() .setValue("eins zwei drei") .build(); final Int32Value intValue = Int32Value.newBuilder().setValue(123).build(); final Version nextVersion = Versions.increment(projection.getVersion()); final Event e1 = eventFactory.createEvent(strValue, nextVersion); final Event e2 = eventFactory.createEvent(intValue, Versions.increment(nextVersion)); final boolean projectionChanged = Projection.play(projection, ImmutableList.of(e1, e2)); final String projectionState = projection.getState() .getValue(); assertTrue(projectionChanged); assertTrue(projectionState.contains(strValue.getValue())); assertTrue(projectionState.contains(String.valueOf(intValue.getValue()))); }
@VisibleForTesting Span generateSpan(SpanData spanData) { SpanContext context = spanData.getContext(); final String traceIdHex = encodeTraceId(context.getTraceId()); final String spanIdHex = encodeSpanId(context.getSpanId()); SpanName spanName = SpanName.newBuilder().setProject(projectId).setTrace(traceIdHex).setSpan(spanIdHex).build(); Span.Builder spanBuilder = Span.newBuilder() .setNameWithSpanName(spanName) .setSpanId(encodeSpanId(context.getSpanId())) .setDisplayName(toTruncatableStringProto(spanData.getName())) .setStartTime(toTimestampProto(spanData.getStartTimestamp())) .setAttributes(toAttributesProto(spanData.getAttributes())) .setTimeEvents( toTimeEventsProto(spanData.getAnnotations(), spanData.getNetworkEvents())); io.opencensus.trace.Status status = spanData.getStatus(); if (status != null) { spanBuilder.setStatus(toStatusProto(status)); } Timestamp end = spanData.getEndTimestamp(); if (end != null) { spanBuilder.setEndTime(toTimestampProto(end)); } spanBuilder.setLinks(toLinksProto(spanData.getLinks())); Integer childSpanCount = spanData.getChildSpanCount(); if (childSpanCount != null) { spanBuilder.setChildSpanCount(Int32Value.newBuilder().setValue(childSpanCount).build()); } if (spanData.getParentSpanId() != null && spanData.getParentSpanId().isValid()) { spanBuilder.setParentSpanId(encodeSpanId(spanData.getParentSpanId())); } return spanBuilder.build(); }
/** * Creates additional types (Value, Struct and ListValue) to be added to the Service config. * TODO (guptasu): Fix this hack. Find a better way to add the predefined types. * TODO (guptasu): Add them only when required and not in all cases. */ static Iterable<Type> createAdditionalServiceTypes() { Map<String, DescriptorProto> additionalMessages = Maps.newHashMap(); additionalMessages.put(Struct.getDescriptor().getFullName(), Struct.getDescriptor().toProto()); additionalMessages.put(Value.getDescriptor().getFullName(), Value.getDescriptor().toProto()); additionalMessages.put(ListValue.getDescriptor().getFullName(), ListValue.getDescriptor().toProto()); additionalMessages.put(Empty.getDescriptor().getFullName(), Empty.getDescriptor().toProto()); additionalMessages.put(Int32Value.getDescriptor().getFullName(), Int32Value.getDescriptor().toProto()); additionalMessages.put(DoubleValue.getDescriptor().getFullName(), DoubleValue.getDescriptor().toProto()); additionalMessages.put(BoolValue.getDescriptor().getFullName(), BoolValue.getDescriptor().toProto()); additionalMessages.put(StringValue.getDescriptor().getFullName(), StringValue.getDescriptor().toProto()); for (Descriptor descriptor : Struct.getDescriptor().getNestedTypes()) { additionalMessages.put(descriptor.getFullName(), descriptor.toProto()); } // TODO (guptasu): Remove this hard coding. Without this, creation of Model from Service throws. // Needs investigation. String fileName = "struct.proto"; List<Type> additionalTypes = Lists.newArrayList(); for (String typeName : additionalMessages.keySet()) { additionalTypes.add(TypesBuilderFromDescriptor.createType(typeName, additionalMessages.get(typeName), fileName)); } return additionalTypes; }
@Test public void testReadValidationFailsQueryLimitZero() throws Exception { Query invalidLimit = Query.newBuilder().setLimit(Int32Value.newBuilder().setValue(0)).build(); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Invalid query limit 0: must be positive"); DatastoreIO.v1().read().withQuery(invalidLimit); }
@Test public void testReadValidationFailsQueryLimitNegative() throws Exception { Query invalidLimit = Query.newBuilder().setLimit(Int32Value.newBuilder().setValue(-5)).build(); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("Invalid query limit -5: must be positive"); DatastoreIO.v1().read().withQuery(invalidLimit); }
/** Helper function to run a test reading from a {@link ReadFn}. */ private void readFnTest(int numEntities) throws Exception { // An empty query to read entities. Query query = Query.newBuilder().setLimit( Int32Value.newBuilder().setValue(numEntities)).build(); // Use mockResponseForQuery to generate results. when(mockDatastore.runQuery(any(RunQueryRequest.class))) .thenAnswer(new Answer<RunQueryResponse>() { @Override public RunQueryResponse answer(InvocationOnMock invocationOnMock) throws Throwable { Query q = ((RunQueryRequest) invocationOnMock.getArguments()[0]).getQuery(); return mockResponseForQuery(q); } }); ReadFn readFn = new ReadFn(V_1_OPTIONS, mockDatastoreFactory); DoFnTester<Query, Entity> doFnTester = DoFnTester.of(readFn); /** * Although Datastore client is marked transient in {@link ReadFn}, when injected through * mock factory using a when clause for unit testing purposes, it is not serializable * because it doesn't have a no-arg constructor. Thus disabling the cloning to prevent the * test object from being serialized. */ doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE); List<Entity> entities = doFnTester.processBundle(query); int expectedNumCallsToRunQuery = (int) Math.ceil((double) numEntities / QUERY_BATCH_LIMIT); verify(mockDatastore, times(expectedNumCallsToRunQuery)).runQuery(any(RunQueryRequest.class)); // Validate the number of results. assertEquals(numEntities, entities.size()); }
/** Builds a latest timestamp statistics query. */ private static Query makeLatestTimestampQuery(String namespace) { Query.Builder timestampQuery = Query.newBuilder(); if (namespace == null) { timestampQuery.addKindBuilder().setName("__Stat_Total__"); } else { timestampQuery.addKindBuilder().setName("__Stat_Ns_Total__"); } timestampQuery.addOrder(makeOrder("timestamp", DESCENDING)); timestampQuery.setLimit(Int32Value.newBuilder().setValue(1)); return timestampQuery.build(); }
@Override protected Rejection outerObject() { final Message commandMessage = Int32Value.getDefaultInstance(); final Command command = requestFactory.command().create(commandMessage); final Message rejectionMessage = CannotPerformBusinessOperation.newBuilder() .setOperationId(newUuid()) .build(); final Rejection rejection = Rejections.createRejection(rejectionMessage, command); return rejection; }
@Test public void return_event_classes_which_it_handles() { final Set<EventClass> classes = ProjectionClass.of(TestProjection.class) .getEventSubscriptions(); assertEquals(TestProjection.HANDLING_EVENT_COUNT, classes.size()); assertTrue(classes.contains(EventClass.of(StringValue.class))); assertTrue(classes.contains(EventClass.of(Int32Value.class))); }
/** * Tests the concurrent access to the {@linkplain io.spine.server.bus.BusFilter bus filters}. * * <p>The {@linkplain io.spine.server.bus.FilterChain filter chain} is a queue of the filters * which are sequentially applied to the posted message. The first {@code Bus.post()} call * invokes the filters lazy initialization. In the concurrent environment (which is natural for * a {@link io.spine.server.bus.Bus Bus}), the initialization may be performed multiple times. * Thus, some unexpected issues may appear when accessing the non-synchronously initialized * filter chain. * * <p>To make sure that the chain works fine (i.e. produces no exceptions), we invoke the * initialization multiple times from several threads. */ @SuppressWarnings("MethodWithMultipleLoops") // OK for such test case. @Ignore // This test is used only to diagnose EventBus malfunctions in concurrent environment. // It's too long to execute this test per each build, so we leave it as is for now. // Please see build log to find out if there were some errors during the test execution. @Test public void store_filters_regarding_possible_concurrent_modifications() throws InterruptedException { final int threadCount = 50; // "Random" more or less valid Event. final Event event = Event.newBuilder() .setId(EventId.newBuilder().setValue("123-1")) .setMessage(pack(Int32Value.newBuilder() .setValue(42) .build())) .build(); final StorageFactory storageFactory = StorageFactorySwitch.newInstance(newName("baz"), false).get(); final ExecutorService executor = Executors.newFixedThreadPool(threadCount); // Catch non-easily reproducible bugs. for (int i = 0; i < 300; i++) { final EventBus eventBus = EventBus.newBuilder() .setStorageFactory(storageFactory) .build(); for (int j = 0; j < threadCount; j++) { executor.execute(new Runnable() { @Override public void run() { eventBus.post(event); } }); } // Let the system destroy all the native threads, clean up, etc. Thread.sleep(100); } executor.shutdownNow(); }
@Test(expected = IllegalStateException.class) public void throw_exception_if_dispatch_unknown_command() { final Int32Value unknownCommand = Int32Value.getDefaultInstance(); final CommandEnvelope envelope = CommandEnvelope.of( requestFactory.createCommand(unknownCommand) ); processManager.dispatchCommand(envelope); }
@Test(expected = IllegalArgumentException.class) public void throw_exception_if_dispatch_unknown_command() { final Command unknownCommand = requestFactory.createCommand(Int32Value.getDefaultInstance()); final CommandEnvelope request = CommandEnvelope.of(unknownCommand); repository().dispatchCommand(request); }
@Test public void update_entity_column_values() { final Project.Status initialStatus = DONE; final Project.Status statusAfterUpdate = CANCELLED; final Int32Value initialStatusValue = Int32Value.newBuilder() .setValue(initialStatus.getNumber()) .build(); final ColumnFilter status = eq("projectStatusValue", initialStatusValue); final CompositeColumnFilter aggregatingFilter = CompositeColumnFilter.newBuilder() .setOperator(ALL) .addFilter(status) .build(); final EntityFilters filters = EntityFilters.newBuilder() .addFilter(aggregatingFilter) .build(); final EntityQuery<I> query = EntityQueries.from(filters, getTestEntityClass()); final I id = newId(); final TestCounterEntity<I> entity = new TestCounterEntity<>(id); entity.setStatus(initialStatus); final EntityRecord record = newStorageRecord(id, newState(id)); final EntityRecordWithColumns recordWithColumns = create(record, entity); final RecordStorage<I> storage = getStorage(); final FieldMask fieldMask = FieldMask.getDefaultInstance(); // Create the record. storage.write(id, recordWithColumns); final Iterator<EntityRecord> recordsBefore = storage.readAll(query, fieldMask); assertSingleRecord(record, recordsBefore); // Update the entity columns of the record. entity.setStatus(statusAfterUpdate); final EntityRecordWithColumns updatedRecordWithColumns = create(record, entity); storage.write(id, updatedRecordWithColumns); final Iterator<EntityRecord> recordsAfter = storage.readAll(query, fieldMask); assertFalse(recordsAfter.hasNext()); }
@Test public void create_set_on_varargs() { assertEquals(3, EventClass.setOf( BoolValue.class, Int32Value.class, StringValue.class).size()); }
private Int32ValueMarshaller() { super(Int32Value.getDefaultInstance()); }
@Override protected final void doMerge(JsonParser parser, int unused, Message.Builder messageBuilder) throws IOException { Int32Value.Builder builder = (Int32Value.Builder) messageBuilder; builder.setValue(ParseSupport.parseInt32(parser)); }
@Override protected final void doWrite(Int32Value message, JsonGenerator gen) throws IOException { SerializeSupport.printSignedInt32(message.getValue(), gen); }
@Test public void anyFields() throws Exception { TestAllTypes content = TestAllTypes.newBuilder().setOptionalInt32(1234).build(); TestAny message = TestAny.newBuilder().setAnyValue(Any.pack(content)).build(); assertMatchesUpstream(message, TestAllTypes.getDefaultInstance()); TestAny messageWithDefaultAnyValue = TestAny.newBuilder().setAnyValue(Any.getDefaultInstance()).build(); assertMatchesUpstream(messageWithDefaultAnyValue); // Well-known types have a special formatting when embedded in Any. // // 1. Any in Any. Any anyMessage = Any.pack(Any.pack(content)); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); // 2. Wrappers in Any. anyMessage = Any.pack(Int32Value.newBuilder().setValue(12345).build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); anyMessage = Any.pack(UInt32Value.newBuilder().setValue(12345).build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); anyMessage = Any.pack(Int64Value.newBuilder().setValue(12345).build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); anyMessage = Any.pack(UInt64Value.newBuilder().setValue(12345).build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); anyMessage = Any.pack(FloatValue.newBuilder().setValue(12345).build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); anyMessage = Any.pack(DoubleValue.newBuilder().setValue(12345).build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); anyMessage = Any.pack(BoolValue.newBuilder().setValue(true).build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); anyMessage = Any.pack(StringValue.newBuilder().setValue("Hello").build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); anyMessage = Any.pack(BytesValue.newBuilder().setValue(ByteString.copyFrom(new byte[] {1, 2})).build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); // 3. Timestamp in Any. anyMessage = Any.pack(Timestamps.parse("1969-12-31T23:59:59Z")); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); // 4. Duration in Any anyMessage = Any.pack(Durations.parse("12345.10s")); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); // 5. FieldMask in Any anyMessage = Any.pack(FieldMaskUtil.fromString("foo.bar,baz")); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); // 6. Struct in Any Struct.Builder structBuilder = Struct.newBuilder(); structBuilder.putFields("number", Value.newBuilder().setNumberValue(1.125).build()); anyMessage = Any.pack(structBuilder.build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); // 7. Value (number type) in Any Value.Builder valueBuilder = Value.newBuilder(); valueBuilder.setNumberValue(1); anyMessage = Any.pack(valueBuilder.build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); // 8. Value (null type) in Any anyMessage = Any.pack(Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build()); assertMatchesUpstream(anyMessage, TestAllTypes.getDefaultInstance()); }
private AnEntityView(Int32Value id) { super(id, "View title"); }
@Override protected StringValue load(Int32Value id) { return STATE; }
/** * Convert a protocol buffer field value to {@link Any} with the below rule: * <ul> * <li> If the field is a primitive type and can be mapped to a wrapper message type * defined in //tech/type/proto/wrappers.proto, its value is boxed into a wrapper * and goes to Any.value, the type name of the wrapper goes to Any.type_url. * <li> If the field is already a message, its type name goes to Any.type_url, * its value directly goes to Any.value * <li> If the field is an enum value, the name of the enum value is boxed into * tech.type.String and put into Any.value, and tech.type.String goes to Any.type_url. */ private static Any toAnyType(FieldDescriptor.Type protobufType, Object value) { Any.Builder builder = Any.newBuilder(); java.lang.String typeFullName; Message wrapperMessage; switch (protobufType) { case MESSAGE: wrapperMessage = (Message) value; typeFullName = wrapperMessage.getDescriptorForType().getFullName(); break; case ENUM: // NOTE: Erasing the enum type to the String wrapper is currently intentional, to avoid // the need to add an enum wrapper type. This may change in the future. typeFullName = StringValue.getDescriptor().getFullName(); wrapperMessage = StringValue.newBuilder().setValue(((EnumValueDescriptor) value).getName()).build(); break; case BOOL: typeFullName = BoolValue.getDescriptor().getFullName(); wrapperMessage = BoolValue.newBuilder().setValue((Boolean) value).build(); break; case DOUBLE: typeFullName = DoubleValue.getDescriptor().getFullName(); wrapperMessage = DoubleValue.newBuilder().setValue((java.lang.Double) value).build(); break; case FLOAT: typeFullName = FloatValue.getDescriptor().getFullName(); wrapperMessage = FloatValue.newBuilder().setValue((java.lang.Float) value).build(); break; case STRING: typeFullName = StringValue.getDescriptor().getFullName(); wrapperMessage = StringValue.newBuilder().setValue((java.lang.String) value).build(); break; case SINT32: case SFIXED32: case INT32: typeFullName = Int32Value.getDescriptor().getFullName(); wrapperMessage = Int32Value.newBuilder().setValue((Integer) value).build(); break; case SINT64: case SFIXED64: case INT64: typeFullName = Int64Value.getDescriptor().getFullName(); wrapperMessage = Int64Value.newBuilder().setValue((Long) value).build(); break; case UINT32: case FIXED32: typeFullName = UInt32Value.getDescriptor().getFullName(); wrapperMessage = UInt32Value.newBuilder().setValue((Integer) value).build(); break; case UINT64: case FIXED64: typeFullName = UInt64Value.getDescriptor().getFullName(); wrapperMessage = UInt64Value.newBuilder().setValue((Long) value).build(); break; case BYTES: typeFullName = BytesValue.getDescriptor().getFullName(); wrapperMessage = BytesValue.newBuilder().setValue(ByteString.copyFrom((byte[]) value)) .build(); break; default: throw new IllegalArgumentException("Type " + protobufType.name() + " cannot be converted to Any type."); } return builder.setTypeUrl(TYPE_SERVICE_BASE_URL + "/" + typeFullName) .setValue(wrapperMessage.toByteString()).build(); }
/** Read and output entities for the given query. */ @ProcessElement public void processElement(ProcessContext context) throws Exception { Query query = context.element(); String namespace = options.getNamespace(); int userLimit = query.hasLimit() ? query.getLimit().getValue() : Integer.MAX_VALUE; boolean moreResults = true; QueryResultBatch currentBatch = null; while (moreResults) { Query.Builder queryBuilder = query.toBuilder().clone(); queryBuilder.setLimit(Int32Value.newBuilder().setValue( Math.min(userLimit, QUERY_BATCH_LIMIT))); if (currentBatch != null && !currentBatch.getEndCursor().isEmpty()) { queryBuilder.setStartCursor(currentBatch.getEndCursor()); } RunQueryRequest request = makeRequest(queryBuilder.build(), namespace); RunQueryResponse response = runQueryWithRetries(request); currentBatch = response.getBatch(); // MORE_RESULTS_AFTER_LIMIT is not implemented yet: // https://groups.google.com/forum/#!topic/gcd-discuss/iNs6M1jA2Vw, so // use result count to determine if more results might exist. int numFetch = currentBatch.getEntityResultsCount(); if (query.hasLimit()) { verify(userLimit >= numFetch, "Expected userLimit %s >= numFetch %s, because query limit %s must be <= userLimit", userLimit, numFetch, query.getLimit()); userLimit -= numFetch; } // output all the entities from the current batch. for (EntityResult entityResult : currentBatch.getEntityResultsList()) { context.output(entityResult.getEntity()); } // Check if we have more entities to be read. moreResults = // User-limit does not exist (so userLimit == MAX_VALUE) and/or has not been satisfied (userLimit > 0) // All indications from the API are that there are/may be more results. && ((numFetch == QUERY_BATCH_LIMIT) || (currentBatch.getMoreResults() == NOT_FINISHED)); } }
@SuppressWarnings("unused") // Used for the Model construction @Assign Iterable<Message> handle(Int32Value command) { // NoOp for test return Collections.emptySet(); }
@Subscribe public void on(Int32Value event) { final StringValue newState = createNewState("integerState", String.valueOf(event.getValue())); getBuilder().mergeFrom(newState); }
/** Invalid command handler, which does not produce events. */ @Assign List<Message> on(Int32Value value) { return emptyList(); }
@Test public void return_int_msg_field_class_by_descriptor() { assertReturnsFieldClass(Integer.class, Int32Value.getDescriptor()); }
@SuppressWarnings("OverlyLongMethod") // Complex test case (still tests a single operation) @Test public void filter_records_by_columns() { final Project.Status requiredValue = DONE; final Int32Value wrappedValue = Int32Value.newBuilder() .setValue(requiredValue.getNumber()) .build(); final Version versionValue = Version.newBuilder() .setNumber(2) // Value of the counter after one columns .build(); // scan (incremented 2 times internally) final ColumnFilter status = eq("projectStatusValue", wrappedValue); final ColumnFilter version = eq("counterVersion", versionValue); final CompositeColumnFilter aggregatingFilter = CompositeColumnFilter.newBuilder() .setOperator(ALL) .addFilter(status) .addFilter(version) .build(); final EntityFilters filters = EntityFilters.newBuilder() .addFilter(aggregatingFilter) .build(); final EntityQuery<I> query = EntityQueries.from(filters, getTestEntityClass()); final I idMatching = newId(); final I idWrong1 = newId(); final I idWrong2 = newId(); final TestCounterEntity<I> matchingEntity = new TestCounterEntity<>(idMatching); final TestCounterEntity<I> wrongEntity1 = new TestCounterEntity<>(idWrong1); final TestCounterEntity<I> wrongEntity2 = new TestCounterEntity<>(idWrong2); // 2 of 3 have required values matchingEntity.setStatus(requiredValue); wrongEntity1.setStatus(requiredValue); wrongEntity2.setStatus(CANCELLED); // Change internal Entity state wrongEntity1.getCounter(); // After the mutation above the single matching record is the one under the `idMatching` ID final EntityRecord fineRecord = newStorageRecord(idMatching, newState(idMatching)); final EntityRecord notFineRecord1 = newStorageRecord(idWrong1, newState(idWrong1)); final EntityRecord notFineRecord2 = newStorageRecord(idWrong2, newState(idWrong2)); final EntityRecordWithColumns recordRight = create(fineRecord, matchingEntity); final EntityRecordWithColumns recordWrong1 = create(notFineRecord1, wrongEntity1); final EntityRecordWithColumns recordWrong2 = create(notFineRecord2, wrongEntity2); final RecordStorage<I> storage = getStorage(); storage.write(idMatching, recordRight); storage.write(idWrong1, recordWrong1); storage.write(idWrong2, recordWrong2); final Iterator<EntityRecord> readRecords = storage.readAll(query, FieldMask.getDefaultInstance()); assertSingleRecord(fineRecord, readRecords); }
@Test public void create_set_on_varargs() { assertEquals(3, RejectionClass.setOf(BoolValue.class, Int32Value.class, StringValue.class) .size()); }
public void testAnyInMaps() throws Exception { JsonFormat.TypeRegistry registry = JsonFormat.TypeRegistry.newBuilder().add(TestAllTypes.getDescriptor()).build(); JsonFormat.Printer printer = JsonFormat.printer().usingTypeRegistry(registry); 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()); assertEquals( "{\n" + " \"anyMap\": {\n" + " \"int32_wrapper\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.Int32Value\",\n" + " \"value\": 123\n" + " },\n" + " \"int64_wrapper\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.Int64Value\",\n" + " \"value\": \"456\"\n" + " },\n" + " \"timestamp\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.Timestamp\",\n" + " \"value\": \"1969-12-31T23:59:59Z\"\n" + " },\n" + " \"duration\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.Duration\",\n" + " \"value\": \"12345.100s\"\n" + " },\n" + " \"field_mask\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.FieldMask\",\n" + " \"value\": \"foo.bar,baz\"\n" + " },\n" + " \"struct\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.Struct\",\n" + " \"value\": {\n" + " \"number\": 1.125\n" + " }\n" + " },\n" + " \"list_value\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.ListValue\",\n" + " \"value\": [1.125, null]\n" + " },\n" + " \"number_value\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.Value\",\n" + " \"value\": 1.125\n" + " },\n" + " \"any_value_number\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.Any\",\n" + " \"value\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.Value\",\n" + " \"value\": 1.125\n" + " }\n" + " },\n" + " \"any_value_default\": {\n" + " \"@type\": \"type.googleapis.com/google.protobuf.Any\",\n" + " \"value\": {}\n" + " },\n" + " \"default\": {}\n" + " }\n" + "}", printer.print(testAny.build())); assertRoundTripEquals(testAny.build(), registry); }