diff --git a/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordDocumentReferenceTest.java b/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordDocumentReferenceTest.java index 21baf69cc49f..cad50177cdb9 100644 --- a/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordDocumentReferenceTest.java +++ b/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordDocumentReferenceTest.java @@ -38,6 +38,13 @@ import com.google.firestore.v1.CommitRequest; import com.google.firestore.v1.CommitResponse; import com.google.firestore.v1.Value; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,15 +55,6 @@ import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - @RunWith(MockitoJUnitRunner.class) public class RecordDocumentReferenceTest { @@ -84,7 +82,8 @@ public void serializeBasicTypes() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); documentReference.set(ALL_SUPPORTED_TYPES_OBJECT).get(); @@ -99,19 +98,22 @@ public void doesNotSerializeAdvancedNumberTypes() { InvalidRecord record = new InvalidRecord(new BigInteger("0"), null, null); expectedErrorMessages.put( record, - "Could not serialize object. Numbers of type BigInteger are not supported, please use an int, long, float, double or BigDecimal (found in field 'bigIntegerValue')"); + "Could not serialize object. Numbers of type BigInteger are not supported, please use an" + + " int, long, float, double or BigDecimal (found in field 'bigIntegerValue')"); record = new InvalidRecord(null, (byte) 0, null); expectedErrorMessages.put( record, - "Could not serialize object. Numbers of type Byte are not supported, please use an int, long, float, double or BigDecimal (found in field 'byteValue')"); + "Could not serialize object. Numbers of type Byte are not supported, please use an int," + + " long, float, double or BigDecimal (found in field 'byteValue')"); record = new InvalidRecord(null, null, (short) 0); expectedErrorMessages.put( record, - "Could not serialize object. Numbers of type Short are not supported, please use an int, long, float, double or BigDecimal (found in field 'shortValue')"); + "Could not serialize object. Numbers of type Short are not supported, please use an int," + + " long, float, double or BigDecimal (found in field 'shortValue')"); - for (Map.Entry testCase : expectedErrorMessages.entrySet()) { + for (Map.Entry testCase : expectedErrorMessages.entrySet()) { try { documentReference.set(testCase.getKey()); fail(); @@ -138,14 +140,15 @@ public void doesNotDeserializeAdvancedNumberTypes() throws Exception { streamObserverCapture.capture(), ArgumentMatchers.any()); - DocumentSnapshot snapshot = documentReference.get().get(); + DocumentSnapshot snapshot = documentReference.get().get(); try { snapshot.toObject(InvalidRecord.class); fail(); } catch (RuntimeException e) { assertEquals( String.format( - "Could not deserialize object. Deserializing values to %s is not supported (found in field '%s')", + "Could not deserialize object. Deserializing values to %s is not supported (found" + + " in field '%s')", typeName, fieldName), e.getMessage()); } @@ -157,7 +160,8 @@ public void createDocument() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); documentReference.create(SINGLE_COMPONENT_OBJECT).get(); @@ -172,7 +176,8 @@ public void createWithServerTimestamp() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); documentReference.create(SERVER_TIMESTAMP_OBJECT).get(); @@ -181,7 +186,7 @@ public void createWithServerTimestamp() throws Exception { create(Collections.emptyMap()), transform("foo", serverTimestamp(), "inner.bar", serverTimestamp())); - List commitRequests = commitCapture.getAllValues(); + List commitRequests = commitCapture.getAllValues(); assertCommitEquals(create, commitRequests.get(0)); } @@ -190,7 +195,8 @@ public void setWithServerTimestamp() throws Exception { doReturn(FIELD_TRANSFORM_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); documentReference.set(SERVER_TIMESTAMP_OBJECT).get(); @@ -199,7 +205,7 @@ public void setWithServerTimestamp() throws Exception { set(SERVER_TIMESTAMP_PROTO), transform("foo", serverTimestamp(), "inner.bar", serverTimestamp())); - List commitRequests = commitCapture.getAllValues(); + List commitRequests = commitCapture.getAllValues(); assertCommitEquals(set, commitRequests.get(0)); } @@ -208,18 +214,17 @@ public void mergeWithServerTimestamps() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); - documentReference - .set(SERVER_TIMESTAMP_OBJECT, SetOptions.mergeFields("inner.bar")) - .get(); + documentReference.set(SERVER_TIMESTAMP_OBJECT, SetOptions.mergeFields("inner.bar")).get(); - CommitRequest set = + CommitRequest set = commit( set(SERVER_TIMESTAMP_PROTO, new ArrayList<>()), transform("inner.bar", serverTimestamp())); - List commitRequests = commitCapture.getAllValues(); + List commitRequests = commitCapture.getAllValues(); assertCommitEquals(set, commitRequests.get(0)); } @@ -228,7 +233,8 @@ public void setDocumentWithMerge() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); documentReference.set(SINGLE_COMPONENT_OBJECT, SetOptions.merge()).get(); documentReference.set(ALL_SUPPORTED_TYPES_OBJECT, SetOptions.mergeFields("foo")).get(); @@ -241,7 +247,7 @@ public void setDocumentWithMerge() throws Exception { SetOptions.mergeFieldPaths(Arrays.asList(FieldPath.of("foo")))) .get(); - CommitRequest expectedCommit = commit(set(SINGLE_COMPONENT_PROTO, Arrays.asList("foo"))); + CommitRequest expectedCommit = commit(set(SINGLE_COMPONENT_PROTO, Arrays.asList("foo"))); for (int i = 0; i < 4; ++i) { assertCommitEquals(expectedCommit, commitCapture.getAllValues().get(i)); @@ -253,7 +259,8 @@ public void setDocumentWithNestedMerge() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); documentReference.set(NESTED_RECORD_OBJECT, SetOptions.mergeFields("first.foo")).get(); documentReference @@ -282,7 +289,8 @@ public void setMultipleFieldsWithMerge() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); documentReference .set( @@ -310,7 +318,8 @@ public void setNestedMapWithMerge() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); documentReference.set(NESTED_RECORD_OBJECT, SetOptions.mergeFields("first", "second")).get(); @@ -330,7 +339,8 @@ public void extractFieldMaskFromMerge() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); documentReference.set(NESTED_RECORD_OBJECT, SetOptions.merge()).get(); @@ -341,24 +351,25 @@ public void extractFieldMaskFromMerge() throws Exception { nestedProto.getMapValueBuilder().putAllFields(ALL_SUPPORTED_TYPES_PROTO); nestedUpdate.put("second", nestedProto.build()); - List updateMask = Arrays.asList( - "first.foo", - "second.arrayValue", - "second.bytesValue", - "second.dateValue", - "second.doubleValue", - "second.falseValue", - "second.foo", - "second.geoPointValue", - "second.infValue", - "second.longValue", - "second.nanValue", - "second.negInfValue", - "second.nullValue", - "second.objectValue.foo", - "second.timestampValue", - "second.trueValue", - "second.model.foo"); + List updateMask = + Arrays.asList( + "first.foo", + "second.arrayValue", + "second.bytesValue", + "second.dateValue", + "second.doubleValue", + "second.falseValue", + "second.foo", + "second.geoPointValue", + "second.infValue", + "second.longValue", + "second.nanValue", + "second.negInfValue", + "second.nullValue", + "second.objectValue.foo", + "second.timestampValue", + "second.trueValue", + "second.model.foo"); CommitRequest expectedCommit = commit(set(nestedUpdate, updateMask)); assertCommitEquals(expectedCommit, commitCapture.getValue()); @@ -369,9 +380,12 @@ public void setNestedRecordWithPojoMapWithMerge() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) .sendRequest( - commitCapture.capture(), ArgumentMatchers.>any()); + commitCapture.capture(), + ArgumentMatchers.>any()); - documentReference.set(NESTED_RECORD_WITH_POJO_OBJECT, SetOptions.mergeFields("first", "second")).get(); + documentReference + .set(NESTED_RECORD_WITH_POJO_OBJECT, SetOptions.mergeFields("first", "second")) + .get(); Map nestedUpdate = new HashMap<>(); Value.Builder nestedProto = Value.newBuilder(); @@ -384,7 +398,7 @@ public void setNestedRecordWithPojoMapWithMerge() throws Exception { assertCommitEquals(expectedCommit, commitCapture.getValue()); } - @Test + @Test public void setNestedPojoWithRecordMapWithMerge() throws Exception { doReturn(SINGLE_WRITE_COMMIT_RESPONSE) .when(firestoreMock) @@ -392,7 +406,9 @@ public void setNestedPojoWithRecordMapWithMerge() throws Exception { commitCapture.capture(), ArgumentMatchers.>any()); - documentReference.set(NESTED_POJO_WITH_RECORD_OBJECT, SetOptions.mergeFields("first", "second")).get(); + documentReference + .set(NESTED_POJO_WITH_RECORD_OBJECT, SetOptions.mergeFields("first", "second")) + .get(); Map nestedUpdate = new HashMap<>(); Value.Builder nestedProto = Value.newBuilder(); diff --git a/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordMapperTest.java b/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordMapperTest.java index daa5df99d3f0..f9eab82388cc 100644 --- a/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordMapperTest.java +++ b/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordMapperTest.java @@ -16,6 +16,13 @@ package com.google.cloud.firestore; +import static com.google.cloud.firestore.LocalFirestoreHelper.fromSingleQuotedString; +import static com.google.cloud.firestore.LocalFirestoreHelper.mapAnyType; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import com.google.cloud.firestore.annotation.DocumentId; import com.google.cloud.firestore.annotation.PropertyName; import com.google.cloud.firestore.annotation.ThrowOnExtraProperties; @@ -23,12 +30,6 @@ import com.google.cloud.firestore.spi.v1.FirestoreRpc; import com.google.common.collect.ImmutableList; import com.google.firestore.v1.DatabaseRootName; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; - import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; @@ -40,13 +41,11 @@ import java.util.List; import java.util.Map; import java.util.Set; - -import static com.google.cloud.firestore.LocalFirestoreHelper.fromSingleQuotedString; -import static com.google.cloud.firestore.LocalFirestoreHelper.mapAnyType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; @SuppressWarnings({"unused", "WeakerAccess", "SpellCheckingInspection"}) @RunWith(MockitoJUnitRunner.class) @@ -60,175 +59,96 @@ public class RecordMapperTest { private static final double EPSILON = 0.0003; - public record StringBean ( - String value - ){} + public record StringBean(String value) {} - public record DoubleBean ( - double value - ){} + public record DoubleBean(double value) {} - public record BigDecimalBean ( - BigDecimal value - ){} + public record BigDecimalBean(BigDecimal value) {} - public record FloatBean ( - float value - ){} + public record FloatBean(float value) {} - public record LongBean ( - long value - ){} + public record LongBean(long value) {} - public record IntBean ( - int value - ){} + public record IntBean(int value) {} - public record BooleanBean ( - boolean value - ){} + public record BooleanBean(boolean value) {} - public record ShortBean ( - short value - ){} + public record ShortBean(short value) {} - public record ByteBean ( - byte value - ){} + public record ByteBean(byte value) {} - public record CharBean ( - char value - ){} + public record CharBean(char value) {} - public record IntArrayBean ( - int[] values - ){} + public record IntArrayBean(int[] values) {} - public record StringArrayBean ( - String[] values - ){} + public record StringArrayBean(String[] values) {} - public record XMLAndURLBean ( - String XMLAndURL - ){} + public record XMLAndURLBean(String XMLAndURL) {} - public record CaseSensitiveFieldBean1 ( - String VALUE - ){} + public record CaseSensitiveFieldBean1(String VALUE) {} - public record CaseSensitiveFieldBean2 ( - String value - ){} + public record CaseSensitiveFieldBean2(String value) {} - public record CaseSensitiveFieldBean3 ( - String Value - ){} + public record CaseSensitiveFieldBean3(String Value) {} - public record CaseSensitiveFieldBean4 ( - String valUE - ){} + public record CaseSensitiveFieldBean4(String valUE) {} - public record NestedBean ( - StringBean bean - ){} + public record NestedBean(StringBean bean) {} - public record ObjectBean ( - Object value - ){} + public record ObjectBean(Object value) {} - public record GenericBean ( - B value - ){} + public record GenericBean(B value) {} - public record DoubleGenericBean ( - A valueA, - B valueB - ){} + public record DoubleGenericBean(A valueA, B valueB) {} - public record ListBean ( - List values - ){} + public record ListBean(List values) {} - public record SetBean ( - Set values - ){} + public record SetBean(Set values) {} - public record CollectionBean ( - Collection values - ){} + public record CollectionBean(Collection values) {} - public record MapBean ( - Map values - ){} + public record MapBean(Map values) {} /** * This form is not terribly useful in Java, but Kotlin Maps are immutable and are rewritten into * this form (b/67470108 has more details). */ - public record UpperBoundedMapBean ( - Map values - ){} + public record UpperBoundedMapBean(Map values) {} - public record MultiBoundedMapBean ( - Map values - ){} + public record MultiBoundedMapBean(Map values) {} - public record MultiBoundedMapHolderBean ( - MultiBoundedMapBean map - ){} + public record MultiBoundedMapHolderBean(MultiBoundedMapBean map) {} - public record UnboundedMapBean ( - Map values - ){} + public record UnboundedMapBean(Map values) {} - public record UnboundedTypeVariableMapBean ( - Map values - ){} + public record UnboundedTypeVariableMapBean(Map values) {} - public record UnboundedTypeVariableMapHolderBean ( - UnboundedTypeVariableMapBean map - ){} + public record UnboundedTypeVariableMapHolderBean(UnboundedTypeVariableMapBean map) {} - public record NestedListBean ( - List values - ){} + public record NestedListBean(List values) {} - public record NestedMapBean ( - Map values - ){} + public record NestedMapBean(Map values) {} - public record IllegalKeyMapBean ( - Map values - ){} + public record IllegalKeyMapBean(Map values) {} @ThrowOnExtraProperties - public record ThrowOnUnknownPropertiesBean ( - String value - ){} + public record ThrowOnUnknownPropertiesBean(String value) {} @ThrowOnExtraProperties - public record NoFieldBean( - ){} - - public record PropertyNameBean ( - @PropertyName("my_key") - String key, + public record NoFieldBean() {} - @PropertyName("my_value") - String value - ){} + public record PropertyNameBean( + @PropertyName("my_key") String key, @PropertyName("my_value") String value) {} @SuppressWarnings({"NonAsciiCharacters"}) - public record UnicodeBean ( - String 漢字 - ){} + public record UnicodeBean(String 漢字) {} private static T deserialize(String jsonString, Class clazz) { - return deserialize(jsonString, clazz, /*docRef=*/ null); + return deserialize(jsonString, clazz, /* docRef= */ null); } private static T deserialize(Map json, Class clazz) { - return deserialize(json, clazz, /*docRef=*/ null); + return deserialize(json, clazz, /* docRef= */ null); } private static T deserialize(String jsonString, Class clazz, DocumentReference docRef) { @@ -545,14 +465,11 @@ public void throwOnUnknownProperties() { @Test public void XMLAndURLBean() { - XMLAndURLBean bean = - deserialize("{'XMLAndURL': 'foo'}", XMLAndURLBean.class); + XMLAndURLBean bean = deserialize("{'XMLAndURL': 'foo'}", XMLAndURLBean.class); assertEquals("foo", bean.XMLAndURL()); } - public record AllCapsDefaultHandlingBean ( - String UUID - ){} + public record AllCapsDefaultHandlingBean(String UUID) {} @Test public void allCapsSerializesToUppercaseByDefault() { @@ -563,10 +480,7 @@ public void allCapsSerializesToUppercaseByDefault() { assertEquals("value", deserialized.UUID()); } - public record AllCapsWithPropertyName ( - @PropertyName("uuid") - String UUID - ){} + public record AllCapsWithPropertyName(@PropertyName("uuid") String UUID) {} @Test public void allCapsWithPropertyNameSerializesToLowercase() { @@ -599,9 +513,9 @@ public void beansCanContainMaps() { @Test public void beansCanContainUpperBoundedMaps() { Date date = new Date(1491847082123L); - Map source = mapAnyType("values", mapAnyType("foo", date)); + Map source = mapAnyType("values", mapAnyType("foo", date)); UpperBoundedMapBean bean = convertToCustomClass(source, UpperBoundedMapBean.class); - Map expected = mapAnyType("foo", date); + Map expected = mapAnyType("foo", date); assertEquals(expected, bean.values()); } @@ -628,7 +542,7 @@ public void beansCanContainUnboundedTypeVariableMaps() { UnboundedTypeVariableMapHolderBean bean = convertToCustomClass(source, UnboundedTypeVariableMapHolderBean.class); - Map expected = mapAnyType("foo", "bar"); + Map expected = mapAnyType("foo", "bar"); assertEquals(expected, bean.map().values()); } @@ -636,7 +550,7 @@ public void beansCanContainUnboundedTypeVariableMaps() { public void beansCanContainNestedUnboundedMaps() { UnboundedMapBean bean = deserialize("{'values': {'foo': {'bar': 'baz'}}}", UnboundedMapBean.class); - Map expected = mapAnyType("foo", mapAnyType("bar", "baz")); + Map expected = mapAnyType("foo", mapAnyType("bar", "baz")); assertEquals(expected, bean.values()); } @@ -761,7 +675,8 @@ public void serializingMultiBoundedObjectsWorks() { HashMap values = new HashMap(); values.put("foo", date); - MultiBoundedMapHolderBean holder = new MultiBoundedMapHolderBean(new MultiBoundedMapBean<>(values)); + MultiBoundedMapHolderBean holder = + new MultiBoundedMapHolderBean(new MultiBoundedMapBean<>(values)); Map expected = mapAnyType("map", mapAnyType("values", mapAnyType("foo", new Date(date.getTime())))); @@ -854,7 +769,8 @@ public void roundTripUnicodeBean() { public void shortsCantBeSerialized() { final ShortBean bean = new ShortBean((short) 1); assertExceptionContains( - "Numbers of type Short are not supported, please use an int, long, float, double or BigDecimal (found in field 'value')", + "Numbers of type Short are not supported, please use an int, long, float, double or" + + " BigDecimal (found in field 'value')", () -> serialize(bean)); } @@ -862,7 +778,8 @@ public void shortsCantBeSerialized() { public void bytesCantBeSerialized() { final ByteBean bean = new ByteBean((byte) 1); assertExceptionContains( - "Numbers of type Byte are not supported, please use an int, long, float, double or BigDecimal (found in field 'value')", + "Numbers of type Byte are not supported, please use an int, long, float, double or" + + " BigDecimal (found in field 'value')", () -> serialize(bean)); } @@ -976,16 +893,20 @@ public void serializingGenericBeansSupported() { GenericBean stringBean = new GenericBean("foo"); assertJson("{'value': 'foo'}", serialize(stringBean)); - GenericBean> mapBean = new GenericBean>(Collections.singletonMap("foo", "bar")); + GenericBean> mapBean = + new GenericBean>(Collections.singletonMap("foo", "bar")); assertJson("{'value': {'foo': 'bar'}}", serialize(mapBean)); - GenericBean> listBean = new GenericBean>(Collections.singletonList("foo")); + GenericBean> listBean = + new GenericBean>(Collections.singletonList("foo")); assertJson("{'value': ['foo']}", serialize(listBean)); - GenericBean> recursiveBean = new GenericBean>(new GenericBean<>("foo")); + GenericBean> recursiveBean = + new GenericBean>(new GenericBean<>("foo")); assertJson("{'value': {'value': 'foo'}}", serialize(recursiveBean)); - DoubleGenericBean doubleBean = new DoubleGenericBean("foo", 1.0); + DoubleGenericBean doubleBean = + new DoubleGenericBean("foo", 1.0); assertJson("{'valueB': 1, 'valueA': 'foo'}", serialize(doubleBean)); } @@ -1005,15 +926,10 @@ public void propertyNamesAreParsed() { } // Bean definitions with @DocumentId applied to wrong type. - public record FieldWithDocumentIdOnWrongTypeBean ( - @DocumentId Integer intField - ){} + public record FieldWithDocumentIdOnWrongTypeBean(@DocumentId Integer intField) {} - public record PropertyWithDocumentIdOnWrongTypeBean ( - @PropertyName("intField") - @DocumentId - int intField - ){} + public record PropertyWithDocumentIdOnWrongTypeBean( + @PropertyName("intField") @DocumentId int intField) {} @Test public void documentIdAnnotateWrongTypeThrows() { @@ -1031,23 +947,14 @@ public void documentIdAnnotateWrongTypeThrows() { () -> deserialize("{'intField': 1}", PropertyWithDocumentIdOnWrongTypeBean.class)); } - public record DocumentIdOnStringField ( - @DocumentId String docId - ){} + public record DocumentIdOnStringField(@DocumentId String docId) {} - public record DocumentIdOnStringFieldAsProperty ( - @PropertyName("docIdProperty") - @DocumentId - String docId, + public record DocumentIdOnStringFieldAsProperty( + @PropertyName("docIdProperty") @DocumentId String docId, + @PropertyName("anotherProperty") int someOtherProperty) {} - @PropertyName("anotherProperty") - int someOtherProperty - ){} - - public record DocumentIdOnNestedObjects ( - @PropertyName("nestedDocIdHolder") - DocumentIdOnStringField nestedDocIdHolder - ){} + public record DocumentIdOnNestedObjects( + @PropertyName("nestedDocIdHolder") DocumentIdOnStringField nestedDocIdHolder) {} @Test public void documentIdsDeserialize() { @@ -1055,8 +962,8 @@ public void documentIdsDeserialize() { new DocumentReference( firestoreMock, ResourcePath.create( - DatabaseRootName.of("test-project", "(default)"), - ImmutableList.of("coll", "doc123"))); + DatabaseRootName.of("test-project", "(default)"), + ImmutableList.of("coll", "doc123"))); assertEquals("doc123", deserialize("{}", DocumentIdOnStringField.class, ref).docId()); @@ -1065,7 +972,7 @@ public void documentIdsDeserialize() { deserialize(Collections.singletonMap("property", 100), DocumentIdOnStringField.class, ref) .docId()); - DocumentIdOnStringFieldAsProperty target = + DocumentIdOnStringFieldAsProperty target = deserialize("{'anotherProperty': 100}", DocumentIdOnStringFieldAsProperty.class, ref); assertEquals("doc123", target.docId()); assertEquals(100, target.someOtherProperty()); diff --git a/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordTestHelper.java b/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordTestHelper.java index 6bfe845bed5e..9e7591e43ab7 100644 --- a/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordTestHelper.java +++ b/java-firestore/google-cloud-firestore/src/test-jdk17/java/com/google/cloud/firestore/RecordTestHelper.java @@ -16,6 +16,9 @@ package com.google.cloud.firestore; +import static com.google.cloud.firestore.LocalFirestoreHelper.commitResponse; +import static com.google.cloud.firestore.LocalFirestoreHelper.map; + import com.google.api.core.ApiFuture; import com.google.cloud.Timestamp; import com.google.cloud.firestore.LocalFirestoreHelper.SingleField; @@ -27,10 +30,6 @@ import com.google.firestore.v1.Value; import com.google.protobuf.NullValue; import com.google.type.LatLng; - -import static com.google.cloud.firestore.LocalFirestoreHelper.commitResponse; -import static com.google.cloud.firestore.LocalFirestoreHelper.map; - import java.math.BigInteger; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -40,7 +39,6 @@ import java.util.Map; import java.util.concurrent.TimeUnit; - public final class RecordTestHelper { public static final String DATABASE_NAME; @@ -70,64 +68,42 @@ public final class RecordTestHelper { public static final GeoPoint GEO_POINT; public static final Blob BLOB; + public record SingleComponent(String foo) {} - public record SingleComponent( - String foo) { - } - - public record NestedRecord( - SingleComponent first, - AllSupportedTypes second) { - } + public record NestedRecord(SingleComponent first, AllSupportedTypes second) {} - public record NestedRecordWithPOJO( - SingleField first, - AllSupportedTypes second) { - } + public record NestedRecordWithPOJO(SingleField first, AllSupportedTypes second) {} public static class NestedPOJOWithRecord { public SingleField first = new SingleField(); public AllSupportedTypes second = ALL_SUPPORTED_TYPES_OBJECT; } - public record ServerTimestamp ( + public record ServerTimestamp( + @com.google.cloud.firestore.annotation.ServerTimestamp Date foo, Inner inner) { - @com.google.cloud.firestore.annotation.ServerTimestamp Date foo, - Inner inner - - ){ - record Inner ( - - @com.google.cloud.firestore.annotation.ServerTimestamp Date bar - ){} + record Inner(@com.google.cloud.firestore.annotation.ServerTimestamp Date bar) {} } - public record InvalidRecord ( - BigInteger bigIntegerValue, - Byte byteValue, - Short shortValue - ){} - - - public record AllSupportedTypes ( - - String foo, - Double doubleValue, - long longValue, - double nanValue, - double infValue, - double negInfValue, - boolean trueValue, - boolean falseValue, - SingleComponent objectValue, - Date dateValue, - Timestamp timestampValue, - List arrayValue, - String nullValue, - Blob bytesValue, - GeoPoint geoPointValue, - Map model - ){} + public record InvalidRecord(BigInteger bigIntegerValue, Byte byteValue, Short shortValue) {} + + public record AllSupportedTypes( + String foo, + Double doubleValue, + long longValue, + double nanValue, + double infValue, + double negInfValue, + boolean trueValue, + boolean falseValue, + SingleComponent objectValue, + Date dateValue, + Timestamp timestampValue, + List arrayValue, + String nullValue, + Blob bytesValue, + GeoPoint geoPointValue, + Map model) {} static { try { @@ -154,11 +130,24 @@ public record AllSupportedTypes ( SERVER_TIMESTAMP_PROTO = Collections.emptyMap(); SERVER_TIMESTAMP_OBJECT = new ServerTimestamp(null, new ServerTimestamp.Inner(null)); - ALL_SUPPORTED_TYPES_OBJECT = new AllSupportedTypes("bar", 0.0, 0L, Double.NaN, Double.POSITIVE_INFINITY, - Double.NEGATIVE_INFINITY, true, false, - new SingleComponent("bar"), DATE, - TIMESTAMP, ImmutableList.of("foo"), null, BLOB, GEO_POINT, - ImmutableMap.of("foo", SINGLE_COMPONENT_OBJECT.foo())); + ALL_SUPPORTED_TYPES_OBJECT = + new AllSupportedTypes( + "bar", + 0.0, + 0L, + Double.NaN, + Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY, + true, + false, + new SingleComponent("bar"), + DATE, + TIMESTAMP, + ImmutableList.of("foo"), + null, + BLOB, + GEO_POINT, + ImmutableMap.of("foo", SINGLE_COMPONENT_OBJECT.foo())); ALL_SUPPORTED_TYPES_PROTO = ImmutableMap.builder() .put("foo", Value.newBuilder().setStringValue("bar").build()) @@ -194,7 +183,7 @@ public record AllSupportedTypes ( "arrayValue", Value.newBuilder() .setArrayValue( - ArrayValue.newBuilder().addValues(Value.newBuilder().setStringValue("foo"))) + ArrayValue.newBuilder().addValues(Value.newBuilder().setStringValue("foo"))) .build()) .put("nullValue", Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build()) .put("bytesValue", Value.newBuilder().setBytesValue(BLOB.toByteString()).build()) @@ -202,7 +191,7 @@ public record AllSupportedTypes ( "geoPointValue", Value.newBuilder() .setGeoPointValue( - LatLng.newBuilder().setLatitude(50.1430847).setLongitude(-122.9477780)) + LatLng.newBuilder().setLatitude(50.1430847).setLongitude(-122.9477780)) .build()) .put( "model", @@ -216,9 +205,9 @@ public record AllSupportedTypes ( NESTED_RECORD_OBJECT = new NestedRecord(SINGLE_COMPONENT_OBJECT, ALL_SUPPORTED_TYPES_OBJECT); - NESTED_RECORD_WITH_POJO_OBJECT = new NestedRecordWithPOJO(new SingleField(), ALL_SUPPORTED_TYPES_OBJECT); + NESTED_RECORD_WITH_POJO_OBJECT = + new NestedRecordWithPOJO(new SingleField(), ALL_SUPPORTED_TYPES_OBJECT); NESTED_POJO_WITH_RECORD_OBJECT = new NestedPOJOWithRecord(); } - } diff --git a/java-firestore/samples/snippets/src/main/java/com/example/firestore/Quickstart.java b/java-firestore/samples/snippets/src/main/java/com/example/firestore/Quickstart.java index 8e057413c298..9b8770343f1c 100644 --- a/java-firestore/samples/snippets/src/main/java/com/example/firestore/Quickstart.java +++ b/java-firestore/samples/snippets/src/main/java/com/example/firestore/Quickstart.java @@ -32,8 +32,8 @@ import java.util.Map; /** - * A simple Quick start application demonstrating how to connect to Firestore - * and add and query documents. + * A simple Quick start application demonstrating how to connect to Firestore and add and query + * documents. */ public class Quickstart { @@ -55,9 +55,7 @@ public Quickstart(String projectId) throws Exception { this.db = db; } - /** - * Initialize Firestore using default project ID. - */ + /** Initialize Firestore using default project ID. */ public Quickstart() { // [START firestore_setup_client_create] @@ -79,49 +77,52 @@ Firestore getDb() { */ void addDocument(String docName) throws Exception { switch (docName) { - case "alovelace": { - // [START firestore_setup_dataset_pt1] - DocumentReference docRef = db.collection("users").document("alovelace"); - // Add document data with id "alovelace" using a hashmap - Map data = new HashMap<>(); - data.put("first", "Ada"); - data.put("last", "Lovelace"); - data.put("born", 1815); - //asynchronously write data - ApiFuture result = docRef.set(data); - // ... - // result.get() blocks on response - System.out.println("Update time : " + result.get().getUpdateTime()); - // [END firestore_setup_dataset_pt1] - break; - } - case "aturing": { - // [START firestore_setup_dataset_pt2] - DocumentReference docRef = db.collection("users").document("aturing"); - // Add document data with an additional field ("middle") - Map data = new HashMap<>(); - data.put("first", "Alan"); - data.put("middle", "Mathison"); - data.put("last", "Turing"); - data.put("born", 1912); - - ApiFuture result = docRef.set(data); - System.out.println("Update time : " + result.get().getUpdateTime()); - // [END firestore_setup_dataset_pt2] - break; - } - case "cbabbage": { - DocumentReference docRef = db.collection("users").document("cbabbage"); - Map data = - new ImmutableMap.Builder() - .put("first", "Charles") - .put("last", "Babbage") - .put("born", 1791) - .build(); - ApiFuture result = docRef.set(data); - System.out.println("Update time : " + result.get().getUpdateTime()); - break; - } + case "alovelace": + { + // [START firestore_setup_dataset_pt1] + DocumentReference docRef = db.collection("users").document("alovelace"); + // Add document data with id "alovelace" using a hashmap + Map data = new HashMap<>(); + data.put("first", "Ada"); + data.put("last", "Lovelace"); + data.put("born", 1815); + // asynchronously write data + ApiFuture result = docRef.set(data); + // ... + // result.get() blocks on response + System.out.println("Update time : " + result.get().getUpdateTime()); + // [END firestore_setup_dataset_pt1] + break; + } + case "aturing": + { + // [START firestore_setup_dataset_pt2] + DocumentReference docRef = db.collection("users").document("aturing"); + // Add document data with an additional field ("middle") + Map data = new HashMap<>(); + data.put("first", "Alan"); + data.put("middle", "Mathison"); + data.put("last", "Turing"); + data.put("born", 1912); + + ApiFuture result = docRef.set(data); + System.out.println("Update time : " + result.get().getUpdateTime()); + // [END firestore_setup_dataset_pt2] + break; + } + case "cbabbage": + { + DocumentReference docRef = db.collection("users").document("cbabbage"); + Map data = + new ImmutableMap.Builder() + .put("first", "Charles") + .put("last", "Babbage") + .put("born", 1791) + .build(); + ApiFuture result = docRef.set(data); + System.out.println("Update time : " + result.get().getUpdateTime()); + break; + } default: } } @@ -129,8 +130,7 @@ void addDocument(String docName) throws Exception { void runQuery() throws Exception { // [START firestore_setup_add_query] // asynchronously query for all users born before 1900 - ApiFuture query = - db.collection("users").whereLessThan("born", 1900).get(); + ApiFuture query = db.collection("users").whereLessThan("born", 1900).get(); // ... // query.get() blocks on response QuerySnapshot querySnapshot = query.get();