From 0f540bbdceb2c2a47ce8f758c07f09cf30413dea Mon Sep 17 00:00:00 2001 From: David Noble Date: Wed, 21 Aug 2019 18:42:13 -0700 Subject: [PATCH] Checkpoint for safe keeping --- .gitignore | 1 + jre/pom.xml | 273 +- .../hybridrow/DefaultSpanResizer.java | 37 + .../serialization/hybridrow/Float128.java | 75 + .../hybridrow/HybridRowHeader.java | 51 + .../hybridrow/HybridRowVersion.java | 51 + .../serialization/hybridrow/ISpanResizer.java | 26 + .../hybridrow/MemorySpanResizer.java | 56 + .../serialization/hybridrow/NullValue.java | 67 + .../serialization/hybridrow/Result.java | 71 + .../serialization/hybridrow/RowBuffer.java | 3483 +++++++++++++++++ .../serialization/hybridrow/RowCursor.java | 235 ++ .../hybridrow/RowCursorExtensions.java | 127 + .../serialization/hybridrow/RowOptions.java | 82 + .../serialization/hybridrow/SchemaId.java | 127 + .../serialization/hybridrow/UnixDateTime.java | 98 + .../hybridrow/internal/MurmurHash3.java | 245 ++ .../internal/Utf8StringJsonConverter.java | 34 + .../hybridrow/io/IRowSerializable.java | 22 + .../serialization/hybridrow/io/RowReader.java | 1255 ++++++ .../hybridrow/io/RowReaderExtensions.java | 98 + .../serialization/hybridrow/io/RowWriter.java | 1133 ++++++ .../json/RowReaderJsonExtensions.java | 492 +++ .../hybridrow/json/RowReaderJsonSettings.java | 54 + .../layouts/ILayoutSequenceWritable.java | 32 + .../layouts/ILayoutSpanReadable.java | 26 + .../layouts/ILayoutSpanWritable.java | 32 + .../hybridrow/layouts/ILayoutType.java | 11 + .../layouts/ILayoutUtf8SpanReadable.java | 23 + .../layouts/ILayoutUtf8SpanWritable.java | 28 + .../hybridrow/layouts/Layout.java | 195 + .../hybridrow/layouts/LayoutArray.java | 53 + .../hybridrow/layouts/LayoutBinary.java | 298 ++ .../hybridrow/layouts/LayoutBit.java | 155 + .../hybridrow/layouts/LayoutBoolean.java | 96 + .../hybridrow/layouts/LayoutBuilder.java | 169 + .../hybridrow/layouts/LayoutCode.java | 114 + .../hybridrow/layouts/LayoutCodeTraits.java | 42 + .../hybridrow/layouts/LayoutColumn.java | 246 ++ .../layouts/LayoutCompilationException.java | 26 + .../hybridrow/layouts/LayoutCompiler.java | 370 ++ .../hybridrow/layouts/LayoutDateTime.java | 88 + .../hybridrow/layouts/LayoutDecimal.java | 90 + .../hybridrow/layouts/LayoutEndScope.java | 43 + .../hybridrow/layouts/LayoutFloat128.java | 87 + .../hybridrow/layouts/LayoutFloat32.java | 86 + .../hybridrow/layouts/LayoutFloat64.java | 86 + .../hybridrow/layouts/LayoutGuid.java | 89 + .../hybridrow/layouts/LayoutIndexedScope.java | 26 + .../hybridrow/layouts/LayoutInt16.java | 86 + .../hybridrow/layouts/LayoutInt32.java | 86 + .../hybridrow/layouts/LayoutInt64.java | 86 + .../hybridrow/layouts/LayoutInt8.java | 86 + .../layouts/LayoutMongoDbObjectId.java | 88 + .../hybridrow/layouts/LayoutNull.java | 90 + .../hybridrow/layouts/LayoutNullable.java | 106 + .../hybridrow/layouts/LayoutObject.java | 50 + .../layouts/LayoutPropertyScope.java | 14 + .../hybridrow/layouts/LayoutResolver.java | 11 + .../layouts/LayoutResolverNamespace.java | 75 + .../layouts/LayoutResolverSimple.java | 20 + .../hybridrow/layouts/LayoutScope.java | 157 + .../hybridrow/layouts/LayoutTagged.java | 83 + .../hybridrow/layouts/LayoutTagged2.java | 98 + .../hybridrow/layouts/LayoutTuple.java | 86 + .../hybridrow/layouts/LayoutType.java | 525 +++ .../hybridrow/layouts/LayoutType1.java | 124 + .../hybridrow/layouts/LayoutTypedArray.java | 81 + .../hybridrow/layouts/LayoutTypedMap.java | 100 + .../hybridrow/layouts/LayoutTypedSet.java | 85 + .../hybridrow/layouts/LayoutTypedTuple.java | 99 + .../hybridrow/layouts/LayoutUDT.java | 64 + .../hybridrow/layouts/LayoutUInt16.java | 97 + .../hybridrow/layouts/LayoutUInt32.java | 97 + .../hybridrow/layouts/LayoutUInt64.java | 97 + .../hybridrow/layouts/LayoutUInt8.java | 97 + .../hybridrow/layouts/LayoutUniqueScope.java | 151 + .../hybridrow/layouts/LayoutUnixDateTime.java | 87 + .../hybridrow/layouts/LayoutUtf8.java | 188 + .../hybridrow/layouts/LayoutVarInt.java | 114 + .../hybridrow/layouts/LayoutVarUInt.java | 131 + .../layouts/SamplingStringComparer.java | 48 + .../layouts/SamplingUtf8StringComparer.java | 50 + .../hybridrow/layouts/StringToken.java | 90 + .../hybridrow/layouts/StringTokenizer.java | 123 + .../hybridrow/layouts/SystemSchema.java | 53 + .../hybridrow/layouts/TypeArgument.java | 125 + .../hybridrow/layouts/TypeArgumentList.java | 206 + .../hybridrow/layouts/UpdateOptions.java | 74 + .../hybridrow/recordio/Record.java | 38 + .../hybridrow/recordio/RecordIOFormatter.java | 76 + .../hybridrow/recordio/RecordIOParser.java | 335 ++ .../hybridrow/recordio/RecordIOStream.java | 368 ++ .../hybridrow/recordio/RecordSerializer.java | 53 + .../hybridrow/recordio/Segment.java | 37 + .../hybridrow/recordio/SegmentSerializer.java | 101 + .../hybridrow/schemas/ArrayPropertyType.java | 30 + .../hybridrow/schemas/MapPropertyType.java | 47 + .../hybridrow/schemas/Namespace.java | 93 + .../hybridrow/schemas/ObjectPropertyType.java | 42 + .../hybridrow/schemas/PartitionKey.java | 26 + .../hybridrow/schemas/PrimarySortKey.java | 43 + .../schemas/PrimitivePropertyType.java | 46 + .../hybridrow/schemas/Property.java | 68 + .../schemas/PropertySchemaConverter.java | 85 + .../hybridrow/schemas/PropertyType.java | 62 + .../hybridrow/schemas/Schema.java | 235 ++ .../hybridrow/schemas/SchemaException.java | 26 + .../hybridrow/schemas/SchemaHash.java | 232 ++ .../schemas/SchemaLanguageVersion.java | 51 + .../hybridrow/schemas/SchemaOptions.java | 67 + .../hybridrow/schemas/SchemaValidator.java | 277 ++ .../hybridrow/schemas/ScopePropertyType.java | 24 + .../hybridrow/schemas/SetPropertyType.java | 33 + .../hybridrow/schemas/SortDirection.java | 54 + .../hybridrow/schemas/StaticKey.java | 27 + .../hybridrow/schemas/StorageKind.java | 72 + .../schemas/StrictBooleanConverter.java | 38 + .../schemas/StrictIntegerConverter.java | 48 + .../hybridrow/schemas/TaggedPropertyType.java | 42 + .../hybridrow/schemas/TuplePropertyType.java | 37 + .../hybridrow/schemas/TypeKind.java | 227 ++ .../hybridrow/schemas/UdtPropertyType.java | 59 + jre/src/main/java/tangible/Action0Param.java | 10 + jre/src/main/java/tangible/Func0Param.java | 10 + jre/src/main/java/tangible/Func1Param.java | 10 + jre/src/main/java/tangible/ListHelper.java | 142 + jre/src/main/java/tangible/OutObject.java | 15 + jre/src/main/java/tangible/RefObject.java | 19 + jre/src/main/java/tangible/StringHelper.java | 357 ++ .../main/java/tangible/TryParseHelper.java | 76 + .../hybridrow/perf/BenchmarkSuiteBase.java | 139 + .../perf/BsonJsonModelRowGenerator.java | 131 + .../hybridrow/perf/BsonReaderExtensions.java | 55 + .../hybridrow/perf/BsonRowGenerator.java | 306 ++ .../perf/CassandraHotel/Protobuf/Address.java | 317 ++ .../Available_Rooms_By_Hotel_Date.java | 321 ++ .../CassandraHotelSchemaReflection.java | 121 + .../perf/CassandraHotel/Protobuf/Guests.java | 446 +++ .../perf/CassandraHotel/Protobuf/Hotels.java | 317 ++ .../CassandraHotel/Protobuf/PostalCode.java | 232 ++ .../perf/CodeGenMicroBenchmarkSuite.java | 311 ++ .../hybridrow/perf/CodeGenRowGenerator.java | 1157 ++++++ .../perf/GenerateBenchmarkSuite.java | 111 + .../hybridrow/perf/JsonModelRowGenerator.java | 186 + .../hybridrow/perf/Measurements.java | 63 + .../perf/MicroBenchmarkSuiteBase.java | 126 + .../hybridrow/perf/ProtobufRowGenerator.java | 332 ++ .../hybridrow/perf/ReaderBenchmark.java | 314 ++ .../hybridrow/perf/RowReaderExtensions.java | 88 + .../perf/SchematizedMicroBenchmarkSuite.java | 639 +++ .../hybridrow/perf/TestData.java | 20 + .../UnschematizedMicroBenchmarkSuite.java | 341 ++ .../hybridrow/unit/ArrayAssert.java | 46 + .../hybridrow/unit/AssertThrowsException.java | 111 + .../unit/CrossVersioningUnitTests.java | 614 +++ .../unit/CustomerExampleUnitTests.java | 886 +++++ .../hybridrow/unit/DeleteRowDispatcher.java | 161 + .../hybridrow/unit/IDispatchable.java | 11 + .../hybridrow/unit/IDispatcher.java | 41 + .../unit/LayoutCompilerUnitTests.java | 3234 +++++++++++++++ .../hybridrow/unit/LayoutTypeUnitTests.java | 47 + .../hybridrow/unit/NullRowDispatcher.java | 85 + .../hybridrow/unit/NullableUnitTests.java | 749 ++++ .../hybridrow/unit/PermuteExtensions.java | 34 + .../unit/RandomGeneratorUnitTests.java | 78 + .../hybridrow/unit/ReadRowDispatcher.java | 234 ++ .../hybridrow/unit/RecordIOUnitTests.java | 237 ++ .../hybridrow/unit/ResultAssert.java | 81 + .../hybridrow/unit/RowBufferUnitTests.java | 71 + .../unit/RowOperationDispatcher.java | 406 ++ .../hybridrow/unit/RowReaderUnitTests.java | 424 ++ .../hybridrow/unit/RowWriterUnitTests.java | 505 +++ .../hybridrow/unit/SchemaHashUnitTests.java | 272 ++ .../hybridrow/unit/SchemaIdUnitTests.java | 45 + .../hybridrow/unit/SchemaUnitTests.java | 992 +++++ .../hybridrow/unit/SerializerUnitTest.java | 313 ++ .../hybridrow/unit/TaggedUnitTests.java | 256 ++ .../hybridrow/unit/TupleUnitTests.java | 1099 ++++++ .../hybridrow/unit/TypedArrayUnitTests.java | 661 ++++ .../hybridrow/unit/TypedMapUnitTests.java | 1572 ++++++++ .../hybridrow/unit/TypedSetUnitTests.java | 1992 ++++++++++ .../unit/UpdateOptionsUnitTests.java | 21 + .../hybridrow/unit/WriteRowDispatcher.java | 242 ++ .../unit/customerschema/Address.java | 48 + .../customerschema/AddressSerializer.java | 94 + .../hybridrow/unit/customerschema/Guest.java | 95 + .../hybridrow/unit/customerschema/Hotel.java | 51 + .../unit/customerschema/PostalCode.java | 42 + .../customerschema/PostalCodeSerializer.java | 63 + .../unit/internal/MurmurHash3UnitTests.java | 112 + 191 files changed, 40442 insertions(+), 226 deletions(-) create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/DefaultSpanResizer.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/Float128.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/HybridRowHeader.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/HybridRowVersion.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/ISpanResizer.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/MemorySpanResizer.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/NullValue.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/Result.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowBuffer.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowCursor.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowCursorExtensions.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowOptions.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/SchemaId.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/UnixDateTime.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/internal/MurmurHash3.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/internal/Utf8StringJsonConverter.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/IRowSerializable.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowReader.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowReaderExtensions.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowWriter.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/json/RowReaderJsonExtensions.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/json/RowReaderJsonSettings.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSequenceWritable.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSpanReadable.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSpanWritable.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutUtf8SpanReadable.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutUtf8SpanWritable.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/Layout.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutArray.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBinary.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBit.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBoolean.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBuilder.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCode.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCodeTraits.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutColumn.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCompilationException.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCompiler.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutDateTime.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutDecimal.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutEndScope.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat128.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat32.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat64.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutGuid.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutIndexedScope.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt16.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt32.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt64.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt8.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutMongoDbObjectId.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutNull.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutNullable.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutObject.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutPropertyScope.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolver.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolverNamespace.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolverSimple.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutScope.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTagged.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTagged2.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTuple.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutType1.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedArray.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedMap.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedSet.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedTuple.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUDT.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt16.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt32.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt64.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt8.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUniqueScope.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUnixDateTime.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUtf8.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutVarInt.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutVarUInt.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SamplingStringComparer.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SamplingUtf8StringComparer.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/StringToken.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/StringTokenizer.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SystemSchema.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/TypeArgument.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/TypeArgumentList.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/UpdateOptions.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/Record.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOFormatter.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOParser.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOStream.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordSerializer.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/Segment.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/SegmentSerializer.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ArrayPropertyType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/MapPropertyType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Namespace.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ObjectPropertyType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PartitionKey.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PrimarySortKey.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PrimitivePropertyType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Property.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PropertySchemaConverter.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PropertyType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Schema.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaException.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaHash.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaLanguageVersion.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaOptions.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaValidator.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ScopePropertyType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SetPropertyType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SortDirection.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StaticKey.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StorageKind.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StrictBooleanConverter.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StrictIntegerConverter.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TaggedPropertyType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TuplePropertyType.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TypeKind.java create mode 100644 jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/UdtPropertyType.java create mode 100644 jre/src/main/java/tangible/Action0Param.java create mode 100644 jre/src/main/java/tangible/Func0Param.java create mode 100644 jre/src/main/java/tangible/Func1Param.java create mode 100644 jre/src/main/java/tangible/ListHelper.java create mode 100644 jre/src/main/java/tangible/OutObject.java create mode 100644 jre/src/main/java/tangible/RefObject.java create mode 100644 jre/src/main/java/tangible/StringHelper.java create mode 100644 jre/src/main/java/tangible/TryParseHelper.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BenchmarkSuiteBase.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonJsonModelRowGenerator.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonReaderExtensions.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonRowGenerator.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Address.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Available_Rooms_By_Hotel_Date.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/CassandraHotelSchemaReflection.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Guests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Hotels.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/PostalCode.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CodeGenMicroBenchmarkSuite.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CodeGenRowGenerator.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/GenerateBenchmarkSuite.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/JsonModelRowGenerator.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/Measurements.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/MicroBenchmarkSuiteBase.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/ProtobufRowGenerator.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/ReaderBenchmark.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/RowReaderExtensions.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/SchematizedMicroBenchmarkSuite.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/TestData.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/UnschematizedMicroBenchmarkSuite.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ArrayAssert.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/AssertThrowsException.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/CrossVersioningUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/CustomerExampleUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/DeleteRowDispatcher.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/IDispatchable.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/IDispatcher.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/LayoutCompilerUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/LayoutTypeUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/NullRowDispatcher.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/NullableUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/PermuteExtensions.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RandomGeneratorUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ReadRowDispatcher.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RecordIOUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ResultAssert.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowBufferUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowOperationDispatcher.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowReaderUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowWriterUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaHashUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaIdUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SerializerUnitTest.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TaggedUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TupleUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedArrayUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedMapUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedSetUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/UpdateOptionsUnitTests.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/WriteRowDispatcher.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Address.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/AddressSerializer.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Guest.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Hotel.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/PostalCode.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/PostalCodeSerializer.java create mode 100644 jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/internal/MurmurHash3UnitTests.java diff --git a/.gitignore b/.gitignore index 3e759b7..43c6326 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,7 @@ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ +target/ # Visual Studio 2015/2017 cache/options directory .vs/ diff --git a/jre/pom.xml b/jre/pom.xml index 3477993..11639b7 100644 --- a/jre/pom.xml +++ b/jre/pom.xml @@ -2,22 +2,19 @@ Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. --> - + + 4.0.0 - - com.azure - azure-data-sdk-parent - 1.1.0 - ../../pom.data.xml - - com.microsoft.azure - azure-cosmos-parent - 3.1.0 - pom + com.azure.data + azure-cosmos-serialization + 2.9.5 + jar - Microsoft Azure Cosmos DB SQL API - This package contains Microsoft Azure SDK for Azure Cosmos DB SQL API (with Reactive Extension RX support) + Microsoft Azure Cosmos Serialization API + This package contains Microsoft Azure Serialization API for Azure Cosmos DB https://github.com/Azure/azure-sdk-for-java @@ -32,225 +29,66 @@ Licensed under the MIT License. + ${project.basedir}/target/collectedArtifactsForRelease + UTF-8 UTF-8 - 3.1.0 - 3.1.0 - 4.1.0 - 1.2.0 - 1.10.19 - 4.1.38.Final - 2.0.25.Final - 3.1.0 - 27.0.1-jre - 3.2.9.RELEASE + unit - ${project.basedir}/target/collectedArtifactsForRelease + 27.0.1-jre + 1.10.19 + 3.11.0 - - - - com.microsoft.azure - azure-cosmos - ${project.parent.version} - + - - org.mockito - mockito-core - ${mockito.version} - test - + + com.google.guava + guava + ${guava.version} + - - io.projectreactor - reactor-core - ${reactor-core.version} - + + org.mockito + mockito-core + ${mockito.version} + test + - - io.netty - netty-codec-http - ${netty.version} - + + org.mongodb + bson + ${mongodb.version} + test + - - com.google.guava - guava - ${guava.version} - - - - io.netty - netty-tcnative - ${netty-tcnative.version} - linux-x86_64 - - - - io.netty - netty-handler - ${netty.version} - - - + - - - unit - - default - unit - - - true - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - - - - - - - fast - - simple,cosmosv3 - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - long - - long - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - direct - - direct - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - multi-master - - multi-master - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - examples + + unit - - samples,examples + default + unit + + true + org.apache.maven.plugins - maven-failsafe-plugin + maven-surefire-plugin - - - - integration-test - verify - - - - - - - - - - emulator - - emulator - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - non-emulator - - non-emulator - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - - - - - e2e - - e2e - - - - - org.apache.maven.plugins - maven-failsafe-plugin + @@ -336,7 +174,6 @@ Licensed under the MIT License. 1.8 1.8 - false @@ -357,22 +194,10 @@ Licensed under the MIT License. 1.8 - + default-cli - - - - - - - - + run @@ -390,10 +215,6 @@ Licensed under the MIT License. - - microsoft-azure-cosmos - microsoft-azure-cosmos-benchmark - microsoft-azure-cosmos-examples - + diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/DefaultSpanResizer.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/DefaultSpanResizer.java new file mode 100644 index 0000000..214b5e2 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/DefaultSpanResizer.java @@ -0,0 +1,37 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +public class DefaultSpanResizer implements ISpanResizer { + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly DefaultSpanResizer Default = new + // DefaultSpanResizer(); + public static final DefaultSpanResizer Default = new DefaultSpanResizer(); + + private DefaultSpanResizer() { + } + + /** + * + */ + + public final Span Resize(int minimumLength) { + return Resize(minimumLength, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public Span Resize(int minimumLength, Span buffer = default) + public final Span Resize(int minimumLength, Span buffer) { + //C# TO JAVA CONVERTER WARNING: Java does not allow direct instantiation of arrays of generic type parameters: + //ORIGINAL LINE: Span next = new Memory(new T[Math.Max(minimumLength, buffer.Length)]).Span; + Span next = (new Memory((T[])new Object[Math.max(minimumLength, buffer.Length)])).Span; + if (!buffer.IsEmpty && next.Slice(0, buffer.Length) != buffer) { + buffer.CopyTo(next); + } + + return next; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/Float128.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/Float128.java new file mode 100644 index 0000000..73da2ba --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/Float128.java @@ -0,0 +1,75 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1051 // Do not declare visible instance fields + + +/** + * An IEEE 128-bit floating point value. + *

+ * A binary integer decimal representation of a 128-bit decimal value, supporting 34 decimal digits of + * significand and an exponent range of -6143 to +6144. + * + * + * Source Link + * + * Wikipedia: + * https: //en.wikipedia.org/wiki/Decimal128_floating-point_format + * + * The spec: https: //ieeexplore.ieee.org/document/4610935 + * + * Decimal Encodings: http: //speleotrove.com/decimal/decbits.html + * + * + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [DebuggerDisplay("{" + nameof(Float128.Low) + "," + nameof(Float128.High) + "}")][StructLayout +// (LayoutKind.Sequential, Pack = 1)] public readonly struct Float128 +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: [DebuggerDisplay("{" + nameof(Float128.Low) + "," + nameof(Float128.High) + "}")][StructLayout +// (LayoutKind.Sequential, Pack = 1)] public readonly struct Float128 +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: +public final class Float128 { + /** + * The size (in bytes) of a . + */ + public static final int Size = (Long.SIZE / Byte.SIZE) + (Long.SIZE / Byte.SIZE); + /** + * The high-order 64 bits of the IEEE 754-2008 128-bit decimal floating point, using the BID + * encoding scheme. + */ + public long High; + /** + * The low-order 64 bits of the IEEE 754-2008 128-bit decimal floating point, using the BID + * encoding scheme. + */ + public long Low; + + /** + * Initializes a new instance of the struct. + * + * @param high the high-order 64 bits. + * @param low the low-order 64 bits. + */ + public Float128() { + } + + public Float128(long high, long low) { + this.High = high; + this.Low = low; + } + + public Float128 clone() { + Float128 varCopy = new Float128(); + + varCopy.Low = this.Low; + varCopy.High = this.High; + + return varCopy; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/HybridRowHeader.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/HybridRowHeader.java new file mode 100644 index 0000000..a7a30f1 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/HybridRowHeader.java @@ -0,0 +1,51 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +/** + * Describes the header the precedes all valid Hybrid Rows. + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct HybridRowHeader +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: [StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct HybridRowHeader +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: +public final class HybridRowHeader { + /** + * Size (in bytes) of a serialized header. + */ + public static final int Size = (HybridRowVersion.SIZE / Byte.SIZE) + azure.data.cosmos.serialization.hybridrow.SchemaId.Size; + /** + * The unique identifier of the schema whose layout was used to write this row. + */ + private SchemaId SchemaId = new SchemaId(); + /** + * The version of the HybridRow library used to write this row. + */ + private HybridRowVersion Version = HybridRowVersion.values()[0]; + + /** + * Initializes a new instance of the struct. + * + * @param version The version of the HybridRow library used to write this row. + * @param schemaId The unique identifier of the schema whose layout was used to write this row. + */ + public HybridRowHeader() { + } + + public HybridRowHeader(HybridRowVersion version, SchemaId schemaId) { + this.Version = version; + this.SchemaId = schemaId.clone(); + } + + public SchemaId getSchemaId() { + return SchemaId; + } + + public HybridRowVersion getVersion() { + return Version; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/HybridRowVersion.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/HybridRowVersion.java new file mode 100644 index 0000000..8b79e60 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/HybridRowVersion.java @@ -0,0 +1,51 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1028 // Enum Storage should be Int32 + +/** + * Versions of HybridRow. + * A version from this list MUST be inserted in the version BOM at the beginning of all rows. + */ +//C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: +//ORIGINAL LINE: public enum HybridRowVersion : byte +public enum HybridRowVersion { + Invalid((byte)0), + + /** + * Initial version of the HybridRow format. + */ + V1((byte)0x81); + + public static final int SIZE = java.lang.Byte.SIZE; + private static java.util.HashMap mappings; + private byte byteValue; + + HybridRowVersion(byte value) { + byteValue = value; + getMappings().put(value, this); + } + + public byte getValue() { + return byteValue; + } + + public static HybridRowVersion forValue(byte value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (HybridRowVersion.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/ISpanResizer.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/ISpanResizer.java new file mode 100644 index 0000000..34fef1b --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/ISpanResizer.java @@ -0,0 +1,26 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +public interface ISpanResizer { + /** + * Resizes an existing a buffer. + * The type of the elements of the memory. + * + * @param minimumLength The minimum required length (in elements) of the memory. + * @param buffer Optional existing memory to be copied to the new buffer. Ownership of is + * transferred as part of this call and it should not be used by the caller after this call + * completes. + * @return A new memory whose size is at least as big as + * and containing the content of . + */ + + Span Resize(int minimumLength); + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: Span Resize(int minimumLength, Span buffer = default); + Span Resize(int minimumLength, Span buffer); +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/MemorySpanResizer.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/MemorySpanResizer.java new file mode 100644 index 0000000..6218985 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/MemorySpanResizer.java @@ -0,0 +1,56 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class MemorySpanResizer implements ISpanResizer { + private Memory memory; + + + public MemorySpanResizer() { + this(0); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public MemorySpanResizer(int initialCapacity = 0) + public MemorySpanResizer(int initialCapacity) { + checkArgument(initialCapacity >= 0); + + //C# TO JAVA CONVERTER WARNING: Java does not allow direct instantiation of arrays of generic type parameters: + //ORIGINAL LINE: this.memory = initialCapacity == 0 ? default : new Memory(new T[initialCapacity]); + this.memory = initialCapacity == 0 ? null : new Memory((T[])new Object[initialCapacity]); + } + + public Memory getMemory() { + return this.memory; + } + + /** + * + */ + + public Span Resize(int minimumLength) { + return Resize(minimumLength, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public Span Resize(int minimumLength, Span buffer = default) + public Span Resize(int minimumLength, Span buffer) { + if (this.memory.Length < minimumLength) { + //C# TO JAVA CONVERTER WARNING: Java does not allow direct instantiation of arrays of generic type + // parameters: + //ORIGINAL LINE: this.memory = new Memory(new T[Math.Max(minimumLength, buffer.Length)]); + this.memory = new Memory((T[])new Object[Math.max(minimumLength, buffer.Length)]); + } + + Span next = this.memory.Span; + if (!buffer.IsEmpty && next.Slice(0, buffer.Length) != buffer) { + buffer.CopyTo(next); + } + + return next; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/NullValue.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/NullValue.java new file mode 100644 index 0000000..baacc9e --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/NullValue.java @@ -0,0 +1,67 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +/** + * The literal null value. + *

+ * May be stored hybrid row to indicate the literal null value. Typically this value should + * not be used and the corresponding column should be absent from the row. + */ +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public readonly struct NullValue : IEquatable +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: +public final class NullValue implements IEquatable { + /** + * The default null literal. + * This is the same value as default(). + */ + public static final NullValue Default = new NullValue(); + + /** + * Returns true if this is the same value as . + * + * @param other The value to compare against. + * @return True if the two values are the same. + */ + public boolean equals(NullValue other) { + return true; + } + + /** + * overload. + */ + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + return obj instanceof NullValue && this.equals((NullValue)obj); + } + + /** + * overload. + */ + @Override + public int hashCode() { + return 42; + } + + /** + * Operator == overload. + */ + public static boolean opEquals(NullValue left, NullValue right) { + return left.equals(right.clone()); + } + + /** + * Operator != overload. + */ + public static boolean opNotEquals(NullValue left, NullValue right) { + return !left.equals(right.clone()); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/Result.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/Result.java new file mode 100644 index 0000000..ee96566 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/Result.java @@ -0,0 +1,71 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +public enum Result { + Success(0), + Failure(1), + NotFound(2), + Exists(3), + TooBig(4), + + /** + * The type of an existing field does not match the expected type for this operation. + */ + TypeMismatch(5), + + /** + * An attempt to write in a read-only scope. + */ + InsufficientPermissions(6), + + /** + * An attempt to write a field that did not match its (optional) type constraints. + */ + TypeConstraint(7), + + /** + * The byte sequence could not be parsed as a valid row. + */ + InvalidRow(8), + + /** + * The byte sequence was too short for the requested action. + */ + InsufficientBuffer(9), + + /** + * The operation was cancelled. + */ + Canceled(10); + + public static final int SIZE = java.lang.Integer.SIZE; + private static java.util.HashMap mappings; + private int intValue; + + Result(int value) { + intValue = value; + getMappings().put(value, this); + } + + public int getValue() { + return intValue; + } + + public static Result forValue(int value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (Result.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowBuffer.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowBuffer.java new file mode 100644 index 0000000..e870188 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowBuffer.java @@ -0,0 +1,3483 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +import azure.data.cosmos.serialization.hybridrow.RowBuffer.UniqueIndexItem; +import azure.data.cosmos.serialization.hybridrow.layouts.Layout; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutBit; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutColumn; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutEndScope; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutResolver; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutScope; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutType; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutTypedMap; +import azure.data.cosmos.serialization.hybridrow.layouts.StringToken; +import azure.data.cosmos.serialization.hybridrow.layouts.TypeArgument; +import azure.data.cosmos.serialization.hybridrow.layouts.TypeArgumentList; +import azure.data.cosmos.serialization.hybridrow.layouts.UpdateOptions; + +import java.io.InputStream; +import java.io.OutputStream; +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.UUID; + +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutType.MongoDbObjectId; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public ref struct RowBuffer +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# ref struct: +public final class RowBuffer { + /** + * A sequence of bytes managed by this . + *

+ * A Hybrid Row begins in the 0-th byte of the . Remaining byte + * sequence is defined by the Hybrid Row grammar. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private Span buffer; + private Span buffer; + /** + * The length of row in bytes. + */ + private int length; + /** + * Resizer for growing the memory buffer. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private readonly ISpanResizer resizer; + private ISpanResizer resizer; + /** + * The resolver for UDTs. + */ + private LayoutResolver resolver; + + /** + * Initializes a new instance of the struct. + * + * @param capacity Initial buffer capacity. + * @param resizer Optional memory resizer. + */ + + public RowBuffer(int capacity) { + this(capacity, null); + } + + public RowBuffer() { + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public RowBuffer(int capacity, ISpanResizer resizer = default) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public RowBuffer(int capacity, ISpanResizer resizer) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.resizer = resizer != null ? resizer : DefaultSpanResizer.Default; + this.resizer = resizer != null ? resizer : DefaultSpanResizer < Byte >.Default; + this.buffer = this.resizer.Resize(capacity); + this.length = 0; + this.resolver = null; + } + + /** + * Initializes a new instance of the struct from an existing buffer. + * + * @param buffer The buffer. The row takes ownership of the buffer and the caller should not + * maintain a pointer or mutate the buffer after this call returns. + * @param version The version of the Hybrid Row format to used to encoding the buffer. + * @param resolver The resolver for UDTs. + * @param resizer Optional memory resizer. + */ + + public RowBuffer(Span buffer, HybridRowVersion version, LayoutResolver resolver) { + this(buffer, version, resolver, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public RowBuffer(Span buffer, HybridRowVersion version, LayoutResolver resolver, + // ISpanResizer resizer = default) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public RowBuffer(Span buffer, HybridRowVersion version, LayoutResolver resolver, ISpanResizer resizer) { + checkArgument(buffer.Length >= HybridRowHeader.Size); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.resizer = resizer != null ? resizer : DefaultSpanResizer.Default; + this.resizer = resizer != null ? resizer : DefaultSpanResizer < Byte >.Default; + this.length = buffer.Length; + this.buffer = buffer; + this.resolver = resolver; + + HybridRowHeader header = this.ReadHeader(0).clone(); + Contract.Invariant(header.getVersion() == version); + Layout layout = resolver.Resolve(header.getSchemaId().clone()); + checkState(azure.data.cosmos.serialization.hybridrow.SchemaId.opEquals(header.getSchemaId().clone(), layout.getSchemaId().clone())); + Contract.Invariant(HybridRowHeader.Size + layout.getSize() <= this.length); + } + + /** + * The root header for the row. + */ + public HybridRowHeader getHeader() { + return this.ReadHeader(0).clone(); + } + + /** + * The length of row in bytes. + */ + public int getLength() { + return this.length; + } + + /** + * The resolver for UDTs. + */ + public LayoutResolver getResolver() { + return this.resolver; + } + + /** + * Compute the byte offset from the beginning of the row for a given variable column's value. + * + * @param layout The (optional) layout of the current scope. + * @param scopeOffset The 0-based offset to the beginning of the scope's value. + * @param varIndex The 0-based index of the variable column within the variable segment. + * @return The byte offset from the beginning of the row where the variable column's value should be + * located. + */ + public int ComputeVariableValueOffset(Layout layout, int scopeOffset, int varIndex) { + if (layout == null) { + return scopeOffset; + } + + int index = layout.getNumFixed() + varIndex; + ReadOnlySpan columns = layout.getColumns(); + checkState(index <= columns.Length); + int offset = scopeOffset + layout.getSize(); + for (int i = layout.getNumFixed(); i < index; i++) { + LayoutColumn col = columns[i]; + if (this.ReadBit(scopeOffset, col.getNullBit().clone())) { + int lengthSizeInBytes; + tangible.OutObject tempOut_lengthSizeInBytes = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong valueSizeInBytes = this.Read7BitEncodedUInt(offset, out int lengthSizeInBytes); + long valueSizeInBytes = this.Read7BitEncodedUInt(offset, tempOut_lengthSizeInBytes); + lengthSizeInBytes = tempOut_lengthSizeInBytes.argValue; + if (col.getType().getIsVarint()) { + offset += lengthSizeInBytes; + } else { + offset += (int)valueSizeInBytes + lengthSizeInBytes; + } + } + } + + return offset; + } + + /** + * Compute the number of bytes necessary to store the unsigned integer using the varuint + * encoding. + * + * @param value The value to be encoded. + * @return The number of bytes needed to store the varuint encoding of . + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal static int Count7BitEncodedUInt(ulong value) + public static int Count7BitEncodedUInt(long value) { + // Count the number of bytes needed to write out an int 7 bits at a time. + int i = 0; + while (value >= 0x80L) { + i++; + //C# TO JAVA CONVERTER WARNING: The right shift operator was replaced by Java's logical right shift + // operator since the left operand was originally of an unsigned type, but you should confirm this + // replacement: + value >>>= 7; + } + + i++; + return i; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void DecrementUInt32(int offset, uint decrement) + public void DecrementUInt32(int offset, int decrement) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MemoryMarshal.Cast(this.buffer.Slice(offset))[0] -= decrement; + MemoryMarshal.Cast(this.buffer.Slice(offset))[0] -= decrement; + } + + /** + * Delete the sparse field at the indicated path. + * + * @param edit The field to delete. + */ + public void DeleteSparse(tangible.RefObject edit) { + // If the field doesn't exist, then nothing to do. + if (!edit.argValue.exists) { + return; + } + + int numBytes = 0; + int _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + int _; + tangible.OutObject tempOut__2 = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, edit.argValue.cellType, edit.argValue.cellTypeArgs.clone(), numBytes, + RowOptions.Delete, tempOut__, tempOut__2, tempOut_shift); + shift = tempOut_shift.argValue; + _ = tempOut__2.argValue; + _ = tempOut__.argValue; + this.length += shift; + } + + public void DeleteVariable(int offset, boolean isVarint) { + int spaceAvailable; + tangible.OutObject tempOut_spaceAvailable = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong existingValueBytes = this.Read7BitEncodedUInt(offset, out int spaceAvailable); + long existingValueBytes = this.Read7BitEncodedUInt(offset, tempOut_spaceAvailable); + spaceAvailable = tempOut_spaceAvailable.argValue; + if (!isVarint) { + spaceAvailable += (int)existingValueBytes; // "size" already in spaceAvailable + } + + this.buffer.Slice(offset + spaceAvailable, this.length - (offset + spaceAvailable)).CopyTo(this.buffer.Slice(offset)); + this.length -= spaceAvailable; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void IncrementUInt32(int offset, uint increment) + public void IncrementUInt32(int offset, int increment) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MemoryMarshal.Cast(this.buffer.Slice(offset))[0] += increment; + MemoryMarshal.Cast(this.buffer.Slice(offset))[0] += increment; + } + + /** + * Initializes a row to the minimal size for the given layout. + * + * @param version The version of the Hybrid Row format to use for encoding this row. + * @param layout The layout that describes the column layout of the row. + * @param resolver The resolver for UDTs. + *

+ * The row is initialized to default row for the given layout. All fixed columns have their + * default values. All variable columns are null. No sparse columns are present. The row is + * valid. + */ + public void InitLayout(HybridRowVersion version, Layout layout, LayoutResolver resolver) { + checkArgument(layout != null); + this.resolver = resolver; + + // Ensure sufficient space for fixed schema fields. + this.Ensure(HybridRowHeader.Size + layout.getSize()); + this.length = HybridRowHeader.Size + layout.getSize(); + + // Clear all presence bits. + this.buffer.Slice(HybridRowHeader.Size, layout.getSize()).Fill(0); + + // Set the header. + this.WriteHeader(0, new HybridRowHeader(version, layout.getSchemaId().clone())); + } + + /** + * Compute the byte offsets from the beginning of the row for a given sparse field insertion + * into a set/map. + * + * @param scope The sparse scope to insert into. + * @param srcEdit The field to move into the set/map. + * @return The prepared edit context. + */ + public RowCursor PrepareSparseMove(tangible.RefObject scope, tangible.RefObject srcEdit) { + checkArgument(scope.argValue.scopeType.IsUniqueScope); + + checkArgument(scope.argValue.index == 0); + RowCursor dstEdit; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + scope.argValue.Clone(out dstEdit); + + dstEdit.metaOffset = scope.argValue.valueOffset; + int srcSize = this.SparseComputeSize(srcEdit); + int srcBytes = srcSize - (srcEdit.argValue.valueOffset - srcEdit.argValue.metaOffset); + while (dstEdit.index < dstEdit.count) { + tangible.RefObject tempRef_dstEdit = + new tangible.RefObject(dstEdit); + this.ReadSparseMetadata(tempRef_dstEdit); + dstEdit = tempRef_dstEdit.argValue; + Contract.Assert(dstEdit.pathOffset == + default) + + int elmSize = -1; // defer calculating the full size until needed. + int cmp; + if (scope.argValue.scopeType instanceof LayoutTypedMap) { + cmp = this.CompareKeyValueFieldValue(srcEdit.argValue.clone(), dstEdit); + } else { + tangible.RefObject tempRef_dstEdit2 = + new tangible.RefObject(dstEdit); + elmSize = this.SparseComputeSize(tempRef_dstEdit2); + dstEdit = tempRef_dstEdit2.argValue; + int elmBytes = elmSize - (dstEdit.valueOffset - dstEdit.metaOffset); + cmp = this.CompareFieldValue(srcEdit.argValue.clone(), srcBytes, dstEdit, elmBytes); + } + + if (cmp <= 0) { + dstEdit.exists = cmp == 0; + return dstEdit; + } + + tangible.RefObject tempRef_dstEdit3 = + new tangible.RefObject(dstEdit); + elmSize = (elmSize == -1) ? this.SparseComputeSize(tempRef_dstEdit3) : elmSize; + dstEdit = tempRef_dstEdit3.argValue; + dstEdit.index++; + dstEdit.metaOffset += elmSize; + } + + dstEdit.exists = false; + dstEdit.cellType = LayoutType.EndScope; + dstEdit.valueOffset = dstEdit.metaOffset; + return dstEdit; + } + + public long Read7BitEncodedInt(int offset, tangible.OutObject lenInBytes) { + return RowBuffer.RotateSignToMsb(this.Read7BitEncodedUInt(offset, lenInBytes)); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal ulong Read7BitEncodedUInt(int offset, out int lenInBytes) + public long Read7BitEncodedUInt(int offset, tangible.OutObject lenInBytes) { + // Read out an unsigned long 7 bits at a time. The high bit of the byte, + // when set, indicates there are more bytes. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong b = this.buffer[offset]; + long b = this.buffer[offset]; + if (b < 0x80L) { + lenInBytes.argValue = 1; + return b; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong retval = b & 0x7F; + long retval = b & 0x7F; + int shift = 7; + do { + checkState(shift < 10 * 7); + b = this.buffer[++offset]; + retval |= (b & 0x7F) << shift; + shift += 7; + } while (b >= 0x80L); + + lenInBytes.argValue = shift / 7; + return retval; + } + + public boolean ReadBit(int offset, LayoutBit bit) { + if (bit.getIsInvalid()) { + return true; + } + + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: return (this.buffer[bit.GetOffset(offset)] & unchecked((byte)(1 << bit.GetBit()))) != 0; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + return (this.buffer[bit.GetOffset(offset)] & (byte)(1 << bit.GetBit())) != 0; + } + + public LocalDateTime ReadDateTime(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + public BigDecimal ReadDecimal(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal ReadOnlySpan ReadFixedBinary(int offset, int len) + public ReadOnlySpan ReadFixedBinary(int offset, int len) { + return this.buffer.Slice(offset, len); + } + + public Utf8Span ReadFixedString(int offset, int len) { + return Utf8Span.UnsafeFromUtf8BytesNoValidation(this.buffer.Slice(offset, len)); + } + + public Float128 ReadFloat128(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + public float ReadFloat32(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + public double ReadFloat64(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + /** + * Reads in the contents of the RowBuffer from an input stream and initializes the row buffer + * with the associated layout and rowVersion. + * + * @return true if the serialization succeeded. false if the input stream was corrupted. + */ + public boolean ReadFrom(InputStream inputStream, int bytesCount, HybridRowVersion rowVersion, + LayoutResolver resolver) { + checkArgument(inputStream != null); + checkState(bytesCount >= HybridRowHeader.Size); + + this.Reset(); + this.resolver = resolver; + this.Ensure(bytesCount); + checkState(this.buffer.Length >= bytesCount); + this.length = bytesCount; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Span active = this.buffer.Slice(0, bytesCount); + Span active = this.buffer.Slice(0, bytesCount); + int bytesRead; + do { + bytesRead = inputStream.Read(active); + active = active.Slice(bytesRead); + } while (bytesRead != 0); + + if (active.Length != 0) { + return false; + } + + return this.InitReadFrom(rowVersion); + } + + /** + * Reads in the contents of the RowBuffer from an existing block of memory and initializes + * the row buffer with the associated layout and rowVersion. + * + * @return true if the serialization succeeded. false if the input stream was corrupted. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public bool ReadFrom(ReadOnlySpan input, HybridRowVersion rowVersion, LayoutResolver + // resolver) + public boolean ReadFrom(ReadOnlySpan input, HybridRowVersion rowVersion, LayoutResolver resolver) { + int bytesCount = input.Length; + checkState(bytesCount >= HybridRowHeader.Size); + + this.Reset(); + this.resolver = resolver; + this.Ensure(bytesCount); + checkState(this.buffer.Length >= bytesCount); + input.CopyTo(this.buffer); + this.length = bytesCount; + return this.InitReadFrom(rowVersion); + } + + public UUID ReadGuid(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + public HybridRowHeader ReadHeader(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + public short ReadInt16(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + public int ReadInt32(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + public long ReadInt64(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + public byte ReadInt8(int offset) { + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: return unchecked((sbyte)this.buffer[offset]); + return (byte)this.buffer[offset]; + } + + public MongoDbObjectId ReadMongoDbObjectId(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + public SchemaId ReadSchemaId(int offset) { + return new SchemaId(this.ReadInt32(offset)); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal ReadOnlySpan ReadSparseBinary(ref RowCursor edit) + public ReadOnlySpan ReadSparseBinary(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Binary); + int sizeLenInBytes; + tangible.OutObject tempOut_sizeLenInBytes = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ReadOnlySpan span = this.ReadBinary(edit.valueOffset, out int sizeLenInBytes); + ReadOnlySpan span = this.ReadBinary(edit.argValue.valueOffset, tempOut_sizeLenInBytes); + sizeLenInBytes = tempOut_sizeLenInBytes.argValue; + edit.argValue.endOffset = edit.argValue.valueOffset + sizeLenInBytes + span.Length; + return span; + } + + public boolean ReadSparseBool(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Boolean); + edit.argValue.endOffset = edit.argValue.valueOffset; + return edit.argValue.cellType == LayoutType.Boolean; + } + + public LocalDateTime ReadSparseDateTime(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.DateTime); + edit.argValue.endOffset = edit.argValue.valueOffset + 8; + return this.ReadDateTime(edit.argValue.valueOffset); + } + + public BigDecimal ReadSparseDecimal(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Decimal); + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'sizeof': + edit.argValue.endOffset = edit.argValue.valueOffset + sizeof(BigDecimal); + return this.ReadDecimal(edit.argValue.valueOffset); + } + + public Float128 ReadSparseFloat128(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Float128); + edit.argValue.endOffset = edit.argValue.valueOffset + Float128.Size; + return this.ReadFloat128(edit.argValue.valueOffset).clone(); + } + + public float ReadSparseFloat32(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Float32); + edit.argValue.endOffset = edit.argValue.valueOffset + (Float.SIZE / Byte.SIZE); + return this.ReadFloat32(edit.argValue.valueOffset); + } + + public double ReadSparseFloat64(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Float64); + edit.argValue.endOffset = edit.argValue.valueOffset + (Double.SIZE / Byte.SIZE); + return this.ReadFloat64(edit.argValue.valueOffset); + } + + public UUID ReadSparseGuid(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Guid); + edit.argValue.endOffset = edit.argValue.valueOffset + 16; + return this.ReadGuid(edit.argValue.valueOffset); + } + + public short ReadSparseInt16(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Int16); + edit.argValue.endOffset = edit.argValue.valueOffset + (Short.SIZE / Byte.SIZE); + return this.ReadInt16(edit.argValue.valueOffset); + } + + public int ReadSparseInt32(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Int32); + edit.argValue.endOffset = edit.argValue.valueOffset + (Integer.SIZE / Byte.SIZE); + return this.ReadInt32(edit.argValue.valueOffset); + } + + public long ReadSparseInt64(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Int64); + edit.argValue.endOffset = edit.argValue.valueOffset + (Long.SIZE / Byte.SIZE); + return this.ReadInt64(edit.argValue.valueOffset); + } + + public byte ReadSparseInt8(tangible.RefObject edit) { + // TODO: Remove calls to ReadSparsePrimitiveTypeCode once moved to V2 read. + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Int8); + edit.argValue.endOffset = edit.argValue.valueOffset + (Byte.SIZE / Byte.SIZE); + return this.ReadInt8(edit.argValue.valueOffset); + } + + public MongoDbObjectId ReadSparseMongoDbObjectId(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, MongoDbObjectId); + edit.argValue.endOffset = edit.argValue.valueOffset + MongoDbObjectId.Size; + return this.ReadMongoDbObjectId(edit.argValue.valueOffset).clone(); + } + + public NullValue ReadSparseNull(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Null); + edit.argValue.endOffset = edit.argValue.valueOffset; + return NullValue.Default; + } + + public Utf8Span ReadSparsePath(tangible.RefObject edit) { + Utf8String path; + tangible.OutObject tempOut_path = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: if (edit.layout.Tokenizer.TryFindString((ulong)edit.pathToken, out Utf8String path)) + if (edit.argValue.layout.getTokenizer().TryFindString(edit.argValue.longValue().pathToken, tempOut_path)) { + path = tempOut_path.argValue; + return path.Span; + } else { + path = tempOut_path.argValue; + } + + int numBytes = edit.argValue.pathToken - edit.argValue.layout.getTokenizer().getCount(); + return Utf8Span.UnsafeFromUtf8BytesNoValidation(this.buffer.Slice(edit.argValue.pathOffset, numBytes)); + } + + public int ReadSparsePathLen(Layout layout, int offset, tangible.OutObject pathLenInBytes, + tangible.OutObject pathOffset) { + int sizeLenInBytes; + tangible.OutObject tempOut_sizeLenInBytes = new tangible.OutObject(); + int token = (int)this.Read7BitEncodedUInt(offset, tempOut_sizeLenInBytes); + sizeLenInBytes = tempOut_sizeLenInBytes.argValue; + if (token < layout.getTokenizer().getCount()) { + pathLenInBytes.argValue = sizeLenInBytes; + pathOffset.argValue = offset; + return token; + } + + int numBytes = token - layout.getTokenizer().getCount(); + pathLenInBytes.argValue = numBytes + sizeLenInBytes; + pathOffset.argValue = offset + sizeLenInBytes; + return token; + } + + public Utf8Span ReadSparseString(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.Utf8); + int sizeLenInBytes; + tangible.OutObject tempOut_sizeLenInBytes = new tangible.OutObject(); + Utf8Span span = this.ReadString(edit.argValue.valueOffset, tempOut_sizeLenInBytes); + sizeLenInBytes = tempOut_sizeLenInBytes.argValue; + edit.argValue.endOffset = edit.argValue.valueOffset + sizeLenInBytes + span.Length; + return span; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] internal LayoutType ReadSparseTypeCode(int + // offset) + public LayoutType ReadSparseTypeCode(int offset) { + return LayoutType.FromCode(LayoutCode.forValue(this.ReadUInt8(offset))); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal ushort ReadSparseUInt16(ref RowCursor edit) + public short ReadSparseUInt16(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.UInt16); + edit.argValue.endOffset = edit.argValue.valueOffset + (Short.SIZE / Byte.SIZE); + return this.ReadUInt16(edit.argValue.valueOffset); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal uint ReadSparseUInt32(ref RowCursor edit) + public int ReadSparseUInt32(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.UInt32); + edit.argValue.endOffset = edit.argValue.valueOffset + (Integer.SIZE / Byte.SIZE); + return this.ReadUInt32(edit.argValue.valueOffset); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal ulong ReadSparseUInt64(ref RowCursor edit) + public long ReadSparseUInt64(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.UInt64); + edit.argValue.endOffset = edit.argValue.valueOffset + (Long.SIZE / Byte.SIZE); + return this.ReadUInt64(edit.argValue.valueOffset); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal byte ReadSparseUInt8(ref RowCursor edit) + public byte ReadSparseUInt8(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.UInt8); + edit.argValue.endOffset = edit.argValue.valueOffset + 1; + return this.ReadUInt8(edit.argValue.valueOffset); + } + + public UnixDateTime ReadSparseUnixDateTime(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.UnixDateTime); + edit.argValue.endOffset = edit.argValue.valueOffset + 8; + return this.ReadUnixDateTime(edit.argValue.valueOffset).clone(); + } + + public long ReadSparseVarInt(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.VarInt); + int sizeLenInBytes; + tangible.OutObject tempOut_sizeLenInBytes = new tangible.OutObject(); + long value = this.Read7BitEncodedInt(edit.argValue.valueOffset, tempOut_sizeLenInBytes); + sizeLenInBytes = tempOut_sizeLenInBytes.argValue; + edit.argValue.endOffset = edit.argValue.valueOffset + sizeLenInBytes; + return value; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal ulong ReadSparseVarUInt(ref RowCursor edit) + public long ReadSparseVarUInt(tangible.RefObject edit) { + this.ReadSparsePrimitiveTypeCode(edit, LayoutType.VarUInt); + int sizeLenInBytes; + tangible.OutObject tempOut_sizeLenInBytes = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong value = this.Read7BitEncodedUInt(edit.valueOffset, out int sizeLenInBytes); + long value = this.Read7BitEncodedUInt(edit.argValue.valueOffset, tempOut_sizeLenInBytes); + sizeLenInBytes = tempOut_sizeLenInBytes.argValue; + edit.argValue.endOffset = edit.argValue.valueOffset + sizeLenInBytes; + return value; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal ushort ReadUInt16(int offset) + public short ReadUInt16(int offset) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return MemoryMarshal.Read(this.buffer.Slice(offset)); + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal uint ReadUInt32(int offset) + public int ReadUInt32(int offset) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return MemoryMarshal.Read(this.buffer.Slice(offset)); + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal ulong ReadUInt64(int offset) + public long ReadUInt64(int offset) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return MemoryMarshal.Read(this.buffer.Slice(offset)); + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] internal byte ReadUInt8(int offset) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] internal byte ReadUInt8(int offset) + public byte ReadUInt8(int offset) { + return this.buffer[offset]; + } + + public UnixDateTime ReadUnixDateTime(int offset) { + return MemoryMarshal.Read(this.buffer.Slice(offset)); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal ReadOnlySpan ReadVariableBinary(int offset) + public ReadOnlySpan ReadVariableBinary(int offset) { + int _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.ReadBinary(offset, out int _); + ReadOnlySpan tempVar = this.ReadBinary(offset, tempOut__); + _ = tempOut__.argValue; + return tempVar; + } + + public long ReadVariableInt(int offset) { + int _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + long tempVar = this.Read7BitEncodedInt(offset, tempOut__); + _ = tempOut__.argValue; + return tempVar; + } + + public Utf8Span ReadVariableString(int offset) { + int _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + Utf8Span tempVar = this.ReadString(offset, tempOut__); + _ = tempOut__.argValue; + return tempVar; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal ulong ReadVariableUInt(int offset) + public long ReadVariableUInt(int offset) { + int _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.Read7BitEncodedUInt(offset, out int _); + long tempVar = this.Read7BitEncodedUInt(offset, tempOut__); + _ = tempOut__.argValue; + return tempVar; + } + + /** + * Clears all content from the row. The row is empty after this method. + */ + public void Reset() { + this.length = 0; + this.resolver = null; + } + + /** + * Rotates the sign bit of a two's complement value to the least significant bit. + * + * @param value A signed value. + * @return An unsigned value encoding the same value but with the sign bit in the LSB. + *

+ * Moves the signed bit of a two's complement value to the least significant bit (LSB) by: + * + * + * If negative, take the two's complement. + * + * Left shift the value by 1 bit. + * + * If negative, set the LSB to 1. + * + * + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("StyleCop.CSharp.DocumentationRules", + // "SA1629:DocumentationTextMustEndWithAPeriod", Justification = "Colon.")] internal static ulong RotateSignToLsb + // (long value) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [SuppressMessage("StyleCop.CSharp.DocumentationRules", + // "SA1629:DocumentationTextMustEndWithAPeriod", Justification = "Colon.")] internal static ulong RotateSignToLsb + // (long value) + public static long RotateSignToLsb(long value) { + // Rotate sign to LSB + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + boolean isNegative = value < 0; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong uvalue = (ulong)value; + long uvalue = value; + uvalue = isNegative ? ((~uvalue + 1) << 1) + 1 : uvalue << 1; + return uvalue; + } + } + + /** + * Undoes the rotation introduced by . + * + * @param uvalue An unsigned value with the sign bit in the LSB. + * @return A signed two's complement value encoding the same value. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal static long RotateSignToMsb(ulong uvalue) + public static long RotateSignToMsb(long uvalue) { + // Rotate sign to MSB + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + boolean isNegative = uvalue % 2 != 0; + //C# TO JAVA CONVERTER WARNING: The right shift operator was replaced by Java's logical right shift + // operator since the left operand was originally of an unsigned type, but you should confirm this + // replacement: + long value = isNegative ? (~(uvalue >>> 1) + 1) | 0x8000000000000000 : uvalue >>> 1; + return value; + } + } + + public void SetBit(int offset, LayoutBit bit) { + if (bit.getIsInvalid()) { + return; + } + + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.buffer[bit.GetOffset(offset)] |= unchecked((byte)(1 << bit.GetBit())); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + this.buffer[bit.GetOffset(offset)] |= (byte)(1 << bit.GetBit()); + } + + /** + * Move a sparse iterator to the next field within the same sparse scope. + * + * @param edit The iterator to advance. + * + * + * On success, the path of the field at the given offset, otherwise + * undefined. + * + * + * If found, the offset to the metadata of the field, otherwise a + * location to insert the field. + * + * + * If found, the layout code of the matching field found, otherwise + * undefined. + * + * + * If found, the offset to the value of the field, otherwise + * undefined. + * . + * @return True if there is another field, false if there are no more. + */ + public boolean SparseIteratorMoveNext(tangible.RefObject edit) { + if (edit.argValue.cellType != null) { + // Move to the next element of an indexed scope. + if (edit.argValue.scopeType.IsIndexedScope) { + edit.argValue.index++; + } + + // Skip forward to the end of the current value. + if (edit.argValue.endOffset != 0) { + edit.argValue.metaOffset = edit.argValue.endOffset; + edit.argValue.endOffset = 0; + } else { + edit.argValue.metaOffset += this.SparseComputeSize(edit); + } + } + + // Check if reached end of buffer. + if (edit.argValue.metaOffset < this.length) { + // Check if reached end of sized scope. + if (!edit.argValue.scopeType.IsSizedScope || (edit.argValue.index != edit.argValue.count)) { + // Read the metadata. + this.ReadSparseMetadata(edit); + + // Check if reached end of sparse scope. + if (!(edit.argValue.cellType instanceof LayoutEndScope)) { + edit.argValue.exists = true; + return true; + } + } + } + + edit.argValue.cellType = LayoutType.EndScope; + edit.argValue.exists = false; + edit.argValue.valueOffset = edit.argValue.metaOffset; + return false; + } + + /** + * Produce a new scope from the current iterator position. + * + * @param edit An initialized iterator pointing at a scope. + * @param immutable True if the new scope should be marked immutable (read-only). + * @return A new scope beginning at the current iterator position. + */ + public RowCursor SparseIteratorReadScope(tangible.RefObject edit, boolean immutable) { + LayoutScope scopeType = edit.argValue.cellType instanceof LayoutScope ? (LayoutScope)edit.argValue.cellType : + null; + switch (scopeType) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutObject _: + case LayoutObject + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutArray _: + case LayoutArray _: + { + RowCursor tempVar = new RowCursor(); + tempVar.scopeType = scopeType; + tempVar.scopeTypeArgs = edit.argValue.cellTypeArgs.clone(); + tempVar.start = edit.argValue.valueOffset; + tempVar.valueOffset = edit.argValue.valueOffset; + tempVar.metaOffset = edit.argValue.valueOffset; + tempVar.layout = edit.argValue.layout; + tempVar.immutable = immutable; + return tempVar.clone(); + + break; + } + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedArray _: + case LayoutTypedArray + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedSet _: + case LayoutTypedSet _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedMap _: + case LayoutTypedMap _: + { + int valueOffset = edit.argValue.valueOffset + (Integer.SIZE / Byte.SIZE); // Point after the Size + RowCursor tempVar2 = new RowCursor(); + tempVar2.scopeType = scopeType; + tempVar2.scopeTypeArgs = edit.argValue.cellTypeArgs.clone(); + tempVar2.start = edit.argValue.valueOffset; + tempVar2.valueOffset = valueOffset; + tempVar2.metaOffset = valueOffset; + tempVar2.layout = edit.argValue.layout; + tempVar2.immutable = immutable; + tempVar2.count = this.ReadUInt32(edit.argValue.valueOffset); + return tempVar2.clone(); + + break; + } + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedTuple _: + case LayoutTypedTuple + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTuple _: + case LayoutTuple _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTagged _: + case LayoutTagged _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTagged2 _: + case LayoutTagged2 _: + { + RowCursor tempVar3 = new RowCursor(); + tempVar3.scopeType = scopeType; + tempVar3.scopeTypeArgs = edit.argValue.cellTypeArgs.clone(); + tempVar3.start = edit.argValue.valueOffset; + tempVar3.valueOffset = edit.argValue.valueOffset; + tempVar3.metaOffset = edit.argValue.valueOffset; + tempVar3.layout = edit.argValue.layout; + tempVar3.immutable = immutable; + tempVar3.count = edit.argValue.cellTypeArgs.getCount(); + return tempVar3.clone(); + + break; + } + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutNullable _: + case LayoutNullable + _: + { + boolean hasValue = this.ReadInt8(edit.argValue.valueOffset) != 0; + if (hasValue) { + // Start at the T so it can be read. + int valueOffset = edit.argValue.valueOffset + 1; + RowCursor tempVar4 = new RowCursor(); + tempVar4.scopeType = scopeType; + tempVar4.scopeTypeArgs = edit.argValue.cellTypeArgs.clone(); + tempVar4.start = edit.argValue.valueOffset; + tempVar4.valueOffset = valueOffset; + tempVar4.metaOffset = valueOffset; + tempVar4.layout = edit.argValue.layout; + tempVar4.immutable = immutable; + tempVar4.count = 2; + tempVar4.index = 1; + return tempVar4.clone(); + } else { + // Start at the end of the scope, instead of at the T, so the T will be skipped. + TypeArgument typeArg = edit.argValue.cellTypeArgs.get(0).clone(); + int valueOffset = edit.argValue.valueOffset + 1 + this.CountDefaultValue(typeArg.getType(), + typeArg.getTypeArgs().clone()); + RowCursor tempVar5 = new RowCursor(); + tempVar5.scopeType = scopeType; + tempVar5.scopeTypeArgs = edit.argValue.cellTypeArgs.clone(); + tempVar5.start = edit.argValue.valueOffset; + tempVar5.valueOffset = valueOffset; + tempVar5.metaOffset = valueOffset; + tempVar5.layout = edit.argValue.layout; + tempVar5.immutable = immutable; + tempVar5.count = 2; + tempVar5.index = 2; + return tempVar5.clone(); + } + + break; + } + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUDT _: + case LayoutUDT + _: + { + Layout udt = this.resolver.Resolve(edit.argValue.cellTypeArgs.getSchemaId().clone()); + int valueOffset = this.ComputeVariableValueOffset(udt, edit.argValue.valueOffset, + udt.getNumVariable()); + RowCursor tempVar6 = new RowCursor(); + tempVar6.scopeType = scopeType; + tempVar6.scopeTypeArgs = edit.argValue.cellTypeArgs.clone(); + tempVar6.start = edit.argValue.valueOffset; + tempVar6.valueOffset = valueOffset; + tempVar6.metaOffset = valueOffset; + tempVar6.layout = udt; + tempVar6.immutable = immutable; + return tempVar6.clone(); + + break; + } + + default: + throw new IllegalStateException("Not a scope type."); + return null; + } + } + + /** + * The length of row in bytes. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public byte[] ToArray() + public byte[] ToArray() { + return this.buffer.Slice(0, this.length).ToArray(); + } + + public void TypedCollectionMoveField(tangible.RefObject dstEdit, tangible.RefObject srcEdit + , RowOptions options) { + int encodedSize = this.SparseComputeSize(srcEdit); + int numBytes = encodedSize - (srcEdit.argValue.valueOffset - srcEdit.argValue.metaOffset); + + // Insert the field metadata into its new location. + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shiftInsert; + tangible.OutObject tempOut_shiftInsert = new tangible.OutObject(); + this.EnsureSparse(dstEdit, srcEdit.argValue.cellType, srcEdit.argValue.cellTypeArgs.clone(), numBytes, + options, tempOut_metaBytes, tempOut_spaceNeeded, tempOut_shiftInsert); + shiftInsert = tempOut_shiftInsert.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + + this.WriteSparseMetadata(dstEdit, srcEdit.argValue.cellType, srcEdit.argValue.cellTypeArgs.clone(), metaBytes); + checkState(spaceNeeded == metaBytes + numBytes); + if (srcEdit.argValue.metaOffset >= dstEdit.argValue.metaOffset) { + srcEdit.argValue.metaOffset += shiftInsert; + srcEdit.argValue.valueOffset += shiftInsert; + } + + // Copy the value bits from the old location. + this.buffer.Slice(srcEdit.argValue.valueOffset, numBytes).CopyTo(this.buffer.Slice(dstEdit.argValue.valueOffset)); + this.length += shiftInsert; + + // Delete the old location. + tangible.OutObject tempOut_metaBytes2 = new tangible.OutObject(); + tangible.OutObject tempOut_spaceNeeded2 = new tangible.OutObject(); + int shiftDelete; + tangible.OutObject tempOut_shiftDelete = new tangible.OutObject(); + this.EnsureSparse(srcEdit, srcEdit.argValue.cellType, srcEdit.argValue.cellTypeArgs.clone(), numBytes, + RowOptions.Delete, tempOut_metaBytes2, tempOut_spaceNeeded2, tempOut_shiftDelete); + shiftDelete = tempOut_shiftDelete.argValue; + spaceNeeded = tempOut_spaceNeeded2.argValue; + metaBytes = tempOut_metaBytes2.argValue; + + checkState(shiftDelete < 0); + this.length += shiftDelete; + } + + /** + * Rebuild the unique index for a set/map scope. + * + * @param scope The sparse scope to rebuild an index for. + * @return Success if the index could be built, an error otherwise. + *

+ * The MUST be a set or map scope. + *

+ * The scope may have been built (e.g. via RowWriter) with relaxed uniqueness constraint checking. + * This operation rebuilds an index to support verification of uniqueness constraints during + * subsequent partial updates. If the appropriate uniqueness constraints cannot be established (i.e. + * a duplicate exists), this operation fails. Before continuing, the resulting scope should either: + * + * + * + * Be repaired (e.g. by deleting duplicates) and the index rebuild operation should be + * run again. + * + * + * Be deleted. The entire scope should be removed including its items. + * + * Failure to perform one of these actions will leave the row is potentially in a corrupted + * state where partial updates may subsequent fail. + *

+ *

+ * The target may or may not have already been indexed. This + * operation is idempotent. + *

+ */ + public Result TypedCollectionUniqueIndexRebuild(tangible.RefObject scope) { + checkArgument(scope.argValue.scopeType.IsUniqueScope); + checkArgument(scope.argValue.index == 0); + RowCursor dstEdit; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be + // converted using the 'OutObject' helper class unless the method is within the code being modified: + scope.argValue.Clone(out dstEdit); + if (dstEdit.count <= 1) { + return Result.Success; + } + + // Compute Index Elements. + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'stackalloc' in Java: + UniqueIndexItem item; + Span uniqueIndex = dstEdit.count < 100 ? stackalloc UniqueIndexItem[dstEdit.count] : + new UniqueIndexItem[dstEdit.count]; + dstEdit.metaOffset = scope.argValue.valueOffset; + for (; dstEdit.index < dstEdit.count; dstEdit.index++) { + tangible.RefObject tempRef_dstEdit = + new tangible.RefObject(dstEdit); + this.ReadSparseMetadata(tempRef_dstEdit); + dstEdit = tempRef_dstEdit.argValue; + Contract.Assert(dstEdit.pathOffset == + default) + tangible.RefObject tempRef_dstEdit2 = + new tangible.RefObject(dstEdit); + int elmSize = this.SparseComputeSize(tempRef_dstEdit2); + dstEdit = tempRef_dstEdit2.argValue; + + UniqueIndexItem tempVar = new UniqueIndexItem(); + tempVar.Code = dstEdit.cellType.LayoutCode; + tempVar.MetaOffset = dstEdit.metaOffset; + tempVar.ValueOffset = dstEdit.valueOffset; + tempVar.Size = elmSize; + uniqueIndex[dstEdit.index] = tempVar.clone(); + + dstEdit.metaOffset += elmSize; + } + + // Create scratch space equal to the sum of the sizes of the scope's values. + // Implementation Note: theoretically this scratch space could be eliminated by + // performing the item move operations directly during the Insertion Sort, however, + // doing so might result in moving the same item multiple times. Under the assumption + // that items are relatively large, using scratch space requires each item to be moved + // AT MOST once. Given that row buffer memory is likely reused, scratch space is + // relatively memory efficient. + int shift = dstEdit.metaOffset - scope.argValue.valueOffset; + + // Sort and check for duplicates. + // TODO: C# TO JAVA CONVERTER: C# 'unsafe' code is not converted by C# to Java Converter: + // unsafe + // { + // Span p = new Span(Unsafe.AsPointer(ref uniqueIndex + // .GetPinnableReference()), uniqueIndex.Length); + // if (!this.InsertionSort(ref scope, ref dstEdit, p)) + // { + // return Result.Exists; + // } + // } + + // Move elements. + int metaOffset = scope.argValue.valueOffset; + this.Ensure(this.length + shift); + this.buffer.Slice(metaOffset, this.length - metaOffset).CopyTo(this.buffer.Slice(metaOffset + shift)); + for (UniqueIndexItem x : uniqueIndex) { + this.buffer.Slice(x.MetaOffset + shift, x.Size).CopyTo(this.buffer.Slice(metaOffset)); + metaOffset += x.Size; + } + + // Delete the scratch space (if necessary - if it doesn't just fall off the end of the row). + if (metaOffset != this.length) { + this.buffer.Slice(metaOffset + shift, this.length - metaOffset).CopyTo(this.buffer.Slice(metaOffset)); + } + + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + // Fill deleted bits (in debug builds) to detect overflow/alignment errors. + this.buffer.Slice(this.length, shift).Fill(0xFF); + //#endif + + return Result.Success; + } + + public void UnsetBit(int offset, LayoutBit bit) { + checkState(azure.data.cosmos.serialization.hybridrow.layouts.LayoutBit.opNotEquals(bit.clone(), LayoutBit.Invalid)); + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.buffer[bit.GetOffset(offset)] &= unchecked((byte)~(1 << bit.GetBit())); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + this.buffer[bit.GetOffset(offset)] &= (byte)~(1 << bit.GetBit()); + } + + public int Write7BitEncodedInt(int offset, long value) { + return this.Write7BitEncodedUInt(offset, RowBuffer.RotateSignToLsb(value)); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal int Write7BitEncodedUInt(int offset, ulong value) + public int Write7BitEncodedUInt(int offset, long value) { + // Write out an unsigned long 7 bits at a time. The high bit of the byte, + // when set, indicates there are more bytes. + int i = 0; + while (value >= 0x80L) { + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.WriteUInt8(offset + i++, unchecked((byte)(value | 0x80))); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + this.WriteUInt8(offset + i++, (byte)(value | 0x80)); + //C# TO JAVA CONVERTER WARNING: The right shift operator was replaced by Java's logical right shift + // operator since the left operand was originally of an unsigned type, but you should confirm this + // replacement: + value >>>= 7; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.WriteUInt8(offset + i++, (byte)value); + this.WriteUInt8(offset + i++, (byte)value); + return i; + } + + public void WriteDateTime(int offset, LocalDateTime value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + public void WriteDecimal(int offset, BigDecimal value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteFixedBinary(int offset, ReadOnlySpan value, int len) + public void WriteFixedBinary(int offset, ReadOnlySpan value, int len) { + value.CopyTo(this.buffer.Slice(offset, len)); + if (value.Length < len) { + this.buffer.Slice(offset + value.Length, len - value.Length).Fill(0); + } + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteFixedBinary(int offset, ReadOnlySequence value, int len) + public void WriteFixedBinary(int offset, ReadOnlySequence value, int len) { + value.CopyTo(this.buffer.Slice(offset, len)); + if (value.Length < len) { + this.buffer.Slice(offset + (int)value.Length, len - (int)value.Length).Fill(0); + } + } + + public void WriteFixedString(int offset, Utf8Span value) { + value.Span.CopyTo(this.buffer.Slice(offset)); + } + + public void WriteFloat128(int offset, Float128 value) { + tangible.RefObject tempRef_value = + new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + public void WriteFloat32(int offset, float value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + public void WriteFloat64(int offset, double value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + public void WriteGuid(int offset, UUID value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + public void WriteHeader(int offset, HybridRowHeader value) { + tangible.RefObject tempRef_value = + new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + public void WriteInt16(int offset, short value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + public void WriteInt32(int offset, int value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + public void WriteInt64(int offset, long value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + public void WriteInt8(int offset, byte value) { + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.buffer[offset] = unchecked((byte)value); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + this.buffer[offset] = value; + } + + public void WriteMongoDbObjectId(int offset, MongoDbObjectId value) { + tangible.RefObject tempRef_value = + new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + public void WriteNullable(tangible.RefObject edit, LayoutScope scopeType, TypeArgumentList typeArgs, + UpdateOptions options, boolean hasValue, tangible.OutObject newScope) { + int numBytes = this.CountDefaultValue(scopeType, typeArgs.clone()); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, scopeType, typeArgs.clone(), numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, scopeType, typeArgs.clone(), metaBytes); + int numWritten = this.WriteDefaultValue(edit.argValue.valueOffset, scopeType, typeArgs.clone()); + checkState(numBytes == numWritten); + checkState(spaceNeeded == metaBytes + numBytes); + if (hasValue) { + this.WriteInt8(edit.argValue.valueOffset, (byte)1); + } + + int valueOffset = edit.argValue.valueOffset + 1; + newScope.argValue = new RowCursor(); + newScope.argValue.scopeType = scopeType; + newScope.argValue.scopeTypeArgs = typeArgs.clone(); + newScope.argValue.start = edit.argValue.valueOffset; + newScope.argValue.valueOffset = valueOffset; + newScope.argValue.metaOffset = valueOffset; + newScope.argValue.layout = edit.argValue.layout; + newScope.argValue.count = 2; + newScope.argValue.index = 1; + + this.length += shift; + tangible.RefObject tempRef_this = + new tangible.RefObject(this); + azure.data.cosmos.serialization.hybridrow.RowCursorExtensions.MoveNext(newScope.argValue.clone(), tempRef_this); + this = tempRef_this.argValue; + } + + public void WriteSchemaId(int offset, SchemaId value) { + this.WriteInt32(offset, value.getId()); + } + + public void WriteSparseArray(tangible.RefObject edit, LayoutScope scopeType, UpdateOptions options, + tangible.OutObject newScope) { + int numBytes = (LayoutCode.SIZE / Byte.SIZE); // end scope type code. + TypeArgumentList typeArgs = TypeArgumentList.Empty; + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, scopeType, typeArgs.clone(), numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, scopeType, typeArgs.clone(), metaBytes); + this.WriteSparseTypeCode(edit.argValue.valueOffset, LayoutCode.EndScope); + checkState(spaceNeeded == metaBytes + numBytes); + newScope.argValue = new RowCursor(); + newScope.argValue.scopeType = scopeType; + newScope.argValue.scopeTypeArgs = typeArgs.clone(); + newScope.argValue.start = edit.argValue.valueOffset; + newScope.argValue.valueOffset = edit.argValue.valueOffset; + newScope.argValue.metaOffset = edit.argValue.valueOffset; + newScope.argValue.layout = edit.argValue.layout; + + this.length += shift; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteSparseBinary(ref RowCursor edit, ReadOnlySpan value, UpdateOptions + // options) + public void WriteSparseBinary(tangible.RefObject edit, ReadOnlySpan value, UpdateOptions options) { + int len = value.Length; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: int numBytes = len + RowBuffer.Count7BitEncodedUInt((ulong)len); + int numBytes = len + RowBuffer.Count7BitEncodedUInt(len); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Binary, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Binary, TypeArgumentList.Empty, metaBytes); + int sizeLenInBytes = this.WriteBinary(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + len + sizeLenInBytes); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteSparseBinary(ref RowCursor edit, ReadOnlySequence value, UpdateOptions + // options) + public void WriteSparseBinary(tangible.RefObject edit, ReadOnlySequence value, + UpdateOptions options) { + int len = (int)value.Length; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: int numBytes = len + RowBuffer.Count7BitEncodedUInt((ulong)len); + int numBytes = len + RowBuffer.Count7BitEncodedUInt(len); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Binary, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Binary, TypeArgumentList.Empty, metaBytes); + int sizeLenInBytes = this.WriteBinary(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + len + sizeLenInBytes); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseBool(tangible.RefObject edit, boolean value, UpdateOptions options) { + int numBytes = 0; + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, value ? LayoutType.Boolean : LayoutType.BooleanFalse, TypeArgumentList.Empty, + numBytes, options, tempOut_metaBytes, tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, value ? LayoutType.Boolean : LayoutType.BooleanFalse, TypeArgumentList.Empty, + metaBytes); + checkState(spaceNeeded == metaBytes); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseDateTime(tangible.RefObject edit, LocalDateTime value, UpdateOptions options) { + int numBytes = 8; + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.DateTime, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.DateTime, TypeArgumentList.Empty, metaBytes); + this.WriteDateTime(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + 8); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseDecimal(tangible.RefObject edit, BigDecimal value, UpdateOptions options) { + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'sizeof': + int numBytes = sizeof(BigDecimal); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Decimal, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Decimal, TypeArgumentList.Empty, metaBytes); + this.WriteDecimal(edit.argValue.valueOffset, value); + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'sizeof': + checkState(spaceNeeded == metaBytes + sizeof(BigDecimal)); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseFloat128(tangible.RefObject edit, Float128 value, UpdateOptions options) { + int numBytes = Float128.Size; + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Float128, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Float128, TypeArgumentList.Empty, metaBytes); + this.WriteFloat128(edit.argValue.valueOffset, value.clone()); + checkState(spaceNeeded == metaBytes + Float128.Size); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseFloat32(tangible.RefObject edit, float value, UpdateOptions options) { + int numBytes = (Float.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Float32, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Float32, TypeArgumentList.Empty, metaBytes); + this.WriteFloat32(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + (Float.SIZE / Byte.SIZE)); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseFloat64(tangible.RefObject edit, double value, UpdateOptions options) { + int numBytes = (Double.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Float64, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Float64, TypeArgumentList.Empty, metaBytes); + this.WriteFloat64(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + (Double.SIZE / Byte.SIZE)); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseGuid(tangible.RefObject edit, UUID value, UpdateOptions options) { + int numBytes = 16; + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Guid, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Guid, TypeArgumentList.Empty, metaBytes); + this.WriteGuid(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + 16); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseInt16(tangible.RefObject edit, short value, UpdateOptions options) { + int numBytes = (Short.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Int16, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Int16, TypeArgumentList.Empty, metaBytes); + this.WriteInt16(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + (Short.SIZE / Byte.SIZE)); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseInt32(tangible.RefObject edit, int value, UpdateOptions options) { + int numBytes = (Integer.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Int32, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Int32, TypeArgumentList.Empty, metaBytes); + this.WriteInt32(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + (Integer.SIZE / Byte.SIZE)); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseInt64(tangible.RefObject edit, long value, UpdateOptions options) { + int numBytes = (Long.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Int64, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Int64, TypeArgumentList.Empty, metaBytes); + this.WriteInt64(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + (Long.SIZE / Byte.SIZE)); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseInt8(tangible.RefObject edit, byte value, UpdateOptions options) { + int numBytes = (Byte.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Int8, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + + this.WriteSparseMetadata(edit, LayoutType.Int8, TypeArgumentList.Empty, metaBytes); + this.WriteInt8(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + (Byte.SIZE / Byte.SIZE)); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseMongoDbObjectId(tangible.RefObject edit, MongoDbObjectId value, + UpdateOptions options) { + int numBytes = MongoDbObjectId.Size; + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, MongoDbObjectId, TypeArgumentList.Empty, numBytes, options, + tempOut_metaBytes, tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + + this.WriteSparseMetadata(edit, MongoDbObjectId, TypeArgumentList.Empty, metaBytes); + this.WriteMongoDbObjectId(edit.argValue.valueOffset, value.clone()); + checkState(spaceNeeded == metaBytes + MongoDbObjectId.Size); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseNull(tangible.RefObject edit, NullValue value, UpdateOptions options) { + int numBytes = 0; + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Null, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Null, TypeArgumentList.Empty, metaBytes); + checkState(spaceNeeded == metaBytes); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseObject(tangible.RefObject edit, LayoutScope scopeType, UpdateOptions options, + tangible.OutObject newScope) { + int numBytes = (LayoutCode.SIZE / Byte.SIZE); // end scope type code. + TypeArgumentList typeArgs = TypeArgumentList.Empty; + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, scopeType, typeArgs.clone(), numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, scopeType, TypeArgumentList.Empty, metaBytes); + this.WriteSparseTypeCode(edit.argValue.valueOffset, LayoutCode.EndScope); + checkState(spaceNeeded == metaBytes + numBytes); + newScope.argValue = new RowCursor(); + newScope.argValue.scopeType = scopeType; + newScope.argValue.scopeTypeArgs = TypeArgumentList.Empty; + newScope.argValue.start = edit.argValue.valueOffset; + newScope.argValue.valueOffset = edit.argValue.valueOffset; + newScope.argValue.metaOffset = edit.argValue.valueOffset; + newScope.argValue.layout = edit.argValue.layout; + + this.length += shift; + } + + public void WriteSparseString(tangible.RefObject edit, Utf8Span value, UpdateOptions options) { + int len = value.Length; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: int numBytes = len + RowBuffer.Count7BitEncodedUInt((ulong)len); + int numBytes = len + RowBuffer.Count7BitEncodedUInt(len); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.Utf8, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.Utf8, TypeArgumentList.Empty, metaBytes); + int sizeLenInBytes = this.WriteString(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + len + sizeLenInBytes); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseTuple(tangible.RefObject edit, LayoutScope scopeType, TypeArgumentList typeArgs + , UpdateOptions options, tangible.OutObject newScope) { + int numBytes = (LayoutCode.SIZE / Byte.SIZE) * (1 + typeArgs.getCount()); // nulls for each element. + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, scopeType, typeArgs.clone(), numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, scopeType, typeArgs.clone(), metaBytes); + int valueOffset = edit.argValue.valueOffset; + for (int i = 0; i < typeArgs.getCount(); i++) { + this.WriteSparseTypeCode(valueOffset, LayoutCode.Null); + valueOffset += (LayoutCode.SIZE / Byte.SIZE); + } + + this.WriteSparseTypeCode(valueOffset, LayoutCode.EndScope); + checkState(spaceNeeded == metaBytes + numBytes); + newScope.argValue = new RowCursor(); + newScope.argValue.scopeType = scopeType; + newScope.argValue.scopeTypeArgs = typeArgs.clone(); + newScope.argValue.start = edit.argValue.valueOffset; + newScope.argValue.valueOffset = edit.argValue.valueOffset; + newScope.argValue.metaOffset = edit.argValue.valueOffset; + newScope.argValue.layout = edit.argValue.layout; + newScope.argValue.count = typeArgs.getCount(); + + this.length += shift; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void WriteSparseTypeCode(int offset, + // LayoutCode code) + public void WriteSparseTypeCode(int offset, LayoutCode code) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.WriteUInt8(offset, (byte)code); + this.WriteUInt8(offset, (byte)code.getValue()); + } + + public void WriteSparseUDT(tangible.RefObject edit, LayoutScope scopeType, Layout udt, + UpdateOptions options, tangible.OutObject newScope) { + TypeArgumentList typeArgs = new TypeArgumentList(udt.getSchemaId().clone()); + int numBytes = udt.getSize() + (LayoutCode.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, scopeType, typeArgs.clone(), numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, scopeType, typeArgs.clone(), metaBytes); + + // Clear all presence bits. + this.buffer.Slice(edit.argValue.valueOffset, udt.getSize()).Fill(0); + + // Write scope terminator. + int valueOffset = edit.argValue.valueOffset + udt.getSize(); + this.WriteSparseTypeCode(valueOffset, LayoutCode.EndScope); + checkState(spaceNeeded == metaBytes + numBytes); + newScope.argValue = new RowCursor(); + newScope.argValue.scopeType = scopeType; + newScope.argValue.scopeTypeArgs = typeArgs.clone(); + newScope.argValue.start = edit.argValue.valueOffset; + newScope.argValue.valueOffset = valueOffset; + newScope.argValue.metaOffset = valueOffset; + newScope.argValue.layout = udt; + + this.length += shift; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteSparseUInt16(ref RowCursor edit, ushort value, UpdateOptions options) + public void WriteSparseUInt16(tangible.RefObject edit, short value, UpdateOptions options) { + int numBytes = (Short.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.UInt16, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.UInt16, TypeArgumentList.Empty, metaBytes); + this.WriteUInt16(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + (Short.SIZE / Byte.SIZE)); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteSparseUInt32(ref RowCursor edit, uint value, UpdateOptions options) + public void WriteSparseUInt32(tangible.RefObject edit, int value, UpdateOptions options) { + int numBytes = (Integer.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.UInt32, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.UInt32, TypeArgumentList.Empty, metaBytes); + this.WriteUInt32(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + (Integer.SIZE / Byte.SIZE)); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteSparseUInt64(ref RowCursor edit, ulong value, UpdateOptions options) + public void WriteSparseUInt64(tangible.RefObject edit, long value, UpdateOptions options) { + int numBytes = (Long.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.UInt64, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.UInt64, TypeArgumentList.Empty, metaBytes); + this.WriteUInt64(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + (Long.SIZE / Byte.SIZE)); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteSparseUInt8(ref RowCursor edit, byte value, UpdateOptions options) + public void WriteSparseUInt8(tangible.RefObject edit, byte value, UpdateOptions options) { + int numBytes = 1; + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.UInt8, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.UInt8, TypeArgumentList.Empty, metaBytes); + this.WriteUInt8(edit.argValue.valueOffset, value); + checkState(spaceNeeded == metaBytes + 1); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseUnixDateTime(tangible.RefObject edit, UnixDateTime value, UpdateOptions options) { + int numBytes = 8; + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.UnixDateTime, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes + , tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + + this.WriteSparseMetadata(edit, LayoutType.UnixDateTime, TypeArgumentList.Empty, metaBytes); + this.WriteUnixDateTime(edit.argValue.valueOffset, value.clone()); + checkState(spaceNeeded == metaBytes + 8); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + public void WriteSparseVarInt(tangible.RefObject edit, long value, UpdateOptions options) { + int numBytes = RowBuffer.Count7BitEncodedInt(value); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.VarInt, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.VarInt, TypeArgumentList.Empty, metaBytes); + int sizeLenInBytes = this.Write7BitEncodedInt(edit.argValue.valueOffset, value); + checkState(sizeLenInBytes == numBytes); + checkState(spaceNeeded == metaBytes + sizeLenInBytes); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteSparseVarUInt(ref RowCursor edit, ulong value, UpdateOptions options) + public void WriteSparseVarUInt(tangible.RefObject edit, long value, UpdateOptions options) { + int numBytes = RowBuffer.Count7BitEncodedUInt(value); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, LayoutType.VarUInt, TypeArgumentList.Empty, numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, LayoutType.VarUInt, TypeArgumentList.Empty, metaBytes); + int sizeLenInBytes = this.Write7BitEncodedUInt(edit.argValue.valueOffset, value); + checkState(sizeLenInBytes == numBytes); + checkState(spaceNeeded == metaBytes + sizeLenInBytes); + edit.argValue.endOffset = edit.argValue.metaOffset + spaceNeeded; + this.length += shift; + } + + /** + * Copies the content of the buffer into the target stream. + */ + public void WriteTo(OutputStream stream) { + stream.Write(this.buffer.Slice(0, this.length)); + } + + public void WriteTypedArray(tangible.RefObject edit, LayoutScope scopeType, TypeArgumentList typeArgs, + UpdateOptions options, tangible.OutObject newScope) { + int numBytes = (Integer.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, scopeType, typeArgs.clone(), numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, scopeType, typeArgs.clone(), metaBytes); + checkState(spaceNeeded == metaBytes + numBytes); + this.WriteUInt32(edit.argValue.valueOffset, 0); + int valueOffset = edit.argValue.valueOffset + (Integer.SIZE / Byte.SIZE); // Point after the Size + newScope.argValue = new RowCursor(); + newScope.argValue.scopeType = scopeType; + newScope.argValue.scopeTypeArgs = typeArgs.clone(); + newScope.argValue.start = edit.argValue.valueOffset; + newScope.argValue.valueOffset = valueOffset; + newScope.argValue.metaOffset = valueOffset; + newScope.argValue.layout = edit.argValue.layout; + + this.length += shift; + } + + public void WriteTypedMap(tangible.RefObject edit, LayoutScope scopeType, TypeArgumentList typeArgs, + UpdateOptions options, tangible.OutObject newScope) { + int numBytes = (Integer.SIZE / Byte.SIZE); // Sized scope. + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, scopeType, typeArgs.clone(), numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, scopeType, typeArgs.clone(), metaBytes); + checkState(spaceNeeded == metaBytes + numBytes); + this.WriteUInt32(edit.argValue.valueOffset, 0); + int valueOffset = edit.argValue.valueOffset + (Integer.SIZE / Byte.SIZE); // Point after the Size + newScope.argValue = new RowCursor(); + newScope.argValue.scopeType = scopeType; + newScope.argValue.scopeTypeArgs = typeArgs.clone(); + newScope.argValue.start = edit.argValue.valueOffset; + newScope.argValue.valueOffset = valueOffset; + newScope.argValue.metaOffset = valueOffset; + newScope.argValue.layout = edit.argValue.layout; + + this.length += shift; + } + + public void WriteTypedSet(tangible.RefObject edit, LayoutScope scopeType, TypeArgumentList typeArgs, + UpdateOptions options, tangible.OutObject newScope) { + int numBytes = (Integer.SIZE / Byte.SIZE); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, scopeType, typeArgs.clone(), numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, scopeType, typeArgs.clone(), metaBytes); + checkState(spaceNeeded == metaBytes + numBytes); + this.WriteUInt32(edit.argValue.valueOffset, 0); + int valueOffset = edit.argValue.valueOffset + (Integer.SIZE / Byte.SIZE); // Point after the Size + newScope.argValue = new RowCursor(); + newScope.argValue.scopeType = scopeType; + newScope.argValue.scopeTypeArgs = typeArgs.clone(); + newScope.argValue.start = edit.argValue.valueOffset; + newScope.argValue.valueOffset = valueOffset; + newScope.argValue.metaOffset = valueOffset; + newScope.argValue.layout = edit.argValue.layout; + + this.length += shift; + } + + public void WriteTypedTuple(tangible.RefObject edit, LayoutScope scopeType, TypeArgumentList typeArgs, + UpdateOptions options, tangible.OutObject newScope) { + int numBytes = this.CountDefaultValue(scopeType, typeArgs.clone()); + int metaBytes; + tangible.OutObject tempOut_metaBytes = new tangible.OutObject(); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + this.EnsureSparse(edit, scopeType, typeArgs.clone(), numBytes, options, tempOut_metaBytes, + tempOut_spaceNeeded, tempOut_shift); + shift = tempOut_shift.argValue; + spaceNeeded = tempOut_spaceNeeded.argValue; + metaBytes = tempOut_metaBytes.argValue; + this.WriteSparseMetadata(edit, scopeType, typeArgs.clone(), metaBytes); + int numWritten = this.WriteDefaultValue(edit.argValue.valueOffset, scopeType, typeArgs.clone()); + checkState(numBytes == numWritten); + checkState(spaceNeeded == metaBytes + numBytes); + newScope.argValue = new RowCursor(); + newScope.argValue.scopeType = scopeType; + newScope.argValue.scopeTypeArgs = typeArgs.clone(); + newScope.argValue.start = edit.argValue.valueOffset; + newScope.argValue.valueOffset = edit.argValue.valueOffset; + newScope.argValue.metaOffset = edit.argValue.valueOffset; + newScope.argValue.layout = edit.argValue.layout; + newScope.argValue.count = typeArgs.getCount(); + + this.length += shift; + tangible.RefObject tempRef_this = + new tangible.RefObject(this); + azure.data.cosmos.serialization.hybridrow.RowCursorExtensions.MoveNext(newScope.argValue.clone(), tempRef_this); + this = tempRef_this.argValue; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteUInt16(int offset, ushort value) + public void WriteUInt16(int offset, short value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MemoryMarshal.Write(this.buffer.Slice(offset), ref value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteUInt32(int offset, uint value) + public void WriteUInt32(int offset, int value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MemoryMarshal.Write(this.buffer.Slice(offset), ref value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteUInt64(int offset, ulong value) + public void WriteUInt64(int offset, long value) { + tangible.RefObject tempRef_value = new tangible.RefObject(value); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MemoryMarshal.Write(this.buffer.Slice(offset), ref value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void WriteUInt8(int offset, byte value) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void WriteUInt8(int offset, byte value) + public void WriteUInt8(int offset, byte value) { + this.buffer[offset] = value; + } + + public void WriteUnixDateTime(int offset, UnixDateTime value) { + tangible.RefObject tempRef_value = + new tangible.RefObject(value); + MemoryMarshal.Write(this.buffer.Slice(offset), tempRef_value); + value = tempRef_value.argValue; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteVariableBinary(int offset, ReadOnlySpan value, bool exists, out int shift) + public void WriteVariableBinary(int offset, ReadOnlySpan value, boolean exists, + tangible.OutObject shift) { + int numBytes = value.Length; + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + this.EnsureVariable(offset, false, numBytes, exists, tempOut_spaceNeeded, shift); + spaceNeeded = tempOut_spaceNeeded.argValue; + + int sizeLenInBytes = this.WriteBinary(offset, value); + checkState(spaceNeeded == numBytes + sizeLenInBytes); + this.length += shift.argValue; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteVariableBinary(int offset, ReadOnlySequence value, bool exists, out int + // shift) + public void WriteVariableBinary(int offset, ReadOnlySequence value, boolean exists, + tangible.OutObject shift) { + int numBytes = (int)value.Length; + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + this.EnsureVariable(offset, false, numBytes, exists, tempOut_spaceNeeded, shift); + spaceNeeded = tempOut_spaceNeeded.argValue; + + int sizeLenInBytes = this.WriteBinary(offset, value); + checkState(spaceNeeded == numBytes + sizeLenInBytes); + this.length += shift.argValue; + } + + public void WriteVariableInt(int offset, long value, boolean exists, tangible.OutObject shift) { + int numBytes = RowBuffer.Count7BitEncodedInt(value); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + this.EnsureVariable(offset, true, numBytes, exists, tempOut_spaceNeeded, shift); + spaceNeeded = tempOut_spaceNeeded.argValue; + + int sizeLenInBytes = this.Write7BitEncodedInt(offset, value); + checkState(sizeLenInBytes == numBytes); + checkState(spaceNeeded == numBytes); + this.length += shift.argValue; + } + + public void WriteVariableString(int offset, Utf8Span value, boolean exists, tangible.OutObject shift) { + int numBytes = value.Length; + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + this.EnsureVariable(offset, false, numBytes, exists, tempOut_spaceNeeded, shift); + spaceNeeded = tempOut_spaceNeeded.argValue; + + int sizeLenInBytes = this.WriteString(offset, value); + checkState(spaceNeeded == numBytes + sizeLenInBytes); + this.length += shift.argValue; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal void WriteVariableUInt(int offset, ulong value, bool exists, out int shift) + public void WriteVariableUInt(int offset, long value, boolean exists, tangible.OutObject shift) { + int numBytes = RowBuffer.Count7BitEncodedUInt(value); + int spaceNeeded; + tangible.OutObject tempOut_spaceNeeded = new tangible.OutObject(); + this.EnsureVariable(offset, true, numBytes, exists, tempOut_spaceNeeded, shift); + spaceNeeded = tempOut_spaceNeeded.argValue; + + int sizeLenInBytes = this.Write7BitEncodedUInt(offset, value); + checkState(sizeLenInBytes == numBytes); + checkState(spaceNeeded == numBytes); + this.length += shift.argValue; + } + + public RowBuffer clone() { + RowBuffer varCopy = new RowBuffer(); + + varCopy.resizer = this.resizer; + varCopy.buffer = this.buffer; + varCopy.resolver = this.resolver; + varCopy.length = this.length; + + return varCopy; + } + + /** + * Compares the values of two encoded fields using the hybrid row binary collation. + * + * @param left An edit describing the left field. + * @param leftLen The size of the left field's value in bytes. + * @param right An edit describing the right field. + * @param rightLen The size of the right field's value in bytes. + * @return + * + * -1left less than right. + * + * 0left and right are equal. + * + * 1left is greater than right. + * + * + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1201", Justification = "Logical + // Grouping.")] private int CompareFieldValue(RowCursor left, int leftLen, RowCursor right, int rightLen) + private int CompareFieldValue(RowCursor left, int leftLen, RowCursor right, int rightLen) { + if (left.cellType.LayoutCode.getValue() < right.cellType.LayoutCode.getValue()) { + return -1; + } + + if (left.cellType == right.cellType) { + if (leftLen < rightLen) { + return -1; + } + + if (leftLen == rightLen) { + return this.buffer.Slice(left.valueOffset, leftLen).SequenceCompareTo(this.buffer.Slice(right.valueOffset, rightLen)); + } + } + + return 1; + } + + /** + * Compares the values of two encoded key-value pair fields using the hybrid row binary + * collation. + * + * @param left An edit describing the left field. + * @param right An edit describing the right field. + * @return + * + * -1left less than right. + * + * 0left and right are equal. + * + * 1left is greater than right. + * + * + */ + private int CompareKeyValueFieldValue(RowCursor left, RowCursor right) { + LayoutTypedTuple leftScopeType = left.cellType instanceof LayoutTypedTuple ? (LayoutTypedTuple)left.cellType : + null; + LayoutTypedTuple rightScopeType = right.cellType instanceof LayoutTypedTuple ? + (LayoutTypedTuple)right.cellType : null; + checkArgument(leftScopeType != null); + checkArgument(rightScopeType != null); + checkArgument(left.cellTypeArgs.getCount() == 2); + checkArgument(left.cellTypeArgs.equals(right.cellTypeArgs.clone())); + + RowCursor leftKey = new RowCursor(); + leftKey.layout = left.layout; + leftKey.scopeType = leftScopeType; + leftKey.scopeTypeArgs = left.cellTypeArgs.clone(); + leftKey.start = left.valueOffset; + leftKey.metaOffset = left.valueOffset; + leftKey.index = 0; + + tangible.RefObject tempRef_leftKey = + new tangible.RefObject(leftKey); + this.ReadSparseMetadata(tempRef_leftKey); + leftKey = tempRef_leftKey.argValue; + checkState(leftKey.pathOffset == 0); + tangible.RefObject tempRef_leftKey2 = + new tangible.RefObject(leftKey); + int leftKeyLen = this.SparseComputeSize(tempRef_leftKey2) - (leftKey.valueOffset - leftKey.metaOffset); + leftKey = tempRef_leftKey2.argValue; + + RowCursor rightKey = new RowCursor(); + rightKey.layout = right.layout; + rightKey.scopeType = rightScopeType; + rightKey.scopeTypeArgs = right.cellTypeArgs.clone(); + rightKey.start = right.valueOffset; + rightKey.metaOffset = right.valueOffset; + rightKey.index = 0; + + tangible.RefObject tempRef_rightKey = + new tangible.RefObject(rightKey); + this.ReadSparseMetadata(tempRef_rightKey); + rightKey = tempRef_rightKey.argValue; + checkState(rightKey.pathOffset == 0); + tangible.RefObject tempRef_rightKey2 = + new tangible.RefObject(rightKey); + int rightKeyLen = this.SparseComputeSize(tempRef_rightKey2) - (rightKey.valueOffset - rightKey.metaOffset); + rightKey = tempRef_rightKey2.argValue; + + return this.CompareFieldValue(leftKey.clone(), leftKeyLen, rightKey.clone(), rightKeyLen); + } + + /** + * Compute the number of bytes necessary to store the signed integer using the varint + * encoding. + * + * @param value The value to be encoded. + * @return The number of bytes needed to store the varint encoding of . + */ + private static int Count7BitEncodedInt(long value) { + return RowBuffer.Count7BitEncodedUInt(RowBuffer.RotateSignToLsb(value)); + } + + /** + * Return the size (in bytes) of the default sparse value for the type. + * + * @param code The type of the default value. + * @param typeArgs + */ + private int CountDefaultValue(LayoutType code, TypeArgumentList typeArgs) { + // JTHTODO: convert to a virtual? + switch (code) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutNull _: + case LayoutNull + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutBoolean _: + case LayoutBoolean _: + return 1; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutInt8 _: + case LayoutInt8 + _: + return LayoutType.Int8.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutInt16 _: + case LayoutInt16 + _: + return LayoutType.Int16.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutInt32 _: + case LayoutInt32 + _: + return LayoutType.Int32.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutInt64 _: + case LayoutInt64 + _: + return LayoutType.Int64.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUInt8 _: + case LayoutUInt8 + _: + return LayoutType.UInt8.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUInt16 _: + case LayoutUInt16 + _: + return LayoutType.UInt16.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUInt32 _: + case LayoutUInt32 + _: + return LayoutType.UInt32.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUInt64 _: + case LayoutUInt64 + _: + return LayoutType.UInt64.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutFloat32 _: + case LayoutFloat32 + _: + return LayoutType.Float32.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutFloat64 _: + case LayoutFloat64 + _: + return LayoutType.Float64.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutFloat128 _: + case LayoutFloat128 + _: + return LayoutType.Float128.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutDecimal _: + case LayoutDecimal + _: + return LayoutType.Decimal.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutDateTime _: + case LayoutDateTime + _: + return LayoutType.DateTime.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUnixDateTime _: + case LayoutUnixDateTime + _: + return LayoutType.UnixDateTime.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutGuid _: + case LayoutGuid + _: + return LayoutType.Guid.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutMongoDbObjectId _: + case LayoutMongoDbObjectId + _: + return MongoDbObjectId.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUtf8 _: + case LayoutUtf8 + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutBinary _: + case LayoutBinary _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutVarInt _: + case LayoutVarInt _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutVarUInt _: + case LayoutVarUInt _: + + // Variable length types preceded by their varuint size take 1 byte for a size of 0. + return 1; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutObject _: + case LayoutObject + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutArray _: + case LayoutArray _: + + // Variable length sparse collection scopes take 1 byte for the end-of-scope terminator. + return (LayoutCode.SIZE / Byte.SIZE); + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedArray _: + case LayoutTypedArray + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedSet _: + case LayoutTypedSet _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedMap _: + case LayoutTypedMap _: + + // Variable length typed collection scopes preceded by their scope size take sizeof(uint) for a size of 0. + return (Integer.SIZE / Byte.SIZE); + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTuple _: + case LayoutTuple + _: + + // Fixed arity sparse collections take 1 byte for end-of-scope plus a null for each element. + return (LayoutCode.SIZE / Byte.SIZE) + ((LayoutCode.SIZE / Byte.SIZE) * typeArgs.getCount()); + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedTuple _: + case LayoutTypedTuple + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTagged _: + case LayoutTagged _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTagged2 _: + case LayoutTagged2 _: + + // Fixed arity typed collections take the sum of the default values of each element. The scope size is implied by the arity. + int sum = 0; + for (TypeArgument arg : typeArgs) { + sum += this.CountDefaultValue(arg.getType(), arg.getTypeArgs().clone()); + } + + return sum; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutNullable _: + case LayoutNullable + _: + + // Nullables take the default values of the value plus null. The scope size is implied by the arity. + return 1 + this.CountDefaultValue(typeArgs.get(0).getType(), typeArgs.get(0).getTypeArgs().clone()); + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUDT _: + case LayoutUDT + _: + Layout udt = this.resolver.Resolve(typeArgs.getSchemaId().clone()); + return udt.getSize() + (LayoutCode.SIZE / Byte.SIZE); + + default: + Contract.Fail(String.format("Not Implemented: %1$s", code)); + return 0; + } + } + + private static int CountSparsePath(tangible.RefObject edit) { + if (!edit.argValue.writePathToken.getIsNull()) { + return edit.argValue.writePathToken.Varint.length; + } + + tangible.OutObject tempOut_writePathToken = + new tangible.OutObject(); + if (edit.argValue.layout.getTokenizer().TryFindToken(edit.argValue.writePath, tempOut_writePathToken)) { + edit.argValue.argValue.writePathToken = tempOut_writePathToken.argValue; + return edit.argValue.writePathToken.Varint.length; + } else { + edit.argValue.argValue.writePathToken = tempOut_writePathToken.argValue; + } + + int numBytes = edit.argValue.writePath.ToUtf8String().Length; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: int sizeLenInBytes = RowBuffer.Count7BitEncodedUInt((ulong)(edit.layout.Tokenizer.Count + + // numBytes)); + int sizeLenInBytes = + RowBuffer.Count7BitEncodedUInt((long)(edit.argValue.layout.getTokenizer().getCount() + numBytes)); + return sizeLenInBytes + numBytes; + } + + private void Ensure(int size) { + if (this.buffer.Length < size) { + this.buffer = this.resizer.Resize(size, this.buffer); + } + } + + /** + * + * . + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnsureSparse(ref RowCursor edit, + // LayoutType cellType, TypeArgumentList typeArgs, int numBytes, UpdateOptions options, out int metaBytes, out + // int spaceNeeded, out int shift) + private void EnsureSparse(tangible.RefObject edit, LayoutType cellType, TypeArgumentList typeArgs, + int numBytes, UpdateOptions options, tangible.OutObject metaBytes, + tangible.OutObject spaceNeeded, tangible.OutObject shift) { + this.EnsureSparse(edit, cellType, typeArgs.clone(), numBytes, RowOptions.forValue(options), metaBytes, + spaceNeeded, shift); + } + + /** + * Ensure that sufficient space exists in the row buffer to write the current value. + * + * @param edit The prepared edit indicating where and in what context the current write will + * happen. + * @param cellType The type of the field to be written. + * @param typeArgs The type arguments of the field to be written. + * @param numBytes The number of bytes needed to encode the value of the field to be written. + * @param options The kind of edit to be performed. + * @param metaBytes On success, the number of bytes needed to encode the metadata of the new + * field. + * @param spaceNeeded On success, the number of bytes needed in total to encode the new field + * and its metadata. + * @param shift On success, the number of bytes the length of the row buffer was increased + * (which may be negative if the row buffer was shrunk). + */ + private void EnsureSparse(tangible.RefObject edit, LayoutType cellType, TypeArgumentList typeArgs, + int numBytes, RowOptions options, tangible.OutObject metaBytes, + tangible.OutObject spaceNeeded, + tangible.OutObject shift) { + int metaOffset = edit.argValue.metaOffset; + int spaceAvailable = 0; + + // Compute the metadata offsets + if (edit.argValue.scopeType.HasImplicitTypeCode(edit)) { + metaBytes.argValue = 0; + } else { + metaBytes.argValue = cellType.CountTypeArgument(typeArgs.clone()); + } + + if (!edit.argValue.scopeType.IsIndexedScope) { + checkState(edit.argValue.writePath != null); + int pathLenInBytes = RowBuffer.CountSparsePath(edit); + metaBytes.argValue += pathLenInBytes; + } + + if (edit.argValue.exists) { + // Compute value offset for existing value to be overwritten. + spaceAvailable = this.SparseComputeSize(edit); + } + + spaceNeeded.argValue = options == RowOptions.Delete ? 0 : metaBytes.argValue + numBytes; + shift.argValue = spaceNeeded.argValue - spaceAvailable; + if (shift.argValue > 0) { + this.Ensure(this.length + shift.argValue); + } + + this.buffer.Slice(metaOffset + spaceAvailable, this.length - (metaOffset + spaceAvailable)).CopyTo(this.buffer.Slice(metaOffset + spaceNeeded.argValue)); + + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + if (shift.argValue < 0) { + // Fill deleted bits (in debug builds) to detect overflow/alignment errors. + this.buffer.Slice(this.length + shift.argValue, -shift.argValue).Fill(0xFF); + } + //#endif + + // Update the stored size (fixed arity scopes don't store the size because it is implied by the type args). + if (edit.argValue.scopeType.IsSizedScope && !edit.argValue.scopeType.IsFixedArity) { + if ((options == RowOptions.Insert) || (options == RowOptions.InsertAt) || ((options == RowOptions.Upsert) && !edit.argValue.exists)) { + // Add one to the current scope count. + checkState(!edit.argValue.exists); + this.IncrementUInt32(edit.argValue.start, 1); + edit.argValue.count++; + } else if ((options == RowOptions.Delete) && edit.argValue.exists) { + // Subtract one from the current scope count. + checkState(this.ReadUInt32(edit.argValue.start) > 0); + this.DecrementUInt32(edit.argValue.start, 1); + edit.argValue.count--; + } + } + + if (options == RowOptions.Delete) { + edit.argValue.cellType = null; + edit.argValue.cellTypeArgs = null; + edit.argValue.exists = false; + } else { + edit.argValue.cellType = cellType; + edit.argValue.cellTypeArgs = typeArgs.clone(); + edit.argValue.exists = true; + } + } + + private void EnsureVariable(int offset, boolean isVarint, int numBytes, boolean exists, + tangible.OutObject spaceNeeded, tangible.OutObject shift) { + int spaceAvailable = 0; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong existingValueBytes = 0; + long existingValueBytes = 0; + if (exists) { + tangible.OutObject tempOut_spaceAvailable = new tangible.OutObject(); + existingValueBytes = this.Read7BitEncodedUInt(offset, tempOut_spaceAvailable); + spaceAvailable = tempOut_spaceAvailable.argValue; + } + + if (isVarint) { + spaceNeeded.argValue = numBytes; + } else { + spaceAvailable += (int)existingValueBytes; // size already in spaceAvailable + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: spaceNeeded = numBytes + RowBuffer.Count7BitEncodedUInt((ulong)numBytes); + spaceNeeded.argValue = numBytes + RowBuffer.Count7BitEncodedUInt(numBytes); + } + + shift.argValue = spaceNeeded.argValue - spaceAvailable; + if (shift.argValue > 0) { + this.Ensure(this.length + shift.argValue); + this.buffer.Slice(offset + spaceAvailable, this.length - (offset + spaceAvailable)).CopyTo(this.buffer.Slice(offset + spaceNeeded.argValue)); + } else if (shift.argValue < 0) { + this.buffer.Slice(offset + spaceAvailable, this.length - (offset + spaceAvailable)).CopyTo(this.buffer.Slice(offset + spaceNeeded.argValue)); + } + } + + /** + * Reads in the contents of the RowBuffer from an input stream and initializes the row buffer + * with the associated layout and rowVersion. + * + * @return true if the serialization succeeded. false if the input stream was corrupted. + */ + private boolean InitReadFrom(HybridRowVersion rowVersion) { + HybridRowHeader header = this.ReadHeader(0).clone(); + Layout layout = this.resolver.Resolve(header.getSchemaId().clone()); + Contract.Assert(azure.data.cosmos.serialization.hybridrow.SchemaId.opEquals(header.getSchemaId().clone(), + layout.getSchemaId().clone())); + return (header.getVersion() == rowVersion) && (HybridRowHeader.Size + layout.getSize() <= this.length); + } + + /** + * Sorts the array structure using the hybrid row binary + * collation. + * + * @param scope The scope to be sorted. + * @param dstEdit A edit that points at the scope. + * @param uniqueIndex A unique index array structure that identifies the row offsets of each + * element in the scope. + * @return true if the array was sorted, false if a duplicate was found during sorting. + *

+ * Implementation Note: + *

This method MUST guarantee that if at least one duplicate exists it will be found.

+ * Insertion Sort is used for this purpose as it guarantees that each value is eventually compared + * against its previous item in sorted order. If any two successive items are the same they must be + * duplicates. + *

+ * Other search algorithms, such as Quick Sort or Merge Sort, may offer fewer comparisons in the + * limit but don't necessarily guarantee that duplicates will be discovered. If an alternative + * algorithm is used, then an independent duplicate pass MUST be employed. + *

+ *

+ * Under the current operational assumptions, the expected cardinality of sets and maps is + * expected to be relatively small. If this assumption changes, Insertion Sort may no longer be the + * best choice. + *

+ */ + private boolean InsertionSort(tangible.RefObject scope, tangible.RefObject dstEdit, + Span uniqueIndex) { + RowCursor leftEdit = dstEdit.argValue.clone(); + RowCursor rightEdit = dstEdit.argValue.clone(); + + for (int i = 1; i < uniqueIndex.Length; i++) { + UniqueIndexItem x = uniqueIndex[i]; + leftEdit.cellType = LayoutType.FromCode(x.Code); + leftEdit.metaOffset = x.MetaOffset; + leftEdit.valueOffset = x.ValueOffset; + int leftBytes = x.Size - (x.ValueOffset - x.MetaOffset); + + // Walk backwards searching for the insertion point for the item as position i. + int j; + for (j = i - 1; j >= 0; j--) { + UniqueIndexItem y = uniqueIndex[j]; + rightEdit.cellType = LayoutType.FromCode(y.Code); + rightEdit.metaOffset = y.MetaOffset; + rightEdit.valueOffset = y.ValueOffset; + + int cmp; + if (scope.argValue.scopeType instanceof LayoutTypedMap) { + cmp = this.CompareKeyValueFieldValue(leftEdit.clone(), rightEdit.clone()); + } else { + int rightBytes = y.Size - (y.ValueOffset - y.MetaOffset); + cmp = this.CompareFieldValue(leftEdit.clone(), leftBytes, rightEdit.clone(), rightBytes); + } + + // If there are duplicates then fail. + if (cmp == 0) { + return false; + } + + if (cmp > 0) { + break; + } + + // Swap the jth item to the right to make space for the ith item which is smaller. + uniqueIndex[j + 1] = uniqueIndex[j]; + } + + // Insert the ith item into the sorted array. + uniqueIndex[j + 1] = x.clone(); + } + + return true; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private ReadOnlySpan ReadBinary(int offset, out int sizeLenInBytes) + private ReadOnlySpan ReadBinary(int offset, tangible.OutObject sizeLenInBytes) { + int numBytes = (int)this.Read7BitEncodedUInt(offset, sizeLenInBytes); + return this.buffer.Slice(offset + sizeLenInBytes.argValue, numBytes); + } + + /** + * Read the metadata of an encoded sparse field. + * + * @param edit The edit structure to fill in. + * + * + * On success, the path of the field at the given offset, otherwise + * undefined. + * + * + * On success, the offset to the metadata of the field, otherwise a + * location to insert the field. + * + * + * On success, the layout code of the existing field, otherwise + * undefined. + * + * + * On success, the type args of the existing field, otherwise + * undefined. + * + * + * On success, the offset to the value of the field, otherwise + * undefined. + * . + */ + private void ReadSparseMetadata(tangible.RefObject edit) { + if (edit.argValue.scopeType.HasImplicitTypeCode(edit)) { + edit.argValue.scopeType.SetImplicitTypeCode(edit); + edit.argValue.valueOffset = edit.argValue.metaOffset; + } else { + edit.argValue.cellType = this.ReadSparseTypeCode(edit.argValue.metaOffset); + edit.argValue.valueOffset = edit.argValue.metaOffset + (LayoutCode.SIZE / Byte.SIZE); + edit.argValue.cellTypeArgs = TypeArgumentList.Empty; + if (edit.argValue.cellType instanceof LayoutEndScope) { + // Reached end of current scope without finding another field. + edit.argValue.pathToken = 0; + edit.argValue.pathOffset = 0; + edit.argValue.valueOffset = edit.argValue.metaOffset; + return; + } + + tangible.RefObject tempRef_this = + new tangible.RefObject(this); + int sizeLenInBytes; + tangible.OutObject tempOut_sizeLenInBytes = new tangible.OutObject(); + edit.argValue.cellTypeArgs = edit.argValue.cellType.ReadTypeArgumentList(tempRef_this, + edit.argValue.valueOffset, tempOut_sizeLenInBytes).clone(); + sizeLenInBytes = tempOut_sizeLenInBytes.argValue; + this = tempRef_this.argValue; + edit.argValue.valueOffset += sizeLenInBytes; + } + + tangible.RefObject tempRef_this2 = + new tangible.RefObject(this); + edit.argValue.scopeType.ReadSparsePath(tempRef_this2, edit); + this = tempRef_this2.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [Conditional("DEBUG")] private void ReadSparsePrimitiveTypeCode(ref RowCursor edit, LayoutType + // code) + private void ReadSparsePrimitiveTypeCode(tangible.RefObject edit, LayoutType code) { + checkState(edit.argValue.exists); + + if (edit.argValue.scopeType.HasImplicitTypeCode(edit)) { + if (edit.argValue.scopeType instanceof LayoutNullable) { + checkState(edit.argValue.scopeTypeArgs.getCount() == 1); + checkState(edit.argValue.index == 1); + checkState(edit.argValue.scopeTypeArgs.get(0).getType() == code); + checkState(edit.argValue.scopeTypeArgs.get(0).getTypeArgs().getCount() == 0); + } else if (edit.argValue.scopeType.IsFixedArity) { + checkState(edit.argValue.scopeTypeArgs.getCount() > edit.argValue.index); + checkState(edit.argValue.scopeTypeArgs.get(edit.argValue.index).getType() == code); + checkState(edit.argValue.scopeTypeArgs.get(edit.argValue.index).getTypeArgs().getCount() == 0); + } else { + checkState(edit.argValue.scopeTypeArgs.getCount() == 1); + checkState(edit.argValue.scopeTypeArgs.get(0).getType() == code); + checkState(edit.argValue.scopeTypeArgs.get(0).getTypeArgs().getCount() == 0); + } + } else { + if (code == LayoutType.Boolean) { + code = this.ReadSparseTypeCode(edit.argValue.metaOffset); + checkState(code == LayoutType.Boolean || code == LayoutType.BooleanFalse); + } else { + checkState(this.ReadSparseTypeCode(edit.argValue.metaOffset) == code); + } + } + + if (edit.argValue.scopeType.IsIndexedScope) { + checkState(edit.argValue.pathOffset == 0); + checkState(edit.argValue.pathToken == 0); + } else { + int _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + int pathOffset; + tangible.OutObject tempOut_pathOffset = new tangible.OutObject(); + int token = this.ReadSparsePathLen(edit.argValue.layout, + edit.argValue.metaOffset + (LayoutCode.SIZE / Byte.SIZE), tempOut__, tempOut_pathOffset); + pathOffset = tempOut_pathOffset.argValue; + _ = tempOut__.argValue; + checkState(edit.argValue.pathOffset == pathOffset); + checkState(edit.argValue.pathToken == token); + } + } + + private Utf8Span ReadString(int offset, tangible.OutObject sizeLenInBytes) { + int numBytes = (int)this.Read7BitEncodedUInt(offset, sizeLenInBytes); + return Utf8Span.UnsafeFromUtf8BytesNoValidation(this.buffer.Slice(offset + sizeLenInBytes.argValue, numBytes)); + } + + /** + * Skip over a nested scope. + * + * @param edit The sparse scope to search. + * @return The 0-based byte offset immediately following the scope end marker. + */ + private int SkipScope(tangible.RefObject edit) { + while (this.SparseIteratorMoveNext(edit)) { + } + + if (!edit.argValue.scopeType.IsSizedScope) { + edit.argValue.metaOffset += (LayoutCode.SIZE / Byte.SIZE); // Move past the end of scope marker. + } + + return edit.argValue.metaOffset; + } + + /** + * Compute the size of a sparse (primitive) field. + * + * @param cellType The type of the current sparse field. + * @param metaOffset The 0-based offset from the beginning of the row where the field begins. + * @param valueOffset The 0-based offset from the beginning of the row where the field's value + * begins. + * @return The length (in bytes) of the encoded field including the metadata and the value. + */ + private int SparseComputePrimitiveSize(LayoutType cellType, int metaOffset, int valueOffset) { + // JTHTODO: convert to a virtual? + int metaBytes = valueOffset - metaOffset; + LayoutCode code = cellType.LayoutCode; + switch (code) { + case Null: + checkState(LayoutType.Null.Size == 0); + return metaBytes; + + case Boolean: + case BooleanFalse: + checkState(LayoutType.Boolean.Size == 0); + return metaBytes; + + case Int8: + return metaBytes + LayoutType.Int8.Size; + + case Int16: + return metaBytes + LayoutType.Int16.Size; + + case Int32: + return metaBytes + LayoutType.Int32.Size; + + case Int64: + return metaBytes + LayoutType.Int64.Size; + + case UInt8: + return metaBytes + LayoutType.UInt8.Size; + + case UInt16: + return metaBytes + LayoutType.UInt16.Size; + + case UInt32: + return metaBytes + LayoutType.UInt32.Size; + + case UInt64: + return metaBytes + LayoutType.UInt64.Size; + + case Float32: + return metaBytes + LayoutType.Float32.Size; + + case Float64: + return metaBytes + LayoutType.Float64.Size; + + case Float128: + return metaBytes + LayoutType.Float128.Size; + + case Decimal: + return metaBytes + LayoutType.Decimal.Size; + + case DateTime: + return metaBytes + LayoutType.DateTime.Size; + + case UnixDateTime: + return metaBytes + LayoutType.UnixDateTime.Size; + + case Guid: + return metaBytes + LayoutType.Guid.Size; + + case MongoDbObjectId: + return metaBytes + MongoDbObjectId.Size; + + case Utf8: + case Binary: + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + ///#pragma warning disable SA1137 // Elements should have the same indentation + { + int sizeLenInBytes; + tangible.OutObject tempOut_sizeLenInBytes = new tangible.OutObject(); + int numBytes = (int)this.Read7BitEncodedUInt(metaOffset + metaBytes, tempOut_sizeLenInBytes); + sizeLenInBytes = tempOut_sizeLenInBytes.argValue; + return metaBytes + sizeLenInBytes + numBytes; + } + + case VarInt: + case VarUInt: { + int sizeLenInBytes; + tangible.OutObject tempOut_sizeLenInBytes2 = new tangible.OutObject(); + this.Read7BitEncodedUInt(metaOffset + metaBytes, tempOut_sizeLenInBytes2); + sizeLenInBytes = tempOut_sizeLenInBytes2.argValue; + return metaBytes + sizeLenInBytes; + } + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + ///#pragma warning restore SA1137 // Elements should have the same indentation + + default: + Contract.Fail(String.format("Not Implemented: %1$s", code)); + return 0; + } + } + + /** + * Compute the size of a sparse field. + * + * @param edit The edit structure describing the field to measure. + * @return The length (in bytes) of the encoded field including the metadata and the value. + */ + private int SparseComputeSize(tangible.RefObject edit) { + if (!(edit.argValue.cellType instanceof LayoutScope)) { + return this.SparseComputePrimitiveSize(edit.argValue.cellType, edit.argValue.metaOffset, + edit.argValue.valueOffset); + } + + // Compute offset to end of value for current value. + RowCursor newScope = this.SparseIteratorReadScope(edit, true).clone(); + tangible.RefObject tempRef_newScope = + new tangible.RefObject(newScope); + int tempVar = this.SkipScope(tempRef_newScope) - edit.argValue.metaOffset; + newScope = tempRef_newScope.argValue; + return tempVar; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private int WriteBinary(int offset, ReadOnlySpan value) + private int WriteBinary(int offset, ReadOnlySpan value) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: int sizeLenInBytes = this.Write7BitEncodedUInt(offset, (ulong)value.Length); + int sizeLenInBytes = this.Write7BitEncodedUInt(offset, (long)value.Length); + value.CopyTo(this.buffer.Slice(offset + sizeLenInBytes)); + return sizeLenInBytes; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private int WriteBinary(int offset, ReadOnlySequence value) + private int WriteBinary(int offset, ReadOnlySequence value) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: int sizeLenInBytes = this.Write7BitEncodedUInt(offset, (ulong)value.Length); + int sizeLenInBytes = this.Write7BitEncodedUInt(offset, (long)value.Length); + value.CopyTo(this.buffer.Slice(offset + sizeLenInBytes)); + return sizeLenInBytes; + } + + private int WriteDefaultValue(int offset, LayoutType code, TypeArgumentList typeArgs) { + // JTHTODO: convert to a virtual? + switch (code) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutNull _: + case LayoutNull + _: + this.WriteSparseTypeCode(offset, code.LayoutCode); + return 1; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutBoolean _: + case LayoutBoolean + _: + this.WriteSparseTypeCode(offset, LayoutCode.BooleanFalse); + return 1; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutInt8 _: + case LayoutInt8 + _: + this.WriteInt8(offset, (byte)0); + return LayoutType.Int8.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutInt16 _: + case LayoutInt16 + _: + this.WriteInt16(offset, (short)0); + return LayoutType.Int16.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutInt32 _: + case LayoutInt32 + _: + this.WriteInt32(offset, 0); + return LayoutType.Int32.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutInt64 _: + case LayoutInt64 + _: + this.WriteInt64(offset, 0); + return LayoutType.Int64.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUInt8 _: + case LayoutUInt8 + _: + this.WriteUInt8(offset, (byte)0); + return LayoutType.UInt8.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUInt16 _: + case LayoutUInt16 + _: + this.WriteUInt16(offset, (short)0); + return LayoutType.UInt16.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUInt32 _: + case LayoutUInt32 + _: + this.WriteUInt32(offset, 0); + return LayoutType.UInt32.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUInt64 _: + case LayoutUInt64 + _: + this.WriteUInt64(offset, 0); + return LayoutType.UInt64.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutFloat32 _: + case LayoutFloat32 + _: + this.WriteFloat32(offset, 0); + return LayoutType.Float32.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutFloat64 _: + case LayoutFloat64 + _: + this.WriteFloat64(offset, 0); + return LayoutType.Float64.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutFloat128 _: + case LayoutFloat128 + _: + this.WriteFloat128(offset, null); + return LayoutType.Float128.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutDecimal _: + case LayoutDecimal + _: + this.WriteDecimal(offset, 0); + return LayoutType.Decimal.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutDateTime _: + case LayoutDateTime + _: + this.WriteDateTime(offset, LocalDateTime.MIN); + return LayoutType.DateTime.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUnixDateTime _: + case LayoutUnixDateTime + _: + this.WriteUnixDateTime(offset, null); + return LayoutType.UnixDateTime.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutGuid _: + case LayoutGuid + _: + this.WriteGuid(offset, null); + return LayoutType.Guid.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutMongoDbObjectId _: + case LayoutMongoDbObjectId + _: + this.WriteMongoDbObjectId(offset, null); + return MongoDbObjectId.Size; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUtf8 _: + case LayoutUtf8 + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutBinary _: + case LayoutBinary _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutVarInt _: + case LayoutVarInt _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutVarUInt _: + case LayoutVarUInt _: + + // Variable length types preceded by their varuint size take 1 byte for a size of 0. + return this.Write7BitEncodedUInt(offset, 0); + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutObject _: + case LayoutObject + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutArray _: + case LayoutArray _: + + // Variable length sparse collection scopes take 1 byte for the end-of-scope terminator. + this.WriteSparseTypeCode(offset, LayoutCode.EndScope); + return (LayoutCode.SIZE / Byte.SIZE); + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedArray _: + case LayoutTypedArray + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedSet _: + case LayoutTypedSet _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedMap _: + case LayoutTypedMap _: + + // Variable length typed collection scopes preceded by their scope size take sizeof(uint) for a size of 0. + this.WriteUInt32(offset, 0); + return (Integer.SIZE / Byte.SIZE); + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTuple _: + case LayoutTuple + _: + + // Fixed arity sparse collections take 1 byte for end-of-scope plus a null for each element. + for (int i = 0; i < typeArgs.getCount(); i++) { + this.WriteSparseTypeCode(offset, LayoutCode.Null); + } + + this.WriteSparseTypeCode(offset, LayoutCode.EndScope); + return (LayoutCode.SIZE / Byte.SIZE) + ((LayoutCode.SIZE / Byte.SIZE) * typeArgs.getCount()); + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedTuple _: + case LayoutTypedTuple + _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTagged _: + case LayoutTagged _: + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTagged2 _: + case LayoutTagged2 _: + + // Fixed arity typed collections take the sum of the default values of each element. The scope size is implied by the arity. + int sum = 0; + for (TypeArgument arg : typeArgs) { + sum += this.WriteDefaultValue(offset + sum, arg.getType(), arg.getTypeArgs().clone()); + } + + return sum; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutNullable _: + case LayoutNullable + _: + + // Nullables take the default values of the value plus null. The scope size is implied by the arity. + this.WriteInt8(offset, (byte)0); + return 1 + this.WriteDefaultValue(offset + 1, typeArgs.get(0).getType(), typeArgs.get(0).getTypeArgs().clone()); + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUDT _: + case LayoutUDT + _: + + // Clear all presence bits. + Layout udt = this.resolver.Resolve(typeArgs.getSchemaId().clone()); + this.buffer.Slice(offset, udt.getSize()).Fill(0); + + // Write scope terminator. + this.WriteSparseTypeCode(offset + udt.getSize(), LayoutCode.EndScope); + return udt.getSize() + (LayoutCode.SIZE / Byte.SIZE); + + default: + Contract.Fail(String.format("Not Implemented: %1$s", code)); + return 0; + } + } + + private void WriteSparseMetadata(tangible.RefObject edit, LayoutType cellType, + TypeArgumentList typeArgs, int metaBytes) { + int metaOffset = edit.argValue.metaOffset; + if (!edit.argValue.scopeType.HasImplicitTypeCode(edit)) { + tangible.RefObject tempRef_this = + new tangible.RefObject(this); + metaOffset += cellType.WriteTypeArgument(tempRef_this, metaOffset, typeArgs.clone()); + this = tempRef_this.argValue; + } + + this.WriteSparsePath(edit, metaOffset); + edit.argValue.valueOffset = edit.argValue.metaOffset + metaBytes; + checkState(edit.argValue.valueOffset == edit.argValue.metaOffset + metaBytes); + } + + private void WriteSparsePath(tangible.RefObject edit, int offset) { + // Some scopes don't encode paths, therefore the cost is always zero. + if (edit.argValue.scopeType.IsIndexedScope) { + edit.argValue.pathToken = 0; + edit.argValue.pathOffset = 0; + return; + } + + StringToken _; + tangible.OutObject tempOut__ = + new tangible.OutObject(); + Contract.Assert(!edit.argValue.layout.getTokenizer().TryFindToken(edit.argValue.writePath, tempOut__) || !edit.argValue.writePathToken.getIsNull()); + _ = tempOut__.argValue; + if (!edit.argValue.writePathToken.getIsNull()) { + edit.argValue.writePathToken.Varint.CopyTo(this.buffer.Slice(offset)); + edit.argValue.pathToken = edit.argValue.intValue().writePathToken.Id; + edit.argValue.pathOffset = offset; + } else { + // TODO: It would be better if we could avoid allocating here when the path is UTF16. + Utf8Span span = edit.argValue.writePath.ToUtf8String(); + edit.argValue.pathToken = edit.argValue.layout.getTokenizer().getCount() + span.Length; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: int sizeLenInBytes = this.Write7BitEncodedUInt(offset, (ulong)edit.pathToken); + int sizeLenInBytes = this.Write7BitEncodedUInt(offset, edit.argValue.longValue().pathToken); + edit.argValue.pathOffset = offset + sizeLenInBytes; + span.Span.CopyTo(this.buffer.Slice(offset + sizeLenInBytes)); + } + } + + private int WriteString(int offset, Utf8Span value) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: int sizeLenInBytes = this.Write7BitEncodedUInt(offset, (ulong)value.Length); + int sizeLenInBytes = this.Write7BitEncodedUInt(offset, (long)value.Length); + value.Span.CopyTo(this.buffer.Slice(offset + sizeLenInBytes)); + return sizeLenInBytes; + } + + /** + * represents a single item within a set/map scope that needs + * to be indexed. + *

+ *

+ * This structure is used when rebuilding a set/map index during row streaming via + * . + * + * Each item encodes its offsets and length within the row. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DebuggerDisplay("{MetaOffset}/{ValueOffset}")] private struct UniqueIndexItem + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ from the original: + //ORIGINAL LINE: [DebuggerDisplay("{MetaOffset}/{ValueOffset}")] private struct UniqueIndexItem + static final class UniqueIndexItem { + /** + * The layout code of the value. + */ + public LayoutCode Code = LayoutCode.values()[0]; + + /** + * If existing, the offset to the metadata of the existing field, otherwise the location to + * insert a new field. + */ + public int MetaOffset; + /** + * Size of the target element. + */ + public int Size; + /** + * If existing, the offset to the value of the existing field, otherwise undefined. + */ + public int ValueOffset; + + public UniqueIndexItem clone() { + UniqueIndexItem varCopy = new UniqueIndexItem(); + + varCopy.Code = this.Code; + varCopy.MetaOffset = this.MetaOffset; + varCopy.ValueOffset = this.ValueOffset; + varCopy.Size = this.Size; + + return varCopy; + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowCursor.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowCursor.java new file mode 100644 index 0000000..f4e7987 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowCursor.java @@ -0,0 +1,235 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter + +// ReSharper disable InconsistentNaming + +import azure.data.cosmos.serialization.hybridrow.layouts.Layout; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutEndScope; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutScope; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutType; +import azure.data.cosmos.serialization.hybridrow.layouts.StringToken; +import azure.data.cosmos.serialization.hybridrow.layouts.TypeArgument; +import azure.data.cosmos.serialization.hybridrow.layouts.TypeArgumentList; + +// ReSharper disable UseNameofExpression +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [DebuggerDisplay("{ToString()}")] public struct RowCursor +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: [DebuggerDisplay("{ToString()}")] public struct RowCursor +public final class RowCursor { + /** + * If existing, the layout code of the existing field, otherwise undefined. + */ + public LayoutType cellType; + /** + * For types with generic parameters (e.g. , the type parameters. + */ + public TypeArgumentList cellTypeArgs = new TypeArgumentList(); + /** + * For sized scopes (e.g. Typed Array), the number of elements. + */ + public int count; + /** + * If true, this scope is an unique index scope whose index will be built after its items are written. + */ + public boolean deferUniqueIndex; + /** + * If existing, the offset to the end of the existing field. Used as a hint when skipping + * forward. + */ + public int endOffset; + /** + * True if an existing field matching the search criteria was found. + */ + public boolean exists; + /** + * If true, this scope's nested fields cannot be updated individually. + * The entire scope can still be replaced. + */ + public boolean immutable; + /** + * For indexed scopes (e.g. Array), the 0-based index into the scope of the sparse field. + */ + public int index; + /** + * The layout describing the contents of the scope, or null if the scope is unschematized. + */ + public Layout layout; + /** + * If existing, the offset to the metadata of the existing field, otherwise the location to + * insert a new field. + */ + public int metaOffset; + /** + * If existing, the offset scope relative path for reading. + */ + public int pathOffset; + /** + * If existing, the layout string token of scope relative path for reading. + */ + public int pathToken; + /** + * The kind of scope within which this edit was prepared. + */ + public LayoutScope scopeType; + /** + * The type parameters of the scope within which this edit was prepared. + */ + public TypeArgumentList scopeTypeArgs = new TypeArgumentList(); + /** + * The 0-based byte offset from the beginning of the row where the first sparse field within + * the scope begins. + */ + public int start; + /** + * If existing, the offset to the value of the existing field, otherwise undefined. + */ + public int valueOffset; + /** + * If existing, the scope relative path for writing. + */ + public UtfAnyString writePath; + /** + * If WritePath is tokenized, then its token. + */ + public StringToken writePathToken = new StringToken(); + + public static RowCursor Create(tangible.RefObject row) { + SchemaId schemaId = row.argValue.ReadSchemaId(1).clone(); + Layout layout = row.argValue.getResolver().Resolve(schemaId.clone()); + int sparseSegmentOffset = row.argValue.ComputeVariableValueOffset(layout, HybridRowHeader.Size, + layout.getNumVariable()); + RowCursor tempVar = new RowCursor(); + tempVar.layout = layout; + tempVar.scopeType = LayoutType.UDT; + tempVar.scopeTypeArgs = new TypeArgumentList(schemaId.clone()); + tempVar.start = HybridRowHeader.Size; + tempVar.metaOffset = sparseSegmentOffset; + tempVar.valueOffset = sparseSegmentOffset; + return tempVar.clone(); + } + + // TODO: C# TO JAVA CONVERTER: 'ref return' methods are not converted by C# to Java Converter: + // public static ref RowCursor Create(ref RowBuffer row, out RowCursor cursor) + // { + // SchemaId schemaId = row.ReadSchemaId(1); + // Layout layout = row.Resolver.Resolve(schemaId); + // int sparseSegmentOffset = row.ComputeVariableValueOffset(layout, HybridRowHeader.Size, layout + // .NumVariable); + // cursor = new RowCursor { layout = layout, scopeType = LayoutType.UDT, scopeTypeArgs = new + // TypeArgumentList(schemaId), start = HybridRowHeader.Size, metaOffset = sparseSegmentOffset, + // valueOffset = sparseSegmentOffset}; + // + // return ref cursor; + // } + + // TODO: C# TO JAVA CONVERTER: 'ref return' methods are not converted by C# to Java Converter: + // public static ref RowCursor CreateForAppend(ref RowBuffer row, out RowCursor cursor) + // { + // SchemaId schemaId = row.ReadSchemaId(1); + // Layout layout = row.Resolver.Resolve(schemaId); + // cursor = new RowCursor { layout = layout, scopeType = LayoutType.UDT, scopeTypeArgs = new + // TypeArgumentList(schemaId), start = HybridRowHeader.Size, metaOffset = row.Length, valueOffset = row + // .Length}; + // + // return ref cursor; + // } + + public RowCursor clone() { + RowCursor varCopy = new RowCursor(); + + varCopy.layout = this.layout; + varCopy.scopeType = this.scopeType; + varCopy.scopeTypeArgs = this.scopeTypeArgs.clone(); + varCopy.immutable = this.immutable; + varCopy.deferUniqueIndex = this.deferUniqueIndex; + varCopy.start = this.start; + varCopy.exists = this.exists; + varCopy.writePath = this.writePath; + varCopy.writePathToken = this.writePathToken.clone(); + varCopy.pathOffset = this.pathOffset; + varCopy.pathToken = this.pathToken; + varCopy.metaOffset = this.metaOffset; + varCopy.cellType = this.cellType; + varCopy.valueOffset = this.valueOffset; + varCopy.endOffset = this.endOffset; + varCopy.count = this.count; + varCopy.index = this.index; + varCopy.cellTypeArgs = this.cellTypeArgs.clone(); + + return varCopy; + } + + @Override + public String toString() { + try { + if (this.scopeType == null) { + return ""; + } + + TypeArgument scopeTypeArg = (this.scopeType == null) || (this.scopeType instanceof LayoutEndScope) ? + default: + new TypeArgument(this.scopeType, this.scopeTypeArgs.clone()); + + TypeArgument typeArg = (this.cellType == null) || (this.cellType instanceof LayoutEndScope) ? + default: + new TypeArgument(this.cellType, this.cellTypeArgs.clone()); + + String pathOrIndex = !this.writePath.IsNull ? this.writePath.toString() : String.valueOf(this.index); + return String.format("%1$s[%2$s] : %3$s@%4$s/%5$s", scopeTypeArg.clone(), pathOrIndex, + typeArg.clone(), this.metaOffset, this.valueOffset) + (this.immutable ? " immutable" : ""); + } catch (java.lang.Exception e) { + return ""; + } + } + + /** + * If true, this scope's nested fields cannot be updated individually. + * The entire scope can still be replaced. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool Immutable + boolean getImmutable() + + /** + * For indexed scopes (e.g. Array), the 0-based index into the scope of the next insertion. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int Index + int getIndex() + + /** + * The layout describing the contents of the scope, or null if the scope is unschematized. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DebuggerBrowsable(DebuggerBrowsableState.Never)] public Layout Layout + Layout getLayout() + + /** + * The kind of scope. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DebuggerBrowsable(DebuggerBrowsableState.Never)] public LayoutType ScopeType + LayoutType getScopeType() + + /** + * For types with generic parameters (e.g. , the type parameters. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DebuggerBrowsable(DebuggerBrowsableState.Never)] public TypeArgumentList ScopeTypeArgs + TypeArgumentList getScopeTypeArgs() + + /** + * The full logical type. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DebuggerBrowsable(DebuggerBrowsableState.Never)] public TypeArgument TypeArg + TypeArgument getTypeArg() +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowCursorExtensions.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowCursorExtensions.java new file mode 100644 index 0000000..800162c --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowCursorExtensions.java @@ -0,0 +1,127 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutEndScope; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class RowCursorExtensions { + /** Makes a copy of the current cursor. + + The two cursors will have independent and unconnected lifetimes after cloning. However, + mutations to a can invalidate any active cursors over the same row. + + */ + // TODO: C# TO JAVA CONVERTER: 'ref return' methods are not converted by C# to Java Converter: + // public static ref RowCursor Clone(this in RowCursor src, out RowCursor dest) + // { + // dest = src; + // return ref dest; + // } + + /** + * Returns an equivalent scope that is read-only. + */ + // TODO: C# TO JAVA CONVERTER: 'ref return' methods are not converted by C# to Java Converter: + // public static ref RowCursor AsReadOnly(this in RowCursor src, out RowCursor dest) + // { + // dest = src; + // dest.immutable = true; + // return ref dest; + // } + + // TODO: C# TO JAVA CONVERTER: 'ref return' methods are not converted by C# to Java Converter: + // public static ref RowCursor Find(this ref RowCursor edit, ref RowBuffer row, UtfAnyString path) + // { + // Contract.Requires(!edit.scopeType.IsIndexedScope); + // + // if (!(edit.cellType is LayoutEndScope)) + // { + // while (row.SparseIteratorMoveNext(ref edit)) + // { + // if (path.Equals(row.ReadSparsePath(ref edit))) + // { + // edit.exists = true; + // break; + // } + // } + // } + // + // edit.writePath = path; + // edit.writePathToken = default; + // return ref edit; + // } + + // TODO: C# TO JAVA CONVERTER: 'ref return' methods are not converted by C# to Java Converter: + // public static ref RowCursor Find(this ref RowCursor edit, ref RowBuffer row, in StringToken pathToken) + // { + // Contract.Requires(!edit.scopeType.IsIndexedScope); + // + // if (!(edit.cellType is LayoutEndScope)) + // { + // while (row.SparseIteratorMoveNext(ref edit)) + // { + // if (pathToken.Id == (ulong)edit.pathToken) + // { + // edit.exists = true; + // break; + // } + // } + // } + // + // edit.writePath = pathToken.Path; + // edit.writePathToken = pathToken; + // return ref edit; + // } + public static boolean MoveNext(tangible.RefObject edit, tangible.RefObject row) { + edit.argValue.writePath = null; + edit.argValue.writePathToken = null; + return row.argValue.SparseIteratorMoveNext(edit); + } + + public static boolean MoveNext(tangible.RefObject edit, tangible.RefObject row, + tangible.RefObject childScope) { + if (childScope.argValue.scopeType != null) { + azure.data.cosmos.serialization.hybridrow.RowCursorExtensions.Skip(edit.argValue.clone(), row, childScope); + } + + return azure.data.cosmos.serialization.hybridrow.RowCursorExtensions.MoveNext(edit.argValue.clone(), row); + } + + public static boolean MoveTo(tangible.RefObject edit, tangible.RefObject row, int index) { + checkState(edit.argValue.index <= index); + edit.argValue.writePath = null; + edit.argValue.writePathToken = null; + while (edit.argValue.index < index) { + if (!row.argValue.SparseIteratorMoveNext(edit)) { + return false; + } + } + + return true; + } + + public static void Skip(tangible.RefObject edit, tangible.RefObject row, + tangible.RefObject childScope) { + checkArgument(childScope.argValue.start == edit.argValue.valueOffset); + if (!(childScope.argValue.cellType instanceof LayoutEndScope)) { + while (row.argValue.SparseIteratorMoveNext(childScope)) { + } + } + + if (childScope.argValue.scopeType.IsSizedScope) { + edit.argValue.endOffset = childScope.argValue.metaOffset; + } else { + edit.argValue.endOffset = childScope.argValue.metaOffset + (LayoutCode.SIZE / Byte.SIZE); // Move past the end of scope marker. + } + + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + childScope.argValue = null; + //#endif + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowOptions.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowOptions.java new file mode 100644 index 0000000..66bb768 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/RowOptions.java @@ -0,0 +1,82 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +/** + * Describes the desired behavior when mutating a hybrid row. + */ +public enum RowOptions { + None(0), + + /** + * Overwrite an existing value. + *

+ * An existing value is assumed to exist at the offset provided. The existing value is + * replaced inline. The remainder of the row is resized to accomodate either an increase or decrease + * in required space. + */ + Update(1), + + /** + * Insert a new value. + *

+ * An existing value is assumed NOT to exist at the offset provided. The new value is + * inserted immediately at the offset. The remainder of the row is resized to accomodate either an + * increase or decrease in required space. + */ + Insert(2), + + /** + * Update an existing value or insert a new value, if no value exists. + *

+ * If a value exists, then this operation becomes , otherwise it + * becomes . + */ + Upsert(3), + + /** + * Insert a new value moving existing values to the right. + *

+ * Within an array scope, inserts a new value immediately at the index moving all subsequent + * items to the right. In any other scope behaves the same as . + */ + InsertAt(4), + + /** + * Delete an existing value. + *

+ * If a value exists, then it is removed. The remainder of the row is resized to accomodate + * a decrease in required space. If no value exists this operation is a no-op. + */ + Delete(5); + + public static final int SIZE = java.lang.Integer.SIZE; + private static java.util.HashMap mappings; + private int intValue; + + RowOptions(int value) { + intValue = value; + getMappings().put(value, this); + } + + public int getValue() { + return intValue; + } + + public static RowOptions forValue(int value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (RowOptions.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/SchemaId.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/SchemaId.java new file mode 100644 index 0000000..c930be1 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/SchemaId.java @@ -0,0 +1,127 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +import Newtonsoft.Json.*; + +import static com.google.common.base.Preconditions.checkArgument; + +/** + * The unique identifier for a schema. + * Identifiers must be unique within the scope of the database in which they are used. + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [JsonConverter(typeof(SchemaIdConverter))][DebuggerDisplay("{" + nameof(SchemaId.Id) + "}") +// ][StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct SchemaId : IEquatable +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: [JsonConverter(typeof(SchemaIdConverter))][DebuggerDisplay("{" + nameof(SchemaId.Id) + "}") +// ][StructLayout(LayoutKind.Sequential, Pack = 1)] public readonly struct SchemaId : IEquatable +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: +public final class SchemaId implements IEquatable { + public static final SchemaId Invalid = null; + public static final int Size = (Integer.SIZE / Byte.SIZE); + /** + * The underlying identifier. + */ + private int Id; + + /** + * Initializes a new instance of the struct. + * + * @param id The underlying globally unique identifier of the schema. + */ + public SchemaId() { + } + + public SchemaId(int id) { + this.Id = id; + } + + public int getId() { + return Id; + } + + /** + * overload. + */ + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + return obj instanceof SchemaId && this.equals((SchemaId)obj); + } + + /** + * Returns true if this is the same as . + * + * @param other The value to compare against. + * @return True if the two values are the same. + */ + public boolean equals(SchemaId other) { + return this.getId() == other.getId(); + } + + /** + * overload. + */ + @Override + public int hashCode() { + return (new Integer(this.getId())).hashCode(); + } + + /** + * Operator == overload. + */ + public static boolean opEquals(SchemaId left, SchemaId right) { + return left.equals(right.clone()); + } + + /** + * Operator != overload. + */ + public static boolean opNotEquals(SchemaId left, SchemaId right) { + return !left.equals(right.clone()); + } + + /** + * overload. + */ + @Override + public String toString() { + return String.valueOf(this.getId()); + } + + /** + * Helper class for parsing from JSON. + */ + public static class SchemaIdConverter extends JsonConverter { + @Override + public boolean getCanWrite() { + return true; + } + + @Override + public boolean CanConvert(java.lang.Class objectType) { + return objectType.isAssignableFrom(SchemaId.class); + } + + @Override + public Object ReadJson(JsonReader reader, java.lang.Class objectType, Object existingValue, + JsonSerializer serializer) { + checkArgument(reader.TokenType == JsonToken.Integer); + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'checked' in this context: + //ORIGINAL LINE: return new SchemaId(checked((int)(long)reader.Value)); + return new SchemaId((int)(long)reader.Value); + } + + @Override + public void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer) { + writer.WriteValue((long)((SchemaId)value).getId()); + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/UnixDateTime.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/UnixDateTime.java new file mode 100644 index 0000000..1b6064e --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/UnixDateTime.java @@ -0,0 +1,98 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow; + +/** + * A wall clock time expressed in milliseconds since the Unix Epoch. + *

+ * A is a fixed length value-type providing millisecond + * granularity as a signed offset from the Unix Epoch (midnight, January 1, 1970 UTC). + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [DebuggerDisplay("{" + nameof(UnixDateTime.Milliseconds) + "}")][StructLayout(LayoutKind.Sequential, +// Pack = 1)] public readonly struct UnixDateTime : IEquatable +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: [DebuggerDisplay("{" + nameof(UnixDateTime.Milliseconds) + "}")][StructLayout(LayoutKind.Sequential, +// Pack = 1)] public readonly struct UnixDateTime : IEquatable +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: +public final class UnixDateTime implements IEquatable { + /** + * The unix epoch. + * values are signed values centered on . + * + * This is the same value as default(). + */ + public static final UnixDateTime Epoch = new UnixDateTime(); + /** + * The size (in bytes) of a UnixDateTime. + */ + public static final int Size = (Long.SIZE / Byte.SIZE); + /** + * The number of milliseconds since . + * This value may be negative. + */ + private long Milliseconds; + + /** + * Initializes a new instance of the struct. + * + * @param milliseconds The number of milliseconds since . + */ + public UnixDateTime() { + } + + public UnixDateTime(long milliseconds) { + this.Milliseconds = milliseconds; + } + + public long getMilliseconds() { + return Milliseconds; + } + + /** + * Returns true if this is the same value as . + * + * @param other The value to compare against. + * @return True if the two values are the same. + */ + public boolean equals(UnixDateTime other) { + return this.getMilliseconds() == other.getMilliseconds(); + } + + /** + * overload. + */ + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + return obj instanceof UnixDateTime && this.equals((UnixDateTime)obj); + } + + /** + * overload. + */ + @Override + public int hashCode() { + return (new Long(this.getMilliseconds())).hashCode(); + } + + /** + * Operator == overload. + */ + public static boolean opEquals(UnixDateTime left, UnixDateTime right) { + return left.equals(right.clone()); + } + + /** + * Operator != overload. + */ + public static boolean opNotEquals(UnixDateTime left, UnixDateTime right) { + return !left.equals(right.clone()); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/internal/MurmurHash3.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/internal/MurmurHash3.java new file mode 100644 index 0000000..3ec5b84 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/internal/MurmurHash3.java @@ -0,0 +1,245 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.internal; + +/** + * MurmurHash3 for x64 (Little Endian). + *

Reference: https: //en.wikipedia.org/wiki/MurmurHash

+ *

+ * This implementation provides span-based access for hashing content not available in a + * + *

+ */ +public final class MurmurHash3 { + /** MurmurHash3 128-bit implementation. + @param value The data to hash. + @param seed The seed to initialize with. + @return The 128-bit hash represented as two 64-bit words. + */ + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // public static(ulong low, ulong high) Hash128(string value, (ulong high, ulong low) seed) + // { + // Contract.Requires(value != null); + // int size = Encoding.UTF8.GetMaxByteCount(value.Length); + // Span span = size <= 256 ? stackalloc byte[size] : new byte[size]; + // int len = Encoding.UTF8.GetBytes(value.AsSpan(), span); + // return MurmurHash3.Hash128(span.Slice(0, len), seed); + // } + + /** MurmurHash3 128-bit implementation. + @param value The data to hash. + @param seed The seed to initialize with. + @return The 128-bit hash represented as two 64-bit words. + */ + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // public static(ulong low, ulong high) Hash128(bool value, (ulong high, ulong low) seed) + // { + // // Ensure that a bool is ALWAYS a single byte encoding with 1 for true and 0 for false. + // return MurmurHash3.Hash128((byte)(value ? 1 : 0), seed); + // } + + /** MurmurHash3 128-bit implementation. + @param value The data to hash. + @param seed The seed to initialize with. + @return The 128-bit hash represented as two 64-bit words. + */ + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // public static unsafe(ulong low, ulong high) Hash128(T value, (ulong high, ulong low) seed) where T : + // unmanaged + // { + // ReadOnlySpan span = new ReadOnlySpan(&value, 1); + // return MurmurHash3.Hash128(MemoryMarshal.AsBytes(span), seed); + // } + + /** + * MurmurHash3 128-bit implementation. + * + * @param span The data to hash. + * @param seed The seed to initialize with. + * @return The 128-bit hash represented as two 64-bit words. + */ + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // public static unsafe(ulong low, ulong high) Hash128(ReadOnlySpan span, (ulong high, ulong low) seed) + // { + // Contract.Assert(BitConverter.IsLittleEndian, "Little Endian expected"); + // const ulong c1 = 0x87c37b91114253d5; + // const ulong c2 = 0x4cf5ad432745937f; + // + // (ulong h1, ulong h2) = seed; + // + // // body + // unchecked + // { + // fixed (byte* words = span) + // { + // int position; + // for (position = 0; position < span.Length - 15; position += 16) + // { + // ulong k1 = *(ulong*)(words + position); + // ulong k2 = *(ulong*)(words + position + 8); + // + // // k1, h1 + // k1 *= c1; + // k1 = MurmurHash3.RotateLeft64(k1, 31); + // k1 *= c2; + // + // h1 ^= k1; + // h1 = MurmurHash3.RotateLeft64(h1, 27); + // h1 += h2; + // h1 = (h1 * 5) + 0x52dce729; + // + // // k2, h2 + // k2 *= c2; + // k2 = MurmurHash3.RotateLeft64(k2, 33); + // k2 *= c1; + // + // h2 ^= k2; + // h2 = MurmurHash3.RotateLeft64(h2, 31); + // h2 += h1; + // h2 = (h2 * 5) + 0x38495ab5; + // } + // + // { + // // tail + // ulong k1 = 0; + // ulong k2 = 0; + // + // int n = span.Length & 15; + // if (n >= 15) + // { + // k2 ^= (ulong)words[position + 14] << 48; + // } + // + // if (n >= 14) + // { + // k2 ^= (ulong)words[position + 13] << 40; + // } + // + // if (n >= 13) + // { + // k2 ^= (ulong)words[position + 12] << 32; + // } + // + // if (n >= 12) + // { + // k2 ^= (ulong)words[position + 11] << 24; + // } + // + // if (n >= 11) + // { + // k2 ^= (ulong)words[position + 10] << 16; + // } + // + // if (n >= 10) + // { + // k2 ^= (ulong)words[position + 09] << 8; + // } + // + // if (n >= 9) + // { + // k2 ^= (ulong)words[position + 08] << 0; + // } + // + // k2 *= c2; + // k2 = MurmurHash3.RotateLeft64(k2, 33); + // k2 *= c1; + // h2 ^= k2; + // + // if (n >= 8) + // { + // k1 ^= (ulong)words[position + 7] << 56; + // } + // + // if (n >= 7) + // { + // k1 ^= (ulong)words[position + 6] << 48; + // } + // + // if (n >= 6) + // { + // k1 ^= (ulong)words[position + 5] << 40; + // } + // + // if (n >= 5) + // { + // k1 ^= (ulong)words[position + 4] << 32; + // } + // + // if (n >= 4) + // { + // k1 ^= (ulong)words[position + 3] << 24; + // } + // + // if (n >= 3) + // { + // k1 ^= (ulong)words[position + 2] << 16; + // } + // + // if (n >= 2) + // { + // k1 ^= (ulong)words[position + 1] << 8; + // } + // + // if (n >= 1) + // { + // k1 ^= (ulong)words[position + 0] << 0; + // } + // + // k1 *= c1; + // k1 = MurmurHash3.RotateLeft64(k1, 31); + // k1 *= c2; + // h1 ^= k1; + // } + // } + // + // // finalization + // h1 ^= (ulong)span.Length; + // h2 ^= (ulong)span.Length; + // h1 += h2; + // h2 += h1; + // h1 = MurmurHash3.Mix(h1); + // h2 = MurmurHash3.Mix(h2); + // h1 += h2; + // h2 += h1; + // } + // + // return (h1, h2); + // } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong Mix(ulong h) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong Mix(ulong h) + private static long Mix(long h) { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + //C# TO JAVA CONVERTER WARNING: The right shift operator was replaced by Java's logical right shift + // operator since the left operand was originally of an unsigned type, but you should confirm this + // replacement: + h ^= h >>> 33; + h *= 0xff51afd7ed558ccdL; + //C# TO JAVA CONVERTER WARNING: The right shift operator was replaced by Java's logical right shift + // operator since the left operand was originally of an unsigned type, but you should confirm this + // replacement: + h ^= h >>> 33; + h *= 0xc4ceb9fe1a85ec53L; + //C# TO JAVA CONVERTER WARNING: The right shift operator was replaced by Java's logical right shift + // operator since the left operand was originally of an unsigned type, but you should confirm this replacement: + h ^= h >>> 33; + return h; + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong RotateLeft64(ulong n, int numBits) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong RotateLeft64(ulong n, int numBits) + private static long RotateLeft64(long n, int numBits) { + Contract.Assert(numBits < 64, "numBits < 64"); + //C# TO JAVA CONVERTER WARNING: The right shift operator was replaced by Java's logical right shift operator since the left operand was originally of an unsigned type, but you should confirm this replacement: + return (n << numBits) | (n >>> (64 - numBits)); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/internal/Utf8StringJsonConverter.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/internal/Utf8StringJsonConverter.java new file mode 100644 index 0000000..c13cd4e --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/internal/Utf8StringJsonConverter.java @@ -0,0 +1,34 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.internal; + +import Newtonsoft.Json.*; + +/** + * Helper class for parsing from JSON. + */ +public class Utf8StringJsonConverter extends JsonConverter { + @Override + public boolean getCanWrite() { + return true; + } + + @Override + public boolean CanConvert(java.lang.Class objectType) { + return objectType.isAssignableFrom(Utf8String.class); + } + + @Override + public Object ReadJson(JsonReader reader, java.lang.Class objectType, Object existingValue, + JsonSerializer serializer) { + Contract.Requires(reader.TokenType == JsonToken.String); + return Utf8String.TranscodeUtf16((String)reader.Value); + } + + @Override + public void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer) { + writer.WriteValue(((Utf8String)value).toString()); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/IRowSerializable.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/IRowSerializable.java new file mode 100644 index 0000000..67f3a62 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/IRowSerializable.java @@ -0,0 +1,22 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.io; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.layouts.TypeArgument; + +/** + * A type may implement this interface to support serialization into a HybridRow. + */ +public interface IRowSerializable { + /** + * Writes the current instance into the row. + * + * @param writer A writer for the current row scope. + * @param typeArg The schematized layout type, if a schema is available. + * @return Success if the write is successful, the error code otherwise. + */ + Result Write(tangible.RefObject writer, TypeArgument typeArg); +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowReader.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowReader.java new file mode 100644 index 0000000..0254958 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowReader.java @@ -0,0 +1,1255 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.io; + +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.NullValue; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutColumn; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutNullable; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutUDT; +import azure.data.cosmos.serialization.hybridrow.schemas.StorageKind; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.UUID; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1034 // Nested types should not be visible + + +/** + * A forward-only, streaming, field reader for . + *

+ * A allows the traversal in a streaming, left to right fashion, of + * an entire HybridRow. The row's layout provides decoding for any schematized portion of the row. + * However, unschematized sparse fields are read directly from the sparse segment with or without + * schematization allowing all fields within the row, both known and unknown, to be read. + * + * Modifying a invalidates any reader or child reader associated with it. In + * general 's should not be mutated while being enumerated. + */ +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public ref struct RowReader +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# ref struct: +public final class RowReader { + private int columnIndex; + private ReadOnlySpan columns; + private RowCursor cursor = new RowCursor(); + private RowBuffer row = new RowBuffer(); + private int schematizedCount; + // State that can be checkpointed. + private States state = States.values()[0]; + + /** + * Initializes a new instance of the struct. + * + * @param row The row to be read. + * @param scope The scope whose fields should be enumerated. + *

+ * A instance traverses all of the top-level fields of a given + * scope. If the root scope is provided then all top-level fields in the row are enumerated. Nested + * child instances can be access through the method + * to process nested content. + */ + public RowReader() { + } + + /** + * Initializes a new instance of the struct. + * + * @param row The row to be read. + * @param scope The scope whose fields should be enumerated. + *

+ * A instance traverses all of the top-level fields of a given + * scope. If the root scope is provided then all top-level fields in the row are enumerated. Nested + * child instances can be access through the method + * to process nested content. + */ + public RowReader(tangible.RefObject row) { + this(row, RowCursor.Create(row)); + } + + public RowReader(tangible.RefObject row, final Checkpoint checkpoint) { + this.row = row.argValue.clone(); + this.columns = checkpoint.Cursor.layout.getColumns(); + this.schematizedCount = checkpoint.Cursor.layout.getNumFixed() + checkpoint.Cursor.layout.getNumVariable(); + + this.state = checkpoint.State; + this.cursor = checkpoint.Cursor.clone(); + this.columnIndex = checkpoint.ColumnIndex; + } + + private RowReader(tangible.RefObject row, final RowCursor scope) { + this.cursor = scope.clone(); + this.row = row.argValue.clone(); + this.columns = this.cursor.layout.getColumns(); + this.schematizedCount = this.cursor.layout.getNumFixed() + this.cursor.layout.getNumVariable(); + + this.state = States.None; + this.columnIndex = -1; + } + + /** + * True if field has a value (if positioned on a field, undefined otherwise). + *

+ * If the current field is a Nullable scope, this method return true if the value is not + * null. If the current field is a nullable Null primitive value, this method return true if the value + * is set (even though its values is set to null). + */ + public boolean getHasValue() { + switch (this.state) { + case Schematized: + return true; + case Sparse: + if (this.cursor.cellType instanceof LayoutNullable) { + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + RowCursor nullableScope = this.row.SparseIteratorReadScope(tempRef_cursor, true).clone(); + this.cursor = tempRef_cursor.argValue; + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + tangible.RefObject tempRef_nullableScope = new tangible.RefObject(nullableScope); + boolean tempVar = LayoutNullable.HasValue(tempRef_row, tempRef_nullableScope) == Result.Success; + nullableScope = tempRef_nullableScope.argValue; + this.row = tempRef_row.argValue; + return tempVar; + } + + return true; + default: + return false; + } + } + + /** + * The 0-based index, relative to the start of the scope, of the field (if positioned on a + * field, undefined otherwise). + *

+ * When enumerating a non-indexed scope, this value is always 0 (see ). + */ + public int getIndex() { + switch (this.state) { + case Schematized: + return 0; + case Sparse: + return this.cursor.index; + default: + return 0; + } + } + + /** + * The length of row in bytes. + */ + public int getLength() { + return this.row.getLength(); + } + + /** + * The path, relative to the scope, of the field (if positioned on a field, undefined + * otherwise). + *

+ * When enumerating an indexed scope, this value is always null (see ). + */ + public UtfAnyString getPath() { + switch (this.state) { + case Schematized: + return this.columns[this.columnIndex].Path; + case Sparse: + if (this.cursor.pathOffset == 0) { + return null; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + Utf8Span span = this.row.ReadSparsePath(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Utf8String.CopyFrom(span); + default: + return null; + } + } + + /** + * The path, relative to the scope, of the field (if positioned on a field, undefined + * otherwise). + *

+ * When enumerating an indexed scope, this value is always null (see ). + */ + public Utf8Span getPathSpan() { + switch (this.state) { + case Schematized: + return this.columns[this.columnIndex].Path.Span; + case Sparse: + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + Utf8Span tempVar = this.row.ReadSparsePath(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return tempVar; + default: + return null; + } + } + + /** + * The storage placement of the field (if positioned on a field, undefined otherwise). + */ + public StorageKind getStorage() { + switch (this.state) { + case Schematized: + return this.columns[this.columnIndex].Storage; + case Sparse: + return StorageKind.Sparse; + default: + return null; + } + } + + /** + * The type of the field (if positioned on a field, undefined otherwise). + */ + public LayoutType getType() { + switch (this.state) { + case Schematized: + return this.columns[this.columnIndex].Type; + case Sparse: + return this.cursor.cellType; + default: + return null; + } + } + + /** + * The type arguments of the field (if positioned on a field, undefined otherwise). + */ + public TypeArgumentList getTypeArgs() { + switch (this.state) { + case Schematized: + return this.columns[this.columnIndex].TypeArgs; + case Sparse: + return this.cursor.cellTypeArgs.clone(); + default: + return TypeArgumentList.Empty; + } + } + + /** + * Advances the reader to the next field. + * + * @return True, if there is another field to be read, false otherwise. + */ + public boolean Read() { + switch (this.state) { + case None: { + if (this.cursor.scopeType instanceof LayoutUDT) { + this.state = States.Schematized; + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case States.Schematized + } + + this.state = States.Sparse; + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case States.Sparse + } + + case Schematized: { + this.columnIndex++; + if (this.columnIndex >= this.schematizedCount) { + this.state = States.Sparse; + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case States.Sparse + } + + checkState(this.cursor.scopeType instanceof LayoutUDT); + LayoutColumn col = this.columns[this.columnIndex]; + if (!this.row.ReadBit(this.cursor.start, col.getNullBit().clone())) { + // Skip schematized values if they aren't present. + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case States.Schematized + } + + return true; + } + + case Sparse: { + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + if (!Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(this.cursor.clone(), + tempRef_row)) { + this.row = tempRef_row.argValue; + this.state = States.Done; + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case States.Done + } else { + this.row = tempRef_row.argValue; + } + + return true; + } + + case Done: { + return false; + } + } + + return false; + } + + /** + * Read the current field as a variable length, sequence of bytes. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadBinary(out byte[] value) + public Result ReadBinary(tangible.OutObject value) { + ReadOnlySpan span; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Result r = this.ReadBinary(out ReadOnlySpan span); + Result r = this.ReadBinary(out span); + value.argValue = (r == Result.Success) ? span.ToArray() : + default + return r; + } + + /** + * Read the current field as a variable length, sequence of bytes. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadBinary(out ReadOnlySpan value) + public Result ReadBinary(tangible.OutObject> value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutBinary)) { + value.argValue = null; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseBinary(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = null; + return Result.Failure; + } + } + + /** + * Read the current field as a . + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadBool(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutBoolean)) { + value.argValue = false; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseBool(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = false; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadDateTime(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutDateTime)) { + value.argValue = LocalDateTime.MIN; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseDateTime(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = LocalDateTime.MIN; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadDecimal(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutDecimal)) { + value.argValue = new BigDecimal(0); + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseDecimal(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = new BigDecimal(0); + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 128-bit, IEEE-encoded floating point value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadFloat128(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value.clone()); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutFloat128)) { + value.argValue = null; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseFloat128(tempRef_cursor).clone(); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = null; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 32-bit, IEEE-encoded floating point value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadFloat32(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutFloat32)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseFloat32(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 64-bit, IEEE-encoded floating point value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadFloat64(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutFloat64)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseFloat64(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadGuid(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutGuid)) { + value.argValue = null; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseGuid(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = null; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 16-bit, signed integer. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadInt16(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutInt16)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseInt16(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 32-bit, signed integer. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadInt32(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutInt32)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseInt32(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 64-bit, signed integer. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadInt64(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutInt64)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseInt64(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 8-bit, signed integer. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadInt8(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutInt8)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseInt8(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadMongoDbObjectId(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value.clone()); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutMongoDbObjectId)) { + value.argValue = null; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseMongoDbObjectId(tempRef_cursor).clone(); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = null; + return Result.Failure; + } + } + + /** + * Read the current field as a null. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadNull(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value.clone()); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutNull)) { + value.argValue = null; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseNull(tempRef_cursor).clone(); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = null; + return Result.Failure; + } + } + + /** + * Read the current field as a nested, structured, sparse scope. + *

+ * Child readers can be used to read all sparse scope types including typed and untyped + * objects, arrays, tuples, set, and maps. + * + * Nested child readers are independent of their parent. + */ + public RowReader ReadScope() { + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + RowCursor newScope = this.row.SparseIteratorReadScope(tempRef_cursor, true).clone(); + this.cursor = tempRef_cursor.argValue; + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + return new RowReader(ref this.row, newScope) + this.row = tempRef_row.argValue; + return tempVar; + } + + /** + * Read the current field as a nested, structured, sparse scope. + *

+ * Child readers can be used to read all sparse scope types including typed and untyped + * objects, arrays, tuples, set, and maps. + */ + public Result ReadScope(TContext context, ReaderFunc func) { + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + RowCursor childScope = this.row.SparseIteratorReadScope(tempRef_cursor, true).clone(); + this.cursor = tempRef_cursor.argValue; + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + RowReader nestedReader = new RowReader(tempRef_row, childScope.clone()); + this.row = tempRef_row.argValue; + + tangible.RefObject tempRef_nestedReader = + new tangible.RefObject(nestedReader); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + Result result = func == null ? null : func.Invoke(ref nestedReader, context) ??Result.Success; + nestedReader = tempRef_nestedReader.argValue; + if (result != Result.Success) { + return result; + } + + tangible.RefObject tempRef_row2 = + new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor2 = + new tangible.RefObject(nestedReader.cursor); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(this.cursor.clone(), tempRef_row2, + tempRef_cursor2); + nestedReader.cursor = tempRef_cursor2.argValue; + this.row = tempRef_row2.argValue; + return Result.Success; + } + + /** + * Read the current field as a variable length, UTF8 encoded, string value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadString(tangible.OutObject value) { + Utf8Span span; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = this.ReadString(out span); + value.argValue = (r == Result.Success) ? span.toString() : + default + return r; + } + + /** + * Read the current field as a variable length, UTF8 encoded, string value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadString(tangible.OutObject value) { + Utf8Span span; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = this.ReadString(out span); + value.argValue = (r == Result.Success) ? Utf8String.CopyFrom(span) : + default + return r; + } + + /** + * Read the current field as a variable length, UTF8 encoded, string value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadString(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutUtf8)) { + value.argValue = null; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseString(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = null; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 16-bit, unsigned integer. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadUInt16(out ushort value) + public Result ReadUInt16(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutUInt16)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseUInt16(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 32-bit, unsigned integer. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadUInt32(out uint value) + public Result ReadUInt32(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutUInt32)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseUInt32(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 64-bit, unsigned integer. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadUInt64(out ulong value) + public Result ReadUInt64(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutUInt64)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseUInt64(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length, 8-bit, unsigned integer. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadUInt8(out byte value) + public Result ReadUInt8(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutUInt8)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseUInt8(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a fixed length value. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadUnixDateTime(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value.clone()); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutUnixDateTime)) { + value.argValue = null; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseUnixDateTime(tempRef_cursor).clone(); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = null; + return Result.Failure; + } + } + + /** + * Read the current field as a variable length, 7-bit encoded, signed integer. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + public Result ReadVarInt(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutVarInt)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseVarInt(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + /** + * Read the current field as a variable length, 7-bit encoded, unsigned integer. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadVarUInt(out ulong value) + public Result ReadVarUInt(tangible.OutObject value) { + switch (this.state) { + case Schematized: + return this.ReadPrimitiveValue(value); + case Sparse: + if (!(this.cursor.cellType instanceof LayoutVarUInt)) { + value.argValue = 0; + return Result.TypeMismatch; + } + + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + value.argValue = this.row.ReadSparseVarUInt(tempRef_cursor); + this.cursor = tempRef_cursor.argValue; + return Result.Success; + default: + value.argValue = 0; + return Result.Failure; + } + } + + public Checkpoint SaveCheckpoint() { + return new Checkpoint(this.state, this.columnIndex, this.cursor.clone()); + } + + /** + * Advance a reader to the end of a child reader. The child reader is also advanced to the + * end of its scope. + *

+ *

+ * The reader must not have been advanced since the child reader was created with ReadScope. + * This method can be used when the overload of that takes a + * is not an option, such as when TContext is a ref struct. + */ + public Result SkipScope(tangible.RefObject nestedReader) { + if (nestedReader.argValue.cursor.start != this.cursor.valueOffset) { + return Result.Failure; + } + + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor = + new tangible.RefObject(nestedReader.argValue.cursor); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(this.cursor.clone(), tempRef_row, + tempRef_cursor); + nestedReader.argValue.argValue.cursor = tempRef_cursor.argValue; + this.row = tempRef_row.argValue; + return Result.Success; + } + + public RowReader clone() { + RowReader varCopy = new RowReader(); + + varCopy.schematizedCount = this.schematizedCount; + varCopy.columns = this.columns; + varCopy.row = this.row.clone(); + varCopy.state = this.state; + varCopy.columnIndex = this.columnIndex; + varCopy.cursor = this.cursor.clone(); + + return varCopy; + } + + /** + * Read a generic schematized field value via the scope's layout. + * The expected type of the field. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + private Result ReadPrimitiveValue(tangible.OutObject value) { + LayoutColumn col = this.columns[this.columnIndex]; + LayoutType t = this.columns[this.columnIndex].Type; + if (!(t instanceof LayoutType)) { + value.argValue = null; + return Result.TypeMismatch; + } + + switch (col == null ? null : col.getStorage()) { + case Fixed: + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + Result tempVar = t.>TypeAs().ReadFixed(tempRef_row, tempRef_cursor, col, value); + this.cursor = tempRef_cursor.argValue; + this.row = tempRef_row.argValue; + return tempVar; + case Variable: + tangible.RefObject tempRef_row2 = new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor2 = new tangible.RefObject(this.cursor); + Result tempVar2 = t.>TypeAs().ReadVariable(tempRef_row2, tempRef_cursor2, col, value); + this.cursor = tempRef_cursor2.argValue; + this.row = tempRef_row2.argValue; + return tempVar2; + default: + Contract.Assert(false); + value.argValue = null; + return Result.Failure; + } + } + + /** + * Read a generic schematized field value via the scope's layout. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + private Result ReadPrimitiveValue(tangible.OutObject value) { + LayoutColumn col = this.columns[this.columnIndex]; + LayoutType t = this.columns[this.columnIndex].Type; + if (!(t instanceof ILayoutUtf8SpanReadable)) { + value.argValue = null; + return Result.TypeMismatch; + } + + switch (col == null ? null : col.getStorage()) { + case Fixed: + tangible.RefObject tempRef_row = new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor = new tangible.RefObject(this.cursor); + Result tempVar = t.TypeAs().ReadFixed(tempRef_row, tempRef_cursor, col, value); + this.cursor = tempRef_cursor.argValue; + this.row = tempRef_row.argValue; + return tempVar; + case Variable: + tangible.RefObject tempRef_row2 = new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor2 = new tangible.RefObject(this.cursor); + Result tempVar2 = t.TypeAs().ReadVariable(tempRef_row2, tempRef_cursor2, col, value); + this.cursor = tempRef_cursor2.argValue; + this.row = tempRef_row2.argValue; + return tempVar2; + default: + Contract.Assert(false); + value.argValue = null; + return Result.Failure; + } + } + + /** + * Read a generic schematized field value via the scope's layout. + * The sub-element type of the field. + * + * @param value On success, receives the value, undefined otherwise. + * @return Success if the read is successful, an error code otherwise. + */ + private Result ReadPrimitiveValue(tangible.OutObject> value) { + LayoutColumn col = this.columns[this.columnIndex]; + LayoutType t = this.columns[this.columnIndex].Type; + if (!(t instanceof ILayoutSpanReadable)) { + value.argValue = null; + return Result.TypeMismatch; + } + + switch (col == null ? null : col.getStorage()) { + case Fixed: + tangible.RefObject tempRef_row = new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor = new tangible.RefObject(this.cursor); + Result tempVar = t.>TypeAs().ReadFixed(tempRef_row, tempRef_cursor, col, value); + this.cursor = tempRef_cursor.argValue; + this.row = tempRef_row.argValue; + return tempVar; + case Variable: + tangible.RefObject tempRef_row2 = new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor2 = new tangible.RefObject(this.cursor); + Result tempVar2 = t.>TypeAs().ReadVariable(tempRef_row2, tempRef_cursor2, col, value); + this.cursor = tempRef_cursor2.argValue; + this.row = tempRef_row2.argValue; + return tempVar2; + default: + Contract.Assert(false); + value.argValue = null; + return Result.Failure; + } + } + + /** + * The current traversal state of the reader. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: internal enum States : byte + public enum States { + /** + * The reader has not be started yet. + */ + None, + + /** + * Enumerating schematized fields (fixed and variable) from left to right. + */ + Schematized, + + /** + * Enumerating top-level fields of the current scope. + */ + Sparse, + + /** + * The reader has completed the scope. + */ + Done; + + public static final int SIZE = java.lang.Byte.SIZE; + + public byte getValue() { + return this.ordinal(); + } + + public static States forValue(byte value) { + return values()[value]; + } + } + + /** + * A function to reader content from a . + * The type of the context value passed by the caller. + * + * @param reader A forward-only cursor for writing content. + * @param context A context value provided by the caller. + * @return The result. + */ + @FunctionalInterface + public interface ReaderFunc { + Result invoke(tangible.RefObject reader, TContext context); + } + + /** + * An encapsulation of the current state of a that can be used to + * recreate the in the same logical position. + */ + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ from the original: + //ORIGINAL LINE: public readonly struct Checkpoint + //C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: + public final static class Checkpoint { + public int ColumnIndex; + public RowCursor Cursor = new RowCursor(); + public States State = States.values()[0]; + + public Checkpoint() { + } + + public Checkpoint(States state, int columnIndex, RowCursor cursor) { + this.State = state; + this.ColumnIndex = columnIndex; + this.Cursor = cursor.clone(); + } + + public Checkpoint clone() { + Checkpoint varCopy = new Checkpoint(); + + varCopy.State = this.State; + varCopy.ColumnIndex = this.ColumnIndex; + varCopy.Cursor = this.Cursor.clone(); + + return varCopy; + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowReaderExtensions.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowReaderExtensions.java new file mode 100644 index 0000000..be4a64a --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowReaderExtensions.java @@ -0,0 +1,98 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.io; + +import azure.data.cosmos.serialization.hybridrow.Result; + +import java.util.ArrayList; + +public final class RowReaderExtensions { + /** + * Read the current field as a nested, structured, sparse scope containing a linear collection of zero or more + * items. + * The type of the items within the collection. + * + * @param reader A forward-only cursor for reading the collection. + * @param deserializer A function that reads one item from the collection. + * @param list On success, the collection of materialized items. + * @return The result. + */ + public static Result ReadList(tangible.RefObject reader, DeserializerFunc deserializer, + tangible.OutObject> list) { + // Pass the context as a struct by value to avoid allocations. + ListContext ctx = new ListContext(); + ctx.List = new ArrayList(); + ctx.Deserializer = + (tangible.RefObject reader.argValue, tangible.OutObject item) -> deserializer.invoke(reader.argValue.clone(), item); + + // All lambda's here are static. + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + Result r = reader.argValue.ReadScope(ctx.clone(), (ref RowReader arrayReader, ListContext ctx1) -> + { + while (arrayReader.Read()) { + Result r2 = arrayReader.ReadScope(ctx1.clone(), (ref RowReader itemReader, ListContext ctx2) -> + { + tangible.RefObject tempRef_itemReader = new tangible.RefObject(itemReader); + TItem op; + tangible.OutObject tempOut_op = new tangible.OutObject(); + Result r3 = ctx2.Deserializer.invoke(tempRef_itemReader, tempOut_op); + op = tempOut_op.argValue; + itemReader = tempRef_itemReader.argValue; + if (r3 != Result.Success) { + return r3; + } + + ctx2.List.add(op); + return Result.Success; + }); + + if (r2 != Result.Success) { + return r2; + } + } + + return Result.Success; + }); + + if (r != Result.Success) { + list.argValue = null; + return r; + } + + list.argValue = ctx.List; + return Result.Success; + } + + /** + * A function to read content from a . + * The type of the item to read. + * + * @param reader A forward-only cursor for reading the item. + * @param item On success, the item read. + * @return The result. + */ + @FunctionalInterface + public interface DeserializerFunc { + Result invoke(tangible.RefObject reader, tangible.OutObject item); + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: private struct ListContext + private final static class ListContext { + public DeserializerFunc Deserializer; + public ArrayList List; + + public ListContext clone() { + ListContext varCopy = new ListContext(); + + varCopy.List = this.List; + varCopy.Deserializer = this.Deserializer; + + return varCopy; + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowWriter.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowWriter.java new file mode 100644 index 0000000..6825088 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/io/RowWriter.java @@ -0,0 +1,1133 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.io; + +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.NullValue; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.UUID; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public ref struct RowWriter +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# ref struct: +public final class RowWriter { + private RowCursor cursor = new RowCursor(); + private RowBuffer row = new RowBuffer(); + + /** + * Initializes a new instance of the struct. + * + * @param row The row to be read. + * @param scope The scope into which items should be written. + *

+ * A instance writes the fields of a given scope from left to right + * in a forward only manner. If the root scope is provided then all top-level fields in the row can be + * written. + */ + public RowWriter() { + } + + private RowWriter(tangible.RefObject row, tangible.RefObject scope) { + this.row = row.argValue.clone(); + this.cursor = scope.argValue.clone(); + } + + /** + * The active layout of the current writer scope. + */ + public Layout getLayout() { + return this.cursor.layout; + } + + /** + * The length of row in bytes. + */ + public int getLength() { + return this.row.getLength(); + } + + /** + * The resolver for UDTs. + */ + public LayoutResolver getResolver() { + return this.row.getResolver(); + } + + /** + * Write a field as a variable length, sequence of bytes. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteBinary(UtfAnyString path, byte[] value) + public Result WriteBinary(UtfAnyString path, byte[] value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WritePrimitive(path, value, LayoutType.Binary, (ref RowWriter w, byte[] v) => w + // .row.WriteSparseBinary(ref w.cursor, v, UpdateOptions.Upsert)); + return this.WritePrimitive(path, value, LayoutType.Binary, + (ref RowWriter w, byte[] v) -> w.row.WriteSparseBinary(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a variable length, sequence of bytes. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteBinary(UtfAnyString path, ReadOnlySpan value) + public Result WriteBinary(UtfAnyString path, ReadOnlySpan value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WritePrimitive(path, value, LayoutType.Binary, (ref RowWriter w, + // ReadOnlySpan v) => w.row.WriteSparseBinary(ref w.cursor, v, UpdateOptions.Upsert)); + return this.WritePrimitive(path, value, LayoutType.Binary, + (ref RowWriter w, ReadOnlySpan v) -> w.row.WriteSparseBinary(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a variable length, sequence of bytes. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteBinary(UtfAnyString path, ReadOnlySequence value) + public Result WriteBinary(UtfAnyString path, ReadOnlySequence value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WritePrimitive(path, value, LayoutType.Binary, (ref RowWriter w, + // ReadOnlySequence v) => w.row.WriteSparseBinary(ref w.cursor, v, UpdateOptions.Upsert)); + return this.WritePrimitive(path, value, LayoutType.Binary, + (ref RowWriter w, ReadOnlySequence v) -> w.row.WriteSparseBinary(ref w.cursor, v, + UpdateOptions.Upsert)); + } + + /** + * Write a field as a . + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteBool(UtfAnyString path, boolean value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Boolean, + (ref RowWriter w, boolean v) -> w.row.WriteSparseBool(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write an entire row in a streaming left-to-right way. + * The type of the context value to pass to . + * + * @param row The row to write. + * @param context A context value to pass to . + * @param func A function to write the entire row. + * @return Success if the write is successful, an error code otherwise. + */ + public static Result WriteBuffer(tangible.RefObject row, TContext context, + WriterFunc func) { + RowCursor scope = RowCursor.Create(row); + tangible.RefObject tempRef_scope = + new tangible.RefObject(scope); + RowWriter writer = new RowWriter(row, tempRef_scope); + scope = tempRef_scope.argValue; + TypeArgument typeArg = new TypeArgument(LayoutType.UDT, + new TypeArgumentList(scope.layout.getSchemaId().clone())); + tangible.RefObject tempRef_writer = + new tangible.RefObject(writer); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + Result result = func(ref writer, typeArg, context); + writer = tempRef_writer.argValue; + row.argValue = writer.row.clone(); + return result; + } + + /** + * Write a field as a fixed length value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteDateTime(UtfAnyString path, LocalDateTime value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.DateTime, + (ref RowWriter w, LocalDateTime v) -> w.row.WriteSparseDateTime(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteDecimal(UtfAnyString path, BigDecimal value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Decimal, + (ref RowWriter w, BigDecimal v) -> w.row.WriteSparseDecimal(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 128-bit, IEEE-encoded floating point value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteFloat128(UtfAnyString path, Float128 value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value.clone(), LayoutType.Float128, + (ref RowWriter w, Float128 v) -> w.row.WriteSparseFloat128(ref w.cursor, v.clone(), UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 32-bit, IEEE-encoded floating point value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteFloat32(UtfAnyString path, float value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Float32, + (ref RowWriter w, float v) -> w.row.WriteSparseFloat32(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 64-bit, IEEE-encoded floating point value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteFloat64(UtfAnyString path, double value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Float64, + (ref RowWriter w, double v) -> w.row.WriteSparseFloat64(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteGuid(UtfAnyString path, UUID value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Guid, + (ref RowWriter w, UUID v) -> w.row.WriteSparseGuid(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 16-bit, signed integer. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteInt16(UtfAnyString path, short value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Int16, + (ref RowWriter w, short v) -> w.row.WriteSparseInt16(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 32-bit, signed integer. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteInt32(UtfAnyString path, int value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Int32, + (ref RowWriter w, int v) -> w.row.WriteSparseInt32(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 64-bit, signed integer. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteInt64(UtfAnyString path, long value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Int64, + (ref RowWriter w, long v) -> w.row.WriteSparseInt64(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 8-bit, signed integer. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteInt8(UtfAnyString path, byte value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Int8, + (ref RowWriter w, byte v) -> w.row.WriteSparseInt8(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteMongoDbObjectId(UtfAnyString path, MongoDbObjectId value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value.clone(), LayoutType.MongoDbObjectId, (ref RowWriter w, + MongoDbObjectId v) -> w.row.WriteSparseMongoDbObjectId(ref w.cursor, v.clone(), UpdateOptions.Upsert)); + } + + /** + * Write a field as a . + * + * @param path The scope-relative path of the field to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteNull(UtfAnyString path) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, NullValue.Default, LayoutType.Null, + (ref RowWriter w, NullValue v) -> w.row.WriteSparseNull(ref w.cursor, v.clone(), UpdateOptions.Upsert)); + } + + public Result WriteScope(UtfAnyString path, TypeArgument typeArg, TContext context, + WriterFunc func) { + LayoutType type = typeArg.getType(); + Result result = this.PrepareSparseWrite(path, typeArg.clone()); + if (result != Result.Success) { + return result; + } + + RowCursor nestedScope = new RowCursor(); + switch (type) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutObject scopeType: + case LayoutObject + scopeType: + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope = + new tangible.OutObject(); + this.row.WriteSparseObject(tempRef_cursor, scopeType, UpdateOptions.Upsert, tempOut_nestedScope); + nestedScope = tempOut_nestedScope.argValue; + this.cursor = tempRef_cursor.argValue; + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutArray scopeType: + case LayoutArray + scopeType: + tangible.RefObject tempRef_cursor2 = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope2 = + new tangible.OutObject(); + this.row.WriteSparseArray(tempRef_cursor2, scopeType, UpdateOptions.Upsert, tempOut_nestedScope2); + nestedScope = tempOut_nestedScope2.argValue; + this.cursor = tempRef_cursor2.argValue; + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedArray scopeType: + case LayoutTypedArray + scopeType: + tangible.RefObject tempRef_cursor3 = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope3 = + new tangible.OutObject(); + this.row.WriteTypedArray(tempRef_cursor3, scopeType, typeArg.getTypeArgs().clone(), + UpdateOptions.Upsert, tempOut_nestedScope3); + nestedScope = tempOut_nestedScope3.argValue; + this.cursor = tempRef_cursor3.argValue; + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTuple scopeType: + case LayoutTuple + scopeType: + tangible.RefObject tempRef_cursor4 = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope4 = + new tangible.OutObject(); + this.row.WriteSparseTuple(tempRef_cursor4, scopeType, typeArg.getTypeArgs().clone(), + UpdateOptions.Upsert, tempOut_nestedScope4); + nestedScope = tempOut_nestedScope4.argValue; + this.cursor = tempRef_cursor4.argValue; + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedTuple scopeType: + case LayoutTypedTuple + scopeType: + tangible.RefObject tempRef_cursor5 = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope5 = + new tangible.OutObject(); + this.row.WriteTypedTuple(tempRef_cursor5, scopeType, typeArg.getTypeArgs().clone(), + UpdateOptions.Upsert, tempOut_nestedScope5); + nestedScope = tempOut_nestedScope5.argValue; + this.cursor = tempRef_cursor5.argValue; + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTagged scopeType: + case LayoutTagged + scopeType: + tangible.RefObject tempRef_cursor6 = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope6 = + new tangible.OutObject(); + this.row.WriteTypedTuple(tempRef_cursor6, scopeType, typeArg.getTypeArgs().clone(), + UpdateOptions.Upsert, tempOut_nestedScope6); + nestedScope = tempOut_nestedScope6.argValue; + this.cursor = tempRef_cursor6.argValue; + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTagged2 scopeType: + case LayoutTagged2 + scopeType: + tangible.RefObject tempRef_cursor7 = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope7 = + new tangible.OutObject(); + this.row.WriteTypedTuple(tempRef_cursor7, scopeType, typeArg.getTypeArgs().clone(), + UpdateOptions.Upsert, tempOut_nestedScope7); + nestedScope = tempOut_nestedScope7.argValue; + this.cursor = tempRef_cursor7.argValue; + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutNullable scopeType: + case LayoutNullable + scopeType: + tangible.RefObject tempRef_cursor8 = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope8 = + new tangible.OutObject(); + this.row.WriteNullable(tempRef_cursor8, scopeType, typeArg.getTypeArgs().clone(), + UpdateOptions.Upsert, func != null, tempOut_nestedScope8); + nestedScope = tempOut_nestedScope8.argValue; + this.cursor = tempRef_cursor8.argValue; + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutUDT scopeType: + case LayoutUDT + scopeType: + Layout udt = this.row.getResolver().Resolve(typeArg.getTypeArgs().getSchemaId().clone()); + tangible.RefObject tempRef_cursor9 = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope9 = + new tangible.OutObject(); + this.row.WriteSparseUDT(tempRef_cursor9, scopeType, udt, UpdateOptions.Upsert, tempOut_nestedScope9); + nestedScope = tempOut_nestedScope9.argValue; + this.cursor = tempRef_cursor9.argValue; + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedSet scopeType: + case LayoutTypedSet + scopeType: + tangible.RefObject tempRef_cursor10 = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope10 = + new tangible.OutObject(); + this.row.WriteTypedSet(tempRef_cursor10, scopeType, typeArg.getTypeArgs().clone(), + UpdateOptions.Upsert, tempOut_nestedScope10); + nestedScope = tempOut_nestedScope10.argValue; + this.cursor = tempRef_cursor10.argValue; + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case LayoutTypedMap scopeType: + case LayoutTypedMap + scopeType: + tangible.RefObject tempRef_cursor11 = + new tangible.RefObject(this.cursor); + tangible.OutObject tempOut_nestedScope11 = + new tangible.OutObject(); + this.row.WriteTypedMap(tempRef_cursor11, scopeType, typeArg.getTypeArgs().clone(), + UpdateOptions.Upsert, tempOut_nestedScope11); + nestedScope = tempOut_nestedScope11.argValue; + this.cursor = tempRef_cursor11.argValue; + + break; + + default: + return Result.Failure; + } + + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + tangible.RefObject tempRef_nestedScope = + new tangible.RefObject(nestedScope); + RowWriter nestedWriter = new RowWriter(tempRef_row, tempRef_nestedScope); + nestedScope = tempRef_nestedScope.argValue; + this.row = tempRef_row.argValue; + tangible.RefObject tempRef_nestedWriter = + new tangible.RefObject(nestedWriter); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + result = func == null ? null : func.Invoke(ref nestedWriter, typeArg, context) ??Result.Success; + nestedWriter = tempRef_nestedWriter.argValue; + this.row = nestedWriter.row.clone(); + nestedScope.count = nestedWriter.cursor.count; + + if (result != Result.Success) { + // TODO: what about unique violations here? + return result; + } + + if (type instanceof LayoutUniqueScope) { + tangible.RefObject tempRef_nestedScope2 = + new tangible.RefObject(nestedScope); + result = this.row.TypedCollectionUniqueIndexRebuild(tempRef_nestedScope2); + nestedScope = tempRef_nestedScope2.argValue; + if (result != Result.Success) { + // TODO: If the index rebuild fails then the row is corrupted. Should we automatically clean up here? + return result; + } + } + + tangible.RefObject tempRef_row2 = + new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor12 = + new tangible.RefObject(nestedWriter.cursor); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(this.cursor.clone(), tempRef_row2 + , tempRef_cursor12); + nestedWriter.cursor = tempRef_cursor12.argValue; + this.row = tempRef_row2.argValue; + return Result.Success; + } + + /** + * Write a field as a variable length, UTF8 encoded, string value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteString(UtfAnyString path, String value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Utf8, + (ref RowWriter w, String v) -> w.row.WriteSparseString(ref w.cursor, Utf8Span.TranscodeUtf16(v), + UpdateOptions.Upsert)); + } + + /** + * Write a field as a variable length, UTF8 encoded, string value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteString(UtfAnyString path, Utf8Span value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.Utf8, + (ref RowWriter w, Utf8Span v) -> w.row.WriteSparseString(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 16-bit, unsigned integer. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteUInt16(UtfAnyString path, ushort value) + public Result WriteUInt16(UtfAnyString path, short value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WritePrimitive(path, value, LayoutType.UInt16, (ref RowWriter w, ushort v) => w + // .row.WriteSparseUInt16(ref w.cursor, v, UpdateOptions.Upsert)); + return this.WritePrimitive(path, value, LayoutType.UInt16, + (ref RowWriter w, short v) -> w.row.WriteSparseUInt16(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 32-bit, unsigned integer. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteUInt32(UtfAnyString path, uint value) + public Result WriteUInt32(UtfAnyString path, int value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WritePrimitive(path, value, LayoutType.UInt32, (ref RowWriter w, uint v) => w + // .row.WriteSparseUInt32(ref w.cursor, v, UpdateOptions.Upsert)); + return this.WritePrimitive(path, value, LayoutType.UInt32, + (ref RowWriter w, int v) -> w.row.WriteSparseUInt32(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 64-bit, unsigned integer. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteUInt64(UtfAnyString path, ulong value) + public Result WriteUInt64(UtfAnyString path, long value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WritePrimitive(path, value, LayoutType.UInt64, (ref RowWriter w, ulong v) => w + // .row.WriteSparseUInt64(ref w.cursor, v, UpdateOptions.Upsert)); + return this.WritePrimitive(path, value, LayoutType.UInt64, + (ref RowWriter w, long v) -> w.row.WriteSparseUInt64(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length, 8-bit, unsigned integer. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteUInt8(UtfAnyString path, byte value) + public Result WriteUInt8(UtfAnyString path, byte value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WritePrimitive(path, value, LayoutType.UInt8, (ref RowWriter w, byte v) => w.row + // .WriteSparseUInt8(ref w.cursor, v, UpdateOptions.Upsert)); + return this.WritePrimitive(path, value, LayoutType.UInt8, + (ref RowWriter w, byte v) -> w.row.WriteSparseUInt8(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a fixed length value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteUnixDateTime(UtfAnyString path, UnixDateTime value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value.clone(), LayoutType.UnixDateTime, + (ref RowWriter w, UnixDateTime v) -> w.row.WriteSparseUnixDateTime(ref w.cursor, v.clone(), + UpdateOptions.Upsert)); + } + + /** + * Write a field as a variable length, 7-bit encoded, signed integer. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + public Result WriteVarInt(UtfAnyString path, long value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + return this.WritePrimitive(path, value, LayoutType.VarInt, + (ref RowWriter w, long v) -> w.row.WriteSparseVarInt(ref w.cursor, v, UpdateOptions.Upsert)); + } + + /** + * Write a field as a variable length, 7-bit encoded, unsigned integer. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteVarUInt(UtfAnyString path, ulong value) + public Result WriteVarUInt(UtfAnyString path, long value) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WritePrimitive(path, value, LayoutType.VarUInt, (ref RowWriter w, ulong v) => w + // .row.WriteSparseVarUInt(ref w.cursor, v, UpdateOptions.Upsert)); + return this.WritePrimitive(path, value, LayoutType.VarUInt, + (ref RowWriter w, long v) -> w.row.WriteSparseVarUInt(ref w.cursor, v, UpdateOptions.Upsert)); + } + + public RowWriter clone() { + RowWriter varCopy = new RowWriter(); + + varCopy.row = this.row.clone(); + varCopy.cursor = this.cursor.clone(); + + return varCopy; + } + + /** + * Helper for preparing the write of a sparse field. + * + * @param path The path identifying the field to write. + * @param typeArg The (optional) type constraints. + * @return Success if the write is permitted, the error code otherwise. + */ + private Result PrepareSparseWrite(UtfAnyString path, TypeArgument typeArg) { + if (this.cursor.scopeType.IsFixedArity && !(this.cursor.scopeType instanceof LayoutNullable)) { + if ((this.cursor.index < this.cursor.scopeTypeArgs.getCount()) && !typeArg.equals(this.cursor.scopeTypeArgs.get(this.cursor.index).clone())) { + return Result.TypeConstraint; + } + } else if (this.cursor.scopeType instanceof LayoutTypedMap) { + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + if (!typeArg.equals(this.cursor.scopeType.TypeAs().FieldType(tempRef_cursor).clone())) { + this.cursor = tempRef_cursor.argValue; + return Result.TypeConstraint; + } else { + this.cursor = tempRef_cursor.argValue; + } + } else if (this.cursor.scopeType.IsTypedScope && !typeArg.equals(this.cursor.scopeTypeArgs.get(0).clone())) { + return Result.TypeConstraint; + } + + this.cursor.writePath = path; + return Result.Success; + } + + /** + * Helper for writing a primitive value. + * The type of layout type. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @param type The layout type. + * @param sparse The access method for . + * @return Success if the write is successful, an error code otherwise. + */ + private & ILayoutUtf8SpanWritable> Result WritePrimitive(UtfAnyString path, Utf8Span value, TLayoutType type, AccessUtf8SpanMethod sparse) { + Result result = Result.NotFound; + if (this.cursor.scopeType instanceof LayoutUDT) { + result = this.WriteSchematizedValue(path, value); + } + + if (result == Result.NotFound) { + // Write sparse value. + result = this.PrepareSparseWrite(path, type.getTypeArg().clone()); + if (result != Result.Success) { + return result; + } + + tangible.RefObject tempRef_this = + new tangible.RefObject(this); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + sparse(ref this, value) + this = tempRef_this.argValue; + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(this.cursor.clone(), + tempRef_row); + this.row = tempRef_row.argValue; + } + + return result; + } + + /** + * Helper for writing a primitive value. + * The type of layout type. + * The sub-element type of the field. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @param type The layout type. + * @param sparse The access method for . + * @return Success if the write is successful, an error code otherwise. + */ + private & ILayoutSpanWritable, TElement> Result WritePrimitive(UtfAnyString path, ReadOnlySpan value, TLayoutType type, AccessReadOnlySpanMethod sparse) { + Result result = Result.NotFound; + if (this.cursor.scopeType instanceof LayoutUDT) { + result = this.WriteSchematizedValue(path, value); + } + + if (result == Result.NotFound) { + // Write sparse value. + result = this.PrepareSparseWrite(path, type.getTypeArg().clone()); + if (result != Result.Success) { + return result; + } + + tangible.RefObject tempRef_this = + new tangible.RefObject(this); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + sparse(ref this, value) + this = tempRef_this.argValue; + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(this.cursor.clone(), + tempRef_row); + this.row = tempRef_row.argValue; + } + + return result; + } + + /** + * Helper for writing a primitive value. + * The type of layout type. + * The sub-element type of the field. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @param type The layout type. + * @param sparse The access method for . + * @return Success if the write is successful, an error code otherwise. + */ + private & ILayoutSequenceWritable, TElement> Result WritePrimitive(UtfAnyString path, ReadOnlySequence value, TLayoutType type, AccessMethod> sparse) { + Result result = Result.NotFound; + if (this.cursor.scopeType instanceof LayoutUDT) { + result = this.WriteSchematizedValue(path, value); + } + + if (result == Result.NotFound) { + // Write sparse value. + result = this.PrepareSparseWrite(path, type.getTypeArg().clone()); + if (result != Result.Success) { + return result; + } + + tangible.RefObject tempRef_this = + new tangible.RefObject(this); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + sparse(ref this, value) + this = tempRef_this.argValue; + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(this.cursor.clone(), + tempRef_row); + this.row = tempRef_row.argValue; + } + + return result; + } + + /** + * Helper for writing a primitive value. + * The type of the primitive value. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @param type The layout type. + * @param sparse The access method for . + * @return Success if the write is successful, an error code otherwise. + */ + private Result WritePrimitive(UtfAnyString path, TValue value, LayoutType type, + AccessMethod sparse) { + Result result = Result.NotFound; + if (this.cursor.scopeType instanceof LayoutUDT) { + result = this.WriteSchematizedValue(path, value); + } + + if (result == Result.NotFound) { + // Write sparse value. + + result = this.PrepareSparseWrite(path, type.getTypeArg().clone()); + if (result != Result.Success) { + return result; + } + + tangible.RefObject tempRef_this = + new tangible.RefObject(this); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + sparse(ref this, value) + this = tempRef_this.argValue; + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(this.cursor.clone(), + tempRef_row); + this.row = tempRef_row.argValue; + } + + return result; + } + + /** + * Write a generic schematized field value via the scope's layout. + * The expected type of the field. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + private Result WriteSchematizedValue(UtfAnyString path, TValue value) { + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + if (!this.cursor.layout.TryFind(path, out col)) { + return Result.NotFound; + } + + boolean tempVar = col.Type instanceof LayoutType; + LayoutType t = tempVar ? (LayoutType)col.Type : null; + if (!(tempVar)) { + return Result.NotFound; + } + + switch (col.Storage) { + case StorageKind.Fixed: + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + Result tempVar2 = t.WriteFixed(ref this.row, ref this.cursor, col, value) + this.row = tempRef_row.argValue; + return tempVar2; + + case StorageKind.Variable: + tangible.RefObject tempRef_row2 = + new tangible.RefObject(this.row); + Result tempVar3 = t.WriteVariable(ref this.row, ref this.cursor, col, value) + this.row = tempRef_row2.argValue; + return tempVar3; + + default: + return Result.NotFound; + } + + return Result.NotFound; + } + + /** + * Write a generic schematized field value via the scope's layout. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + private Result WriteSchematizedValue(UtfAnyString path, Utf8Span value) { + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + if (!this.cursor.layout.TryFind(path, out col)) { + return Result.NotFound; + } + + LayoutType t = col.Type; + if (!(t instanceof ILayoutUtf8SpanWritable)) { + return Result.NotFound; + } + + switch (col.Storage) { + case StorageKind.Fixed: + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor = + new tangible.RefObject(this.cursor); + Result tempVar = t.TypeAs().WriteFixed(tempRef_row, tempRef_cursor, col, + value); + this.cursor = tempRef_cursor.argValue; + this.row = tempRef_row.argValue; + return tempVar; + case StorageKind.Variable: + tangible.RefObject tempRef_row2 = + new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor2 = + new tangible.RefObject(this.cursor); + Result tempVar2 = t.TypeAs().WriteVariable(tempRef_row2, tempRef_cursor2, + col, value); + this.cursor = tempRef_cursor2.argValue; + this.row = tempRef_row2.argValue; + return tempVar2; + default: + return Result.NotFound; + } + } + + /** + * Write a generic schematized field value via the scope's layout. + * The sub-element type of the field. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + private Result WriteSchematizedValue(UtfAnyString path, ReadOnlySpan value) { + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + if (!this.cursor.layout.TryFind(path, out col)) { + return Result.NotFound; + } + + LayoutType t = col.Type; + if (!(t instanceof ILayoutSpanWritable)) { + return Result.NotFound; + } + + switch (col.Storage) { + case StorageKind.Fixed: + tangible.RefObject tempRef_row = new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor = new tangible.RefObject(this.cursor); + Result tempVar = t.>TypeAs().WriteFixed(tempRef_row, tempRef_cursor, col, value); + this.cursor = tempRef_cursor.argValue; + this.row = tempRef_row.argValue; + return tempVar; + case StorageKind.Variable: + tangible.RefObject tempRef_row2 = new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor2 = new tangible.RefObject(this.cursor); + Result tempVar2 = t.>TypeAs().WriteVariable(tempRef_row2, tempRef_cursor2, col, value); + this.cursor = tempRef_cursor2.argValue; + this.row = tempRef_row2.argValue; + return tempVar2; + default: + return Result.NotFound; + } + } + + /** + * Write a generic schematized field value via the scope's layout. + * The sub-element type of the field. + * + * @param path The scope-relative path of the field to write. + * @param value The value to write. + * @return Success if the write is successful, an error code otherwise. + */ + private Result WriteSchematizedValue(UtfAnyString path, ReadOnlySequence value) { + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + if (!this.cursor.layout.TryFind(path, out col)) { + return Result.NotFound; + } + + LayoutType t = col.Type; + if (!(t instanceof ILayoutSequenceWritable)) { + return Result.NotFound; + } + + switch (col.Storage) { + case StorageKind.Fixed: + tangible.RefObject tempRef_row = new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor = new tangible.RefObject(this.cursor); + Result tempVar = t.>TypeAs().WriteFixed(tempRef_row, tempRef_cursor, col, value); + this.cursor = tempRef_cursor.argValue; + this.row = tempRef_row.argValue; + return tempVar; + case StorageKind.Variable: + tangible.RefObject tempRef_row2 = new tangible.RefObject(this.row); + tangible.RefObject tempRef_cursor2 = new tangible.RefObject(this.cursor); + Result tempVar2 = t.>TypeAs().WriteVariable(tempRef_row2, tempRef_cursor2, col, value); + this.cursor = tempRef_cursor2.argValue; + this.row = tempRef_row2.argValue; + return tempVar2; + default: + return Result.NotFound; + } + } + + @FunctionalInterface + private interface AccessMethod { + void invoke(tangible.RefObject writer, TValue value); + } + + @FunctionalInterface + private interface AccessReadOnlySpanMethod { + void invoke(tangible.RefObject writer, ReadOnlySpan value); + } + + @FunctionalInterface + private interface AccessUtf8SpanMethod { + void invoke(tangible.RefObject writer, Utf8Span value); + } + + /** + * A function to write content into a . + * The type of the context value passed by the caller. + * + * @param writer A forward-only cursor for writing content. + * @param typeArg The type of the current scope. + * @param context A context value provided by the caller. + * @return The result. + */ + @FunctionalInterface + public interface WriterFunc { + Result invoke(tangible.RefObject writer, TypeArgument typeArg, TContext context); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/json/RowReaderJsonExtensions.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/json/RowReaderJsonExtensions.java new file mode 100644 index 0000000..76fa088 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/json/RowReaderJsonExtensions.java @@ -0,0 +1,492 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.json; + +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.NullValue; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; +import azure.data.cosmos.serialization.hybridrow.io.RowReader; + +public final class RowReaderJsonExtensions { + /** + * Project a JSON document from a HybridRow . + * + * @param reader The reader to project to JSON. + * @param str If successful, the JSON document that corresponds to the . + * @return The result. + */ + public static Result ToJson(tangible.RefObject reader, tangible.OutObject str) { + return azure.data.cosmos.serialization.hybridrow.json.RowReaderJsonExtensions.ToJson(reader.argValue.clone(), new RowReaderJsonSettings(" "), str); + } + + /** + * Project a JSON document from a HybridRow . + * + * @param reader The reader to project to JSON. + * @param settings Settings that control how the JSON document is formatted. + * @param str If successful, the JSON document that corresponds to the . + * @return The result. + */ + public static Result ToJson(tangible.RefObject reader, RowReaderJsonSettings settings, + tangible.OutObject str) { + ReaderStringContext ctx = new ReaderStringContext(new StringBuilder(), + new RowReaderJsonSettings(settings.IndentChars, settings.QuoteChar == '\'' ? '\'' : '"'), 1); + + ctx.Builder.append("{"); + Result result = RowReaderJsonExtensions.ToJson(reader, ctx.clone()); + if (result != Result.Success) { + str.argValue = null; + return result; + } + + ctx.Builder.append(ctx.NewLine); + ctx.Builder.append("}"); + str.argValue = ctx.Builder.toString(); + return Result.Success; + } + + private static Result ToJson(tangible.RefObject reader, ReaderStringContext ctx) { + int index = 0; + while (reader.argValue.Read()) { + String path = !reader.argValue.getPath().IsNull ? String.format("%1$s%2$s%3$s:", ctx.Settings.QuoteChar, + reader.argValue.getPath(), ctx.Settings.QuoteChar) : null; + if (index != 0) { + ctx.Builder.append(','); + } + + index++; + ctx.Builder.append(ctx.NewLine); + ctx.WriteIndent(); + if (path != null) { + ctx.Builder.append(path); + ctx.Builder.append(ctx.Separator); + } + + Result r; + char scopeBracket = '\0'; + char scopeCloseBracket = '\0'; + switch (reader.argValue.getType().LayoutCode) { + case Null: { + NullValue _; + tangible.OutObject tempOut__ = + new tangible.OutObject(); + r = reader.argValue.ReadNull(tempOut__); + _ = tempOut__.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append("null"); + break; + } + + case Boolean: { + boolean value; + tangible.OutObject tempOut_value = new tangible.OutObject(); + r = reader.argValue.ReadBool(tempOut_value); + value = tempOut_value.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case Int8: { + byte value; + tangible.OutObject tempOut_value2 = new tangible.OutObject(); + r = reader.argValue.ReadInt8(tempOut_value2); + value = tempOut_value2.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case Int16: { + short value; + tangible.OutObject tempOut_value3 = new tangible.OutObject(); + r = reader.argValue.ReadInt16(tempOut_value3); + value = tempOut_value3.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case Int32: { + int value; + tangible.OutObject tempOut_value4 = new tangible.OutObject(); + r = reader.argValue.ReadInt32(tempOut_value4); + value = tempOut_value4.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case Int64: { + long value; + tangible.OutObject tempOut_value5 = new tangible.OutObject(); + r = reader.argValue.ReadInt64(tempOut_value5); + value = tempOut_value5.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case UInt8: { + byte value; + tangible.OutObject tempOut_value6 = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = reader.ReadUInt8(out byte value); + r = reader.argValue.ReadUInt8(tempOut_value6); + value = tempOut_value6.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case UInt16: { + short value; + tangible.OutObject tempOut_value7 = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = reader.ReadUInt16(out ushort value); + r = reader.argValue.ReadUInt16(tempOut_value7); + value = tempOut_value7.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case UInt32: { + int value; + tangible.OutObject tempOut_value8 = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = reader.ReadUInt32(out uint value); + r = reader.argValue.ReadUInt32(tempOut_value8); + value = tempOut_value8.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case UInt64: { + long value; + tangible.OutObject tempOut_value9 = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = reader.ReadUInt64(out ulong value); + r = reader.argValue.ReadUInt64(tempOut_value9); + value = tempOut_value9.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case VarInt: { + long value; + tangible.OutObject tempOut_value10 = new tangible.OutObject(); + r = reader.argValue.ReadVarInt(tempOut_value10); + value = tempOut_value10.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case VarUInt: { + long value; + tangible.OutObject tempOut_value11 = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = reader.ReadVarUInt(out ulong value); + r = reader.argValue.ReadVarUInt(tempOut_value11); + value = tempOut_value11.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case Float32: { + float value; + tangible.OutObject tempOut_value12 = new tangible.OutObject(); + r = reader.argValue.ReadFloat32(tempOut_value12); + value = tempOut_value12.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case Float64: { + double value; + tangible.OutObject tempOut_value13 = new tangible.OutObject(); + r = reader.argValue.ReadFloat64(tempOut_value13); + value = tempOut_value13.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case Float128: { + Float128 _; + tangible.OutObject tempOut__2 = + new tangible.OutObject(); + r = reader.argValue.ReadFloat128(tempOut__2); + _ = tempOut__2.argValue; + if (r != Result.Success) { + return r; + } + + // ctx.Builder.AppendFormat("High: {0}, Low: {1}\n", value.High, value.Low); + Contract.Assert(false, "Float128 are not supported."); + break; + } + + case Decimal: { + java.math.BigDecimal value; + tangible.OutObject tempOut_value14 = new tangible.OutObject(); + r = reader.argValue.ReadDecimal(tempOut_value14); + value = tempOut_value14.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value); + break; + } + + case DateTime: { + java.time.LocalDateTime value; + tangible.OutObject tempOut_value15 = new tangible.OutObject(); + r = reader.argValue.ReadDateTime(tempOut_value15); + value = tempOut_value15.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(ctx.Settings.QuoteChar); + ctx.Builder.append(value); + ctx.Builder.append(ctx.Settings.QuoteChar); + break; + } + + case UnixDateTime: { + UnixDateTime value; + tangible.OutObject tempOut_value16 = + new tangible.OutObject(); + r = reader.argValue.ReadUnixDateTime(tempOut_value16); + value = tempOut_value16.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(value.Milliseconds); + break; + } + + case Guid: { + java.util.UUID value; + tangible.OutObject tempOut_value17 = new tangible.OutObject(); + r = reader.argValue.ReadGuid(tempOut_value17); + value = tempOut_value17.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(ctx.Settings.QuoteChar); + ctx.Builder.append(value.toString()); + ctx.Builder.append(ctx.Settings.QuoteChar); + break; + } + + case MongoDbObjectId: { + MongoDbObjectId value; + tangible.OutObject tempOut_value18 = new tangible.OutObject(); + r = reader.argValue.ReadMongoDbObjectId(tempOut_value18); + value = tempOut_value18.argValue; + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(ctx.Settings.QuoteChar); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ReadOnlyMemory bytes = value.ToByteArray(); + ReadOnlyMemory bytes = value.ToByteArray(); + ctx.Builder.append(bytes.Span.ToHexString()); + ctx.Builder.append(ctx.Settings.QuoteChar); + break; + } + + case Utf8: { + Utf8Span value; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword + // - these cannot be converted using the 'OutObject' helper class unless the method is within the + // code being modified: + r = reader.argValue.ReadString(out value); + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(ctx.Settings.QuoteChar); + ctx.Builder.append(value.toString()); + ctx.Builder.append(ctx.Settings.QuoteChar); + break; + } + + case Binary: { + ReadOnlySpan value; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = reader.ReadBinary(out ReadOnlySpan value); + r = reader.argValue.ReadBinary(out value); + if (r != Result.Success) { + return r; + } + + ctx.Builder.append(ctx.Settings.QuoteChar); + ctx.Builder.append(value.ToHexString()); + ctx.Builder.append(ctx.Settings.QuoteChar); + break; + } + + case NullableScope: + case ImmutableNullableScope: { + if (!reader.argValue.getHasValue()) { + ctx.Builder.append("null"); + break; + } + + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case LayoutCode.TypedTupleScope + } + + case ArrayScope: + case ImmutableArrayScope: + case TypedArrayScope: + case ImmutableTypedArrayScope: + case TypedSetScope: + case ImmutableTypedSetScope: + case TypedMapScope: + case ImmutableTypedMapScope: + case TupleScope: + case ImmutableTupleScope: + case TypedTupleScope: + case ImmutableTypedTupleScope: + case TaggedScope: + case ImmutableTaggedScope: + case Tagged2Scope: + case ImmutableTagged2Scope: + scopeBracket = '['; + scopeCloseBracket = ']'; + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case LayoutCode.EndScope + case ObjectScope: + case ImmutableObjectScope: + case Schema: + case ImmutableSchema: + scopeBracket = '{'; + scopeCloseBracket = '}'; + + case EndScope: { + ctx.Builder.append(scopeBracket); + int snapshot = ctx.Builder.length(); + r = reader.argValue.ReadScope(new ReaderStringContext(ctx.Builder, ctx.Settings.clone(), ctx.Indent + 1), RowReaderJsonExtensions.ToJson); + if (r != Result.Success) { + return r; + } + + if (ctx.Builder.length() != snapshot) { + ctx.Builder.append(ctx.NewLine); + ctx.WriteIndent(); + } + + ctx.Builder.append(scopeCloseBracket); + break; + } + + default: { + Contract.Assert(false, String.format("Unknown type will be ignored: %1$s", reader.argValue.getType().LayoutCode)); + break; + } + } + } + + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ from the original: + //ORIGINAL LINE: private readonly struct ReaderStringContext + //C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: + private final static class ReaderStringContext { + public StringBuilder Builder; + public int Indent; + public String NewLine; + public String Separator; + public RowReaderJsonSettings Settings = new RowReaderJsonSettings(); + + public ReaderStringContext() { + } + + public ReaderStringContext(StringBuilder builder, RowReaderJsonSettings settings, int indent) { + this.Settings = settings.clone(); + this.Separator = settings.IndentChars == null ? "" : " "; + this.NewLine = settings.IndentChars == null ? "" : "\n"; + this.Indent = indent; + this.Builder = builder; + } + + public void WriteIndent() { + String indentChars = this.Settings.IndentChars != null ? this.Settings.IndentChars : ""; + for (int i = 0; i < this.Indent; i++) { + this.Builder.append(indentChars); + } + } + + public ReaderStringContext clone() { + ReaderStringContext varCopy = new ReaderStringContext(); + + varCopy.Indent = this.Indent; + varCopy.Builder = this.Builder; + varCopy.Settings = this.Settings.clone(); + varCopy.Separator = this.Separator; + varCopy.NewLine = this.NewLine; + + return varCopy; + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/json/RowReaderJsonSettings.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/json/RowReaderJsonSettings.java new file mode 100644 index 0000000..89f9e3b --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/json/RowReaderJsonSettings.java @@ -0,0 +1,54 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.json; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1051 // Do not declare visible instance fields + + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public readonly struct RowReaderJsonSettings +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: +public final class RowReaderJsonSettings { + /** + * If non-null then child objects are indented by one copy of this string per level. + */ + public String IndentChars; + + /** + * The quote character to use. + * May be or . + */ + public char QuoteChar; + + + public RowReaderJsonSettings(String indentChars) { + this(indentChars, '"'); + } + + public RowReaderJsonSettings() { + this(" ", '"'); + } + + public RowReaderJsonSettings() { + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public RowReaderJsonSettings(string indentChars = " ", char quoteChar = '"') + public RowReaderJsonSettings(String indentChars, char quoteChar) { + this.IndentChars = indentChars; + this.QuoteChar = quoteChar; + } + + public RowReaderJsonSettings clone() { + RowReaderJsonSettings varCopy = new RowReaderJsonSettings(); + + varCopy.IndentChars = this.IndentChars; + varCopy.QuoteChar = this.QuoteChar; + + return varCopy; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSequenceWritable.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSequenceWritable.java new file mode 100644 index 0000000..ad6c129 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSequenceWritable.java @@ -0,0 +1,32 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +/** + * An optional interface that indicates a can also write using a + * . + * + * The sub-element type to be written. + */ +public interface ILayoutSequenceWritable extends ILayoutType { + Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + ReadOnlySequence value); + + Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + ReadOnlySequence value); + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: Result WriteSparse(ref RowBuffer b, ref RowCursor edit, ReadOnlySequence value, + // UpdateOptions options = UpdateOptions.Upsert); + Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + ReadOnlySequence value, UpdateOptions options); + + Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + ReadOnlySequence value); +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSpanReadable.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSpanReadable.java new file mode 100644 index 0000000..fe0cf30 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSpanReadable.java @@ -0,0 +1,26 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +/** + * An optional interface that indicates a can also read using a + * . + * + * The sub-element type to be written. + */ +public interface ILayoutSpanReadable extends ILayoutType { + Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject> value); + + Result ReadSparse(tangible.RefObject b, tangible.RefObject scope, + tangible.OutObject> value); + + Result ReadVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject> value); +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSpanWritable.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSpanWritable.java new file mode 100644 index 0000000..9b3b571 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutSpanWritable.java @@ -0,0 +1,32 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +/** + * An optional interface that indicates a can also write using a + * . + * + * The sub-element type to be written. + */ +public interface ILayoutSpanWritable extends ILayoutType { + Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + ReadOnlySpan value); + + Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + ReadOnlySpan value); + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: Result WriteSparse(ref RowBuffer b, ref RowCursor edit, ReadOnlySpan value, + // UpdateOptions options = UpdateOptions.Upsert); + Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + ReadOnlySpan value, UpdateOptions options); + + Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + ReadOnlySpan value); +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutType.java new file mode 100644 index 0000000..77c12bd --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutType.java @@ -0,0 +1,11 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +/** + * Marker interface for layout types. + */ +public interface ILayoutType { +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutUtf8SpanReadable.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutUtf8SpanReadable.java new file mode 100644 index 0000000..59aca73 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutUtf8SpanReadable.java @@ -0,0 +1,23 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +/** + * An optional interface that indicates a can also read using a + * . + */ +public interface ILayoutUtf8SpanReadable extends ILayoutType { + Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value); + + Result ReadSparse(tangible.RefObject b, tangible.RefObject scope, tangible.OutObject value); + + Result ReadVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value); +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutUtf8SpanWritable.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutUtf8SpanWritable.java new file mode 100644 index 0000000..62c4085 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/ILayoutUtf8SpanWritable.java @@ -0,0 +1,28 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +/** + * An optional interface that indicates a can also write using a + * . + */ +public interface ILayoutUtf8SpanWritable extends ILayoutType { + Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + Utf8Span value); + + Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, Utf8Span value); + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: Result WriteSparse(ref RowBuffer b, ref RowCursor edit, Utf8Span value, UpdateOptions options = + // UpdateOptions.Upsert); + Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, Utf8Span value, UpdateOptions options); + + Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + Utf8Span value); +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/Layout.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/Layout.java new file mode 100644 index 0000000..fcfb1dc --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/Layout.java @@ -0,0 +1,195 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +import java.util.ArrayList; +import java.util.HashMap; + +/** + * A Layout describes the structure of a Hybrd Row. + *

+ * A layout indicates the number, order, and type of all schematized columns to be stored + * within a hybrid row. The order and type of columns defines the physical ordering of bytes used to + * encode the row and impacts the cost of updating the row. + * + * A layout is created by compiling a through or + * by constructor through a . + * + * is immutable. + */ +public final class Layout { + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly Layout Empty = SystemSchema.LayoutResolver + // .Resolve(SystemSchema.EmptySchemaId); + public static final Layout Empty = SystemSchema.LayoutResolver.Resolve(SystemSchema.EmptySchemaId); + /** + * Name of the layout. + *

+ * Usually this is the name of the from which this + * was generated. + */ + private String Name; + /** + * The number of bitmask bytes allocated within the layout. + *

+ * A presence bit is allocated for each fixed and variable-length field. Sparse columns + * never have presence bits. Fixed boolean allocate an additional bit from the bitmask to store their + * value. + */ + private int NumBitmaskBytes; + /** + * The number of fixed columns. + */ + private int NumFixed; + /** + * The number of variable-length columns. + */ + private int NumVariable; + /** + * Unique identifier of the schema from which this was generated. + */ + private SchemaId SchemaId = new SchemaId(); + /** + * Minimum required size of a row of this layout. + *

+ * This size excludes all sparse columns, and assumes all columns (including variable) are + * null. + */ + private int Size; + private HashMap pathMap; + private HashMap pathStringMap; + private LayoutColumn[] topColumns; + + public Layout(String name, SchemaId schemaId, int numBitmaskBytes, int minRequiredSize, + ArrayList columns) { + this.Name = name; + this.SchemaId = schemaId.clone(); + this.NumBitmaskBytes = numBitmaskBytes; + this.Size = minRequiredSize; + this.Tokenizer = new StringTokenizer(); + this.pathMap = new HashMap(columns.size(), SamplingUtf8StringComparer.Default); + this.pathStringMap = new HashMap(columns.size()); + this.NumFixed = 0; + this.NumVariable = 0; + + ArrayList top = new ArrayList(columns.size()); + for (LayoutColumn c : columns) { + this.getTokenizer().Add(c.getPath()); + this.pathMap.put(c.getFullPath(), c); + this.pathStringMap.put(c.getFullPath().toString(), c); + if (c.getStorage() == StorageKind.Fixed) { + this.NumFixed = this.getNumFixed() + 1; + } else if (c.getStorage() == StorageKind.Variable) { + this.NumVariable = this.getNumVariable() + 1; + } + + if (c.getParent() == null) { + top.add(c); + } + } + + this.topColumns = top.toArray(new LayoutColumn[0]); + } + + /** + * The set of top level columns defined in the layout (in left-to-right order). + */ + public ReadOnlySpan getColumns() { + return this.topColumns.AsSpan(); + } + + public String getName() { + return Name; + } + + public int getNumBitmaskBytes() { + return NumBitmaskBytes; + } + + public int getNumFixed() { + return NumFixed; + } + + public int getNumVariable() { + return NumVariable; + } + + public SchemaId getSchemaId() { + return SchemaId; + } + + public int getSize() { + return Size; + } + + /** + * Finds a column specification for a column with a matching path. + * + * @param path The path of the column to find. + * @param column If found, the column specification, otherwise null. + * @return True if a column with the path is found, otherwise false. + */ + public boolean TryFind(UtfAnyString path, tangible.OutObject column) { + if (path.IsNull) { + column.argValue = null; + return false; + } + + if (path.IsUtf8) { + return (this.pathMap.containsKey(path.ToUtf8String()) && (column.argValue = + this.pathMap.get(path.ToUtf8String())) == column.argValue); + } + + return (this.pathStringMap.containsKey(path) && (column.argValue = this.pathStringMap.get(path)) == column.argValue); + } + + /** + * Finds a column specification for a column with a matching path. + * + * @param path The path of the column to find. + * @param column If found, the column specification, otherwise null. + * @return True if a column with the path is found, otherwise false. + */ + public boolean TryFind(String path, tangible.OutObject column) { + return (this.pathStringMap.containsKey(path) && (column.argValue = this.pathStringMap.get(path)) == column.argValue); + } + + /** + * Returns a human readable diagnostic string representation of this . + * This representation should only be used for debugging and diagnostic purposes. + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("Layout:\n"); + sb.append(String.format("\tCount: %1$s\n", this.topColumns.length)); + sb.append(String.format("\tFixedSize: %1$s\n", this.getSize())); + for (LayoutColumn c : this.topColumns) { + if (c.getType().getIsFixed()) { + if (c.getType().getIsBool()) { + sb.append(String.format("\t%1$s: %2$s @ %3$s:%4$s:%5$s\n", c.getFullPath(), c.getType().getName(), c.getOffset(), c.getNullBit().clone(), c.getBoolBit().clone())); + } else { + sb.append(String.format("\t%1$s: %2$s @ %3$s\n", c.getFullPath(), c.getType().getName(), c.getOffset())); + } + } else { + sb.append(String.format("\t%1$s: %2$s[%4$s] @ %3$s\n", c.getFullPath(), c.getType().getName(), c.getOffset(), c.getSize())); + } + } + + return sb.toString(); + } + + /** + * A tokenizer for path strings. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Bug in + // Analyzer. This is an auto-property not a method.")] public StringTokenizer Tokenizer + private StringTokenizer getTokenizer() { + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutArray.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutArray.java new file mode 100644 index 0000000..3d14205 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutArray.java @@ -0,0 +1,53 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ArrayScope; +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableArrayScope; + +public final class LayoutArray extends LayoutIndexedScope { + private TypeArgument TypeArg = new TypeArgument(); + + public LayoutArray(boolean immutable) { + super(immutable ? ImmutableArrayScope : ArrayScope, immutable, false, false, false, false); + this.TypeArg = new TypeArgument(this); + } + + @Override + public String getName() { + return this.Immutable ? "im_array" : "array"; + } + + public TypeArgument getTypeArg() { + return TypeArg; + } + + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteSparseArray(edit, this, options, value.clone()); + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBinary.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBinary.java new file mode 100644 index 0000000..94082f3 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBinary.java @@ -0,0 +1,298 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +//C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: +//ORIGINAL LINE: public sealed class LayoutBinary : LayoutType, ILayoutSpanWritable, +// ILayoutSpanReadable, ILayoutSequenceWritable +public final class LayoutBinary extends LayoutType implements ILayoutSpanWritable, + ILayoutSpanReadable, ILayoutSequenceWritable { + public LayoutBinary() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Binary, 0); + } + + @Override + public boolean getIsFixed() { + return false; + } + + @Override + public String getName() { + return "binary"; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, out + // byte[] value) + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + ReadOnlySpan span; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Result r = this.ReadFixed(ref b, ref scope, col, out ReadOnlySpan span); + Result r = this.ReadFixed(b, scope, col, out span); + value.argValue = (r == Result.Success) ? span.ToArray() : + default + return r; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, out + // ReadOnlySpan value) + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject> value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + checkArgument(col.getSize() >= 0); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = null; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadFixedBinary(scope.argValue.start + col.getOffset(), col.getSize()); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadSparse(ref RowBuffer b, ref RowCursor edit, out byte[] value) + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + ReadOnlySpan span; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Result r = this.ReadSparse(ref b, ref edit, out ReadOnlySpan span); + Result r = this.ReadSparse(b, edit, out span); + value.argValue = (r == Result.Success) ? span.ToArray() : + default + return r; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadSparse(ref RowBuffer b, ref RowCursor edit, out ReadOnlySpan value) + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, tangible.OutObject> value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + value.argValue = b.argValue.ReadSparseBinary(edit); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadVariable(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, out + // byte[] value) + @Override + public Result ReadVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col + , tangible.OutObject value) { + ReadOnlySpan span; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Result r = this.ReadVariable(ref b, ref scope, col, out ReadOnlySpan span); + Result r = this.ReadVariable(b, scope, col, out span); + value.argValue = (r == Result.Success) ? span.ToArray() : + default + return r; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadVariable(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, out + // ReadOnlySpan value) + public Result ReadVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col + , tangible.OutObject> value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = null; + return Result.NotFound; + } + + int varOffset = b.argValue.ComputeVariableValueOffset(scope.argValue.layout, scope.argValue.start, + col.getOffset()); + value.argValue = b.argValue.ReadVariableBinary(varOffset); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result WriteFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, byte[] + // value) + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + byte[] value) { + checkArgument(value != null); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WriteFixed(ref b, ref scope, col, new ReadOnlySpan(value)); + return this.WriteFixed(b, scope, col, new ReadOnlySpan(value)); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, + // ReadOnlySpan value) + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + ReadOnlySpan value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + checkArgument(col.getSize() >= 0); + checkArgument(value.Length == col.getSize()); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteFixedBinary(scope.argValue.start + col.getOffset(), value, col.getSize()); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, + // ReadOnlySequence value) + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + ReadOnlySequence value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + checkArgument(col.getSize() >= 0); + checkArgument(value.Length == col.getSize()); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteFixedBinary(scope.argValue.start + col.getOffset(), value, col.getSize()); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, byte[] value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, byte[] value, + // UpdateOptions options = UpdateOptions.Upsert) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, byte[] value, + UpdateOptions options) { + checkArgument(value != null); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WriteSparse(ref b, ref edit, new ReadOnlySpan(value), options); + return this.WriteSparse(b, edit, new ReadOnlySpan(value), options); + } + + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + ReadOnlySpan value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public Result WriteSparse(ref RowBuffer b, ref RowCursor edit, ReadOnlySpan value, + // UpdateOptions options = UpdateOptions.Upsert) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + ReadOnlySpan value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseBinary(edit, value, options); + return Result.Success; + } + + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + ReadOnlySequence value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public Result WriteSparse(ref RowBuffer b, ref RowCursor edit, ReadOnlySequence value, + // UpdateOptions options = UpdateOptions.Upsert) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + ReadOnlySequence value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseBinary(edit, value, options); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result WriteVariable(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, + // byte[] value) + @Override + public Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col, byte[] value) { + checkArgument(value != null); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return this.WriteVariable(ref b, ref scope, col, new ReadOnlySpan(value)); + return this.WriteVariable(b, scope, col, new ReadOnlySpan(value)); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteVariable(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, + // ReadOnlySpan value) + public Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col, ReadOnlySpan value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + int length = value.Length; + if ((col.getSize() > 0) && (length > col.getSize())) { + return Result.TooBig; + } + + boolean exists = b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone()); + int varOffset = b.argValue.ComputeVariableValueOffset(scope.argValue.layout, scope.argValue.start, + col.getOffset()); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + b.argValue.WriteVariableBinary(varOffset, value, exists, tempOut_shift); + shift = tempOut_shift.argValue; + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + scope.argValue.metaOffset += shift; + scope.argValue.valueOffset += shift; + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result WriteVariable(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, + // ReadOnlySequence value) + public Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col, ReadOnlySequence value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + int length = (int)value.Length; + if ((col.getSize() > 0) && (length > col.getSize())) { + return Result.TooBig; + } + + boolean exists = b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone()); + int varOffset = b.argValue.ComputeVariableValueOffset(scope.argValue.layout, scope.argValue.start, + col.getOffset()); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + b.argValue.WriteVariableBinary(varOffset, value, exists, tempOut_shift); + shift = tempOut_shift.argValue; + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + scope.argValue.metaOffset += shift; + scope.argValue.valueOffset += shift; + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBit.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBit.java new file mode 100644 index 0000000..66a2e80 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBit.java @@ -0,0 +1,155 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import static com.google.common.base.Preconditions.checkArgument; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public readonly struct LayoutBit : IEquatable +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: +public final class LayoutBit implements IEquatable { + /** + * The empty bit. + */ + public static final LayoutBit Invalid = new LayoutBit(-1); + + /** + * The 0-based offset into the layout bitmask. + */ + private int index; + + /** + * Initializes a new instance of the struct. + * + * @param index The 0-based offset into the layout bitmask. + */ + public LayoutBit() { + } + + public LayoutBit(int index) { + checkArgument(index >= -1); + this.index = index; + } + + /** + * Compute the division rounding up to the next whole number. + * + * @param numerator The numerator to divide. + * @param divisor The divisor to divide by. + * @return The ceiling(numerator/divisor). + */ + public static int DivCeiling(int numerator, int divisor) { + return (numerator + (divisor - 1)) / divisor; + } + + /** + * Returns the 0-based bit from the beginning of the byte that contains this bit. + * Also see to identify relevant byte. + * + * @return The bit of the byte within the bitmask. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetBit() + public int GetBit() { + return this.index % LayoutType.BitsPerByte; + } + + /** + * Returns the 0-based byte offset from the beginning of the row or scope that contains the + * bit from the bitmask. + *

+ * Also see to identify. + * + * @param offset The byte offset from the beginning of the row where the scope begins. + * @return The byte offset containing this bit. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetOffset(int offset) + public int GetOffset(int offset) { + return offset + (this.index / LayoutType.BitsPerByte); + } + + public LayoutBit clone() { + LayoutBit varCopy = new LayoutBit(); + + varCopy.index = this.index; + + return varCopy; + } + + @Override + public boolean equals(Object other) { + return other instanceof LayoutBit && this.equals((LayoutBit)other); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(LayoutBit other) + public boolean equals(LayoutBit other) { + return this.index == other.index; + } + + @Override + public int hashCode() { + return (new Integer(this.index)).hashCode(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(LayoutBit + // left, LayoutBit right) + public static boolean opEquals(LayoutBit left, LayoutBit right) { + return left.equals(right.clone()); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(LayoutBit + // left, LayoutBit right) + public static boolean opNotEquals(LayoutBit left, LayoutBit right) { + return !azure.data.cosmos.serialization.hybridrow.layouts.LayoutBit.opEquals(left.clone(), right.clone()); + } + + /** + * The 0-based offset into the layout bitmask. + */ + int getIndex() + + /** + * The 0-based offset into the layout bitmask. + */ + boolean getIsInvalid() + + /** + * Allocates layout bits from a bitmask. + */ + public static class Allocator { + /** + * The next bit to allocate. + */ + private int next; + + /** + * Initializes a new instance of the class. + */ + public Allocator() { + this.next = 0; + } + + /** + * The number of bytes needed to hold all bits so far allocated. + */ + public final int getNumBytes() { + return LayoutBit.DivCeiling(this.next, LayoutType.BitsPerByte); + } + + /** + * Allocates a new bit from the bitmask. + * + * @return The allocated bit. + */ + public final LayoutBit Allocate() { + return new LayoutBit(this.next++); + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBoolean.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBoolean.java new file mode 100644 index 0000000..5aaf540 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBoolean.java @@ -0,0 +1,96 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutBoolean extends LayoutType { + public LayoutBoolean(boolean value) { + super(, 0); + } + + @Override + public boolean getIsBool() { + return true; + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "bool"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = false; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadBit(scope.argValue.start, col.getBoolBit().clone()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = false; + return result; + } + + value.argValue = b.argValue.ReadSparseBool(edit); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + boolean value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + if (value) { + b.argValue.SetBit(scope.argValue.start, col.getBoolBit().clone()); + } else { + b.argValue.UnsetBit(scope.argValue.start, col.getBoolBit().clone()); + } + + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, bool value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, boolean value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseBool(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, boolean value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBuilder.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBuilder.java new file mode 100644 index 0000000..2de78ad --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutBuilder.java @@ -0,0 +1,169 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.SchemaId; +import azure.data.cosmos.serialization.hybridrow.schemas.StorageKind; + +import java.util.ArrayList; +import java.util.Stack; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutBuilder { + private LayoutBit.Allocator bitallocator; + private ArrayList fixedColumns; + private int fixedCount; + private int fixedSize; + private String name; + private SchemaId schemaId = new SchemaId(); + private Stack scope; + private ArrayList sparseColumns; + private int sparseCount; + private ArrayList varColumns; + private int varCount; + + // [ + // + // ... + // ... + // ... + // ] + public LayoutBuilder(String name, SchemaId schemaId) { + this.name = name; + this.schemaId = schemaId.clone(); + this.Reset(); + } + + public void AddFixedColumn(String path, LayoutType type, boolean nullable) { + AddFixedColumn(path, type, nullable, 0); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public void AddFixedColumn(string path, LayoutType type, bool nullable, int length = 0) + public void AddFixedColumn(String path, LayoutType type, boolean nullable, int length) { + checkArgument(length >= 0); + checkArgument(!type.getIsVarint()); + + LayoutColumn col; + if (type.getIsNull()) { + checkArgument(nullable); + LayoutBit nullbit = this.bitallocator.Allocate().clone(); + col = new LayoutColumn(path, type, TypeArgumentList.Empty, StorageKind.Fixed, this.getParent(), + this.fixedCount, 0, nullbit.clone(), LayoutBit.Invalid, 0); + } else if (type.getIsBool()) { + LayoutBit nullbit = nullable ? this.bitallocator.Allocate() : LayoutBit.Invalid; + LayoutBit boolbit = this.bitallocator.Allocate().clone(); + col = new LayoutColumn(path, type, TypeArgumentList.Empty, StorageKind.Fixed, this.getParent(), + this.fixedCount, 0, nullbit.clone(), boolbit.clone(), 0); + } else { + LayoutBit nullBit = nullable ? this.bitallocator.Allocate() : LayoutBit.Invalid; + col = new LayoutColumn(path, type, TypeArgumentList.Empty, StorageKind.Fixed, this.getParent(), + this.fixedCount, this.fixedSize, nullBit.clone(), LayoutBit.Invalid, length); + + this.fixedSize += type.getIsFixed() ? type.Size : length; + } + + this.fixedCount++; + this.fixedColumns.add(col); + } + + public void AddObjectScope(String path, LayoutType type) { + LayoutColumn col = new LayoutColumn(path, type, TypeArgumentList.Empty, StorageKind.Sparse, this.getParent(), + this.sparseCount, -1, LayoutBit.Invalid, LayoutBit.Invalid, 0); + + this.sparseCount++; + this.sparseColumns.add(col); + this.scope.push(col); + } + + public void AddSparseColumn(String path, LayoutType type) { + LayoutColumn col = new LayoutColumn(path, type, TypeArgumentList.Empty, StorageKind.Sparse, this.getParent(), + this.sparseCount, -1, LayoutBit.Invalid, LayoutBit.Invalid, 0); + + this.sparseCount++; + this.sparseColumns.add(col); + } + + public void AddTypedScope(String path, LayoutType type, TypeArgumentList typeArgs) { + LayoutColumn col = new LayoutColumn(path, type, typeArgs.clone(), StorageKind.Sparse, this.getParent(), + this.sparseCount, -1, LayoutBit.Invalid, LayoutBit.Invalid, 0); + + this.sparseCount++; + this.sparseColumns.add(col); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public void AddVariableColumn(string path, LayoutType type, int length = 0) + public void AddVariableColumn(String path, LayoutType type, int length) { + + checkArgument(length >= 0); + checkArgument(type.getAllowVariable()); + + LayoutColumn col = new LayoutColumn(path, type, TypeArgumentList.Empty, StorageKind.Variable, + this.getParent(), this.varCount, this.varCount, this.bitallocator.Allocate().clone(), LayoutBit.Invalid, + length); + + this.varCount++; + this.varColumns.add(col); + } + + public void AddVariableColumn(String path, LayoutType type) { + AddVariableColumn(path, type, 0); + } + + public Layout Build() { + // Compute offset deltas. Offset bools by the present byte count, and fixed fields by the sum of the present + // and bool count. + int fixedDelta = this.bitallocator.getNumBytes(); + int varIndexDelta = this.fixedCount; + + // Update the fixedColumns with the delta before freezing them. + ArrayList updatedColumns = + new ArrayList(this.fixedColumns.size() + this.varColumns.size()); + + for (LayoutColumn c : this.fixedColumns) { + c.SetOffset(c.getOffset() + fixedDelta); + updatedColumns.add(c); + } + + for (LayoutColumn c : this.varColumns) { + // Adjust variable column indexes such that they begin immediately following the last fixed column. + c.SetIndex(c.getIndex() + varIndexDelta); + updatedColumns.add(c); + } + + updatedColumns.addAll(this.sparseColumns); + + Layout layout = new Layout(this.name, this.schemaId.clone(), this.bitallocator.getNumBytes(), this.fixedSize + fixedDelta, updatedColumns); + this.Reset(); + return layout; + } + + public void EndObjectScope() { + checkArgument(this.scope.size() > 0); + this.scope.pop(); + } + + private LayoutColumn getParent() { + if (this.scope.empty()) { + return null; + } + + return this.scope.peek(); + } + + private void Reset() { + this.bitallocator = new LayoutBit.Allocator(); + this.fixedSize = 0; + this.fixedCount = 0; + this.fixedColumns = new ArrayList(); + this.varCount = 0; + this.varColumns = new ArrayList(); + this.sparseCount = 0; + this.sparseColumns = new ArrayList(); + this.scope = new Stack(); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCode.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCode.java new file mode 100644 index 0000000..4cca7c0 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCode.java @@ -0,0 +1,114 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1028 // Enum Storage should be Int32 + + +/** + * Type coded used in the binary encoding to indicate the formatting of succeeding bytes. + */ +//C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: +//ORIGINAL LINE: public enum LayoutCode : byte +public enum LayoutCode { + Invalid((byte)0), + + Null((byte)1), + BooleanFalse((byte)2), + Boolean((byte)3), + + Int8((byte)5), + Int16((byte)6), + Int32((byte)7), + Int64((byte)8), + UInt8((byte)9), + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: UInt16 = 10, + UInt16((byte)10), + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: UInt32 = 11, + UInt32((byte)11), + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: UInt64 = 12, + UInt64((byte)12), + VarInt((byte)13), + VarUInt((byte)14), + + Float32((byte)15), + Float64((byte)16), + Decimal((byte)17), + + DateTime((byte)18), + Guid((byte)19), + + Utf8((byte)20), + Binary((byte)21), + + Float128((byte)22), + UnixDateTime((byte)23), + MongoDbObjectId((byte)24), + + ObjectScope((byte)30), + ImmutableObjectScope((byte)31), + ArrayScope((byte)32), + ImmutableArrayScope((byte)33), + TypedArrayScope((byte)34), + ImmutableTypedArrayScope((byte)35), + TupleScope((byte)36), + ImmutableTupleScope((byte)37), + TypedTupleScope((byte)38), + ImmutableTypedTupleScope((byte)39), + MapScope((byte)40), + ImmutableMapScope((byte)41), + TypedMapScope((byte)42), + ImmutableTypedMapScope((byte)43), + SetScope((byte)44), + ImmutableSetScope((byte)45), + TypedSetScope((byte)46), + ImmutableTypedSetScope((byte)47), + NullableScope((byte)48), + ImmutableNullableScope((byte)49), + TaggedScope((byte)50), + ImmutableTaggedScope((byte)51), + Tagged2Scope((byte)52), + ImmutableTagged2Scope((byte)53), + + /** + * Nested row. + */ + Schema((byte)68), + ImmutableSchema((byte)69), + + EndScope((byte)70); + + public static final int SIZE = java.lang.Byte.SIZE; + private static java.util.HashMap mappings; + private byte byteValue; + + LayoutCode(byte value) { + byteValue = value; + getMappings().put(value, this); + } + + public byte getValue() { + return byteValue; + } + + public static LayoutCode forValue(byte value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (LayoutCode.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCodeTraits.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCodeTraits.java new file mode 100644 index 0000000..71fbe40 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCodeTraits.java @@ -0,0 +1,42 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +public final class LayoutCodeTraits { + /** + * Returns true if the type code indicates that, even within a typed scope, this element type + * always requires a type code (because the value itself is in the type code). + * + * @param code The element type code. + */ + public static boolean AlwaysRequiresTypeCode(LayoutCode code) { + return (code == LayoutCode.Boolean) || (code == LayoutCode.BooleanFalse) || (code == LayoutCode.Null); + } + + /** + * Returns a canonicalized version of the layout code. + *

+ * Some codes (e.g. use multiple type codes to also encode + * values. This function converts actual value based code into the canonicalized type code for schema + * comparisons. + * + * @param code The code to canonicalize. + */ + public static LayoutCode Canonicalize(LayoutCode code) { + return (code == LayoutCode.BooleanFalse) ? LayoutCode.Boolean : code; + } + + /** + * Returns the same scope code without the immutable bit set. + * + * @param code The scope type code. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] public static LayoutCode ClearImmutableBit + // (LayoutCode code) + public static LayoutCode ClearImmutableBit(LayoutCode code) { + return code.getValue() & LayoutCode.forValue((byte)0xFE).getValue(); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutColumn.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutColumn.java new file mode 100644 index 0000000..6dd7515 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutColumn.java @@ -0,0 +1,246 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.schemas.StorageKind; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [DebuggerDisplay("{FullPath + \": \" + Type.Name + TypeArgs.ToString()}")] public sealed class +// LayoutColumn +public final class LayoutColumn { + /** + * For bool fields, 0-based index into the bit mask for the bool value. + */ + private LayoutBit boolBit = new LayoutBit(); + /** + * The full logical path of the field within the row. + */ + private Utf8String fullPath; + /** + * 0-based index of the column within the structure. Also indicates which presence bit + * controls this column. + */ + private int index; + /** + * For nullable fields, the 0-based index into the bit mask for the null bit. + */ + private LayoutBit nullBit = new LayoutBit(); + /** + * If equals then the byte offset to + * the field location. + * + * If equals then the 0-based index of the + * field from the beginning of the variable length segment. + * + * For all other values of , is ignored. + */ + private int offset; + /** + * The layout of the parent scope, if a nested column, otherwise null. + */ + private LayoutColumn parent; + /** + * The relative path of the field within its parent scope. + */ + private Utf8String path; + /** + * If then the 0-based extra index within the bool byte + * holding the value of this type, otherwise must be 0. + */ + private int size; + /** + * The storage kind of the field. + */ + private StorageKind storage = StorageKind.values()[0]; + /** + * The physical layout type of the field. + */ + private LayoutType type; + /** + * The physical layout type of the field. + */ + private TypeArgument typeArg = new TypeArgument(); + /** + * For types with generic parameters (e.g. , the type parameters. + */ + private TypeArgumentList typeArgs = new TypeArgumentList(); + + /** + * Initializes a new instance of the class. + * + * @param path The path to the field relative to parent scope. + * @param type Type of the field. + * @param storage Storage encoding of the field. + * @param parent The layout of the parent scope, if a nested column. + * @param index 0-based column index. + * @param offset 0-based Offset from beginning of serialization. + * @param nullBit 0-based index into the bit mask for the null bit. + * @param boolBit For bool fields, 0-based index into the bit mask for the bool value. + * @param length For variable length types the length, otherwise 0. + * @param typeArgs For types with generic parameters (e.g. , the type + * parameters. + */ + + public LayoutColumn(String path, LayoutType type, TypeArgumentList typeArgs, StorageKind storage, + LayoutColumn parent, int index, int offset, LayoutBit nullBit, LayoutBit boolBit) { + this(path, type, typeArgs, storage, parent, index, offset, nullBit, boolBit, 0); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: internal LayoutColumn(string path, LayoutType type, TypeArgumentList typeArgs, StorageKind + // storage, LayoutColumn parent, int index, int offset, LayoutBit nullBit, LayoutBit boolBit, int length = 0) + public LayoutColumn(String path, LayoutType type, TypeArgumentList typeArgs, StorageKind storage, + LayoutColumn parent, int index, int offset, LayoutBit nullBit, LayoutBit boolBit, int length) { + this.path = Utf8String.TranscodeUtf16(path); + this.fullPath = Utf8String.TranscodeUtf16(LayoutColumn.GetFullPath(parent, path)); + this.type = type; + this.typeArgs = typeArgs.clone(); + this.typeArg = new TypeArgument(type, typeArgs.clone()); + this.storage = storage; + this.parent = parent; + this.index = index; + this.offset = offset; + this.nullBit = nullBit.clone(); + this.boolBit = boolBit.clone(); + this.size = this.typeArg.getType().getIsFixed() ? type.Size : length; + } + + /** + * The full logical path of the field within the row. + *

+ * Paths are expressed in dotted notation: e.g. a relative of 'b.c' + * within the scope 'a' yields a of 'a.b.c'. + */ + public Utf8String getFullPath() { + return this.fullPath; + } + + /** + * 0-based index of the column within the structure. Also indicates which presence bit + * controls this column. + */ + public int getIndex() { + return this.index; + } + + /** + * The layout of the parent scope, if a nested column, otherwise null. + */ + public LayoutColumn getParent() { + return this.parent; + } + + /** + * The relative path of the field within its parent scope. + *

+ * Paths are expressed in dotted notation: e.g. a relative of 'b.c' + * within the scope 'a' yields a of 'a.b.c'. + */ + public Utf8String getPath() { + return this.path; + } + + /** + * The storage kind of the field. + */ + public StorageKind getStorage() { + return this.storage; + } + + /** + * The physical layout type of the field. + */ + public LayoutType getType() { + return this.type; + } + + /** + * The full logical type. + */ + public TypeArgument getTypeArg() { + return this.typeArg.clone(); + } + + /** + * For types with generic parameters (e.g. , the type parameters. + */ + public TypeArgumentList getTypeArgs() { + return this.typeArgs.clone(); + } + + public void SetIndex(int index) { + this.index = index; + } + + public void SetOffset(int offset) { + this.offset = offset; + } + + /** + * The physical layout type of the field cast to the specified type. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DebuggerHidden] public T TypeAs() where T : ILayoutType + public T TypeAs() { + return this.type.TypeAs(); + } + + /** + * For bool fields, 0-based index into the bit mask for the bool value. + */ + LayoutBit getBoolBit() + + /** + * For nullable fields, the the bit in the layout bitmask for the null bit. + */ + LayoutBit getNullBit() + + /** + * If equals then the byte offset to + * the field location. + * + * If equals then the 0-based index of the + * field from the beginning of the variable length segment. + * + * For all other values of , is ignored. + */ + int getOffset() + + /** + * If equals then the fixed number of + * bytes reserved for the value. + * + * If equals then the maximum number of + * bytes allowed for the value. + */ + int getSize() + + /** + * Computes the full logical path to the column. + * + * @param parent The layout of the parent scope, if a nested column, otherwise null. + * @param path The path to the field relative to parent scope. + * @return The full logical path. + */ + private static String GetFullPath(LayoutColumn parent, String path) { + if (parent != null) { + switch (LayoutCodeTraits.ClearImmutableBit(parent.type.LayoutCode)) { + case ObjectScope: + case Schema: + return parent.getFullPath().toString() + "." + path; + case ArrayScope: + case TypedArrayScope: + case TypedSetScope: + case TypedMapScope: + return parent.getFullPath().toString() + "[]" + path; + default: + Contract.Fail(String.format("Parent scope type not supported: %1$s", parent.type.LayoutCode)); + return null; + } + } + + return path; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCompilationException.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCompilationException.java new file mode 100644 index 0000000..9944f9a --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCompilationException.java @@ -0,0 +1,26 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import java.io.Serializable; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [Serializable][ExcludeFromCodeCoverage] public sealed class LayoutCompilationException : Exception +public final class LayoutCompilationException extends RuntimeException implements Serializable { + public LayoutCompilationException() { + } + + public LayoutCompilationException(String message) { + super(message); + } + + public LayoutCompilationException(String message, RuntimeException innerException) { + super(message, innerException); + } + + private LayoutCompilationException(SerializationInfo info, StreamingContext context) { + super(info, context); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCompiler.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCompiler.java new file mode 100644 index 0000000..62458cc --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutCompiler.java @@ -0,0 +1,370 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.SchemaId; +import azure.data.cosmos.serialization.hybridrow.schemas.ArrayPropertyType; +import azure.data.cosmos.serialization.hybridrow.schemas.MapPropertyType; +import azure.data.cosmos.serialization.hybridrow.schemas.Namespace; +import azure.data.cosmos.serialization.hybridrow.schemas.ObjectPropertyType; +import azure.data.cosmos.serialization.hybridrow.schemas.PrimitivePropertyType; +import azure.data.cosmos.serialization.hybridrow.schemas.Property; +import azure.data.cosmos.serialization.hybridrow.schemas.PropertyType; +import azure.data.cosmos.serialization.hybridrow.schemas.Schema; +import azure.data.cosmos.serialization.hybridrow.schemas.ScopePropertyType; +import azure.data.cosmos.serialization.hybridrow.schemas.SetPropertyType; +import azure.data.cosmos.serialization.hybridrow.schemas.TaggedPropertyType; +import azure.data.cosmos.serialization.hybridrow.schemas.TuplePropertyType; +import azure.data.cosmos.serialization.hybridrow.schemas.TypeKind; +import azure.data.cosmos.serialization.hybridrow.schemas.UdtPropertyType; + +import java.util.ArrayList; + +import static com.google.common.base.Preconditions.checkArgument; + +/** + * Converts a logical schema into a physical layout. + */ +public final class LayoutCompiler { + /** + * Compiles a logical schema into a physical layout that can be used to read and write rows. + * + * @param ns The namespace within which is defined. + * @param schema The logical schema to produce a layout for. + * @return The layout for the schema. + */ + public static Layout Compile(Namespace ns, Schema schema) { + checkArgument(ns != null); + checkArgument(schema != null); + checkArgument(schema.getType() == TypeKind.Schema); + checkArgument(!tangible.StringHelper.isNullOrWhiteSpace(schema.getName())); + checkArgument(ns.getSchemas().contains(schema)); + + LayoutBuilder builder = new LayoutBuilder(schema.getName(), schema.getSchemaId().clone()); + LayoutCompiler.AddProperties(builder, ns, LayoutCode.Schema, schema.getProperties()); + + return builder.Build(); + } + + private static void AddProperties(LayoutBuilder builder, Namespace ns, LayoutCode scope, + ArrayList properties) { + for (Property p : properties) { + TypeArgumentList typeArgs = new TypeArgumentList(); + tangible.OutObject tempOut_typeArgs = + new tangible.OutObject(); + LayoutType type = LayoutCompiler.LogicalToPhysicalType(ns, p.getPropertyType(), tempOut_typeArgs); + typeArgs = tempOut_typeArgs.argValue; + switch (LayoutCodeTraits.ClearImmutableBit(type.LayoutCode)) { + case ObjectScope: { + if (!p.getPropertyType().getNullable()) { + throw new LayoutCompilationException("Non-nullable sparse column are not supported."); + } + + ObjectPropertyType op = (ObjectPropertyType)p.getPropertyType(); + builder.AddObjectScope(p.getPath(), type); + LayoutCompiler.AddProperties(builder, ns, type.LayoutCode, op.getProperties()); + builder.EndObjectScope(); + break; + } + + case ArrayScope: + case TypedArrayScope: + case SetScope: + case TypedSetScope: + case MapScope: + case TypedMapScope: + case TupleScope: + case TypedTupleScope: + case TaggedScope: + case Tagged2Scope: + case Schema: { + if (!p.getPropertyType().getNullable()) { + throw new LayoutCompilationException("Non-nullable sparse column are not supported."); + } + + builder.AddTypedScope(p.getPath(), type, typeArgs.clone()); + break; + } + + case NullableScope: { + throw new LayoutCompilationException("Nullables cannot be explicitly declared as columns."); + } + + default: { + PropertyType tempVar = p.getPropertyType(); + PrimitivePropertyType pp = tempVar instanceof PrimitivePropertyType ? + (PrimitivePropertyType)tempVar : null; + if (pp != null) { + switch (pp.getStorage()) { + case Fixed: + if (LayoutCodeTraits.ClearImmutableBit(scope) != LayoutCode.Schema) { + throw new LayoutCompilationException("Cannot have fixed storage within a sparse " + + "scope."); + } + + if (type.getIsNull() && !pp.getNullable()) { + throw new LayoutCompilationException("Non-nullable null columns are not supported" + + "."); + } + + builder.AddFixedColumn(p.getPath(), type, pp.getNullable(), pp.getLength()); + break; + case Variable: + if (LayoutCodeTraits.ClearImmutableBit(scope) != LayoutCode.Schema) { + throw new LayoutCompilationException("Cannot have variable storage within a " + + "sparse scope."); + } + + if (!pp.getNullable()) { + throw new LayoutCompilationException("Non-nullable variable columns are not " + + "supported."); + } + + builder.AddVariableColumn(p.getPath(), type, pp.getLength()); + break; + case Sparse: + if (!pp.getNullable()) { + throw new LayoutCompilationException("Non-nullable sparse columns are not " + + "supported."); + } + + builder.AddSparseColumn(p.getPath(), type); + break; + default: + throw new LayoutCompilationException(String.format("Unknown storage specification: " + + "%1$s", pp.getStorage())); + } + } else { + throw new LayoutCompilationException(String.format("Unknown property type: %1$s", + type.getName())); + } + + break; + } + } + } + } + + private static LayoutType LogicalToPhysicalType(Namespace ns, PropertyType logicalType, + tangible.OutObject typeArgs) { + typeArgs.argValue = TypeArgumentList.Empty; + boolean tempVar = + (logicalType instanceof ScopePropertyType ? (ScopePropertyType)logicalType : null).getImmutable(); + boolean immutable = + (logicalType instanceof ScopePropertyType ? (ScopePropertyType)logicalType : null) == null ? null : + tempVar != null && tempVar; + + switch (logicalType.getType()) { + case Null: + return LayoutType.Null; + case Boolean: + return LayoutType.Boolean; + case Int8: + return LayoutType.Int8; + case Int16: + return LayoutType.Int16; + case Int32: + return LayoutType.Int32; + case Int64: + return LayoutType.Int64; + case UInt8: + return LayoutType.UInt8; + case UInt16: + return LayoutType.UInt16; + case UInt32: + return LayoutType.UInt32; + case UInt64: + return LayoutType.UInt64; + case Float32: + return LayoutType.Float32; + case Float64: + return LayoutType.Float64; + case Float128: + return LayoutType.Float128; + case Decimal: + return LayoutType.Decimal; + case DateTime: + return LayoutType.DateTime; + case UnixDateTime: + return LayoutType.UnixDateTime; + case Guid: + return LayoutType.Guid; + case MongoDbObjectId: + return LayoutType.MongoDbObjectId; + case Utf8: + return LayoutType.Utf8; + case Binary: + return LayoutType.Binary; + case VarInt: + return LayoutType.VarInt; + case VarUInt: + return LayoutType.VarUInt; + + case Object: + return immutable ? LayoutType.ImmutableObject : LayoutType.Object; + case Array: + ArrayPropertyType ap = (ArrayPropertyType)logicalType; + if ((ap.getItems() != null) && (ap.getItems().getType() != TypeKind.Any)) { + TypeArgumentList itemTypeArgs = new TypeArgumentList(); + tangible.OutObject tempOut_itemTypeArgs = new tangible.OutObject(); + LayoutType itemType = LayoutCompiler.LogicalToPhysicalType(ns, ap.getItems(), tempOut_itemTypeArgs); + itemTypeArgs = tempOut_itemTypeArgs.argValue; + if (ap.getItems().getNullable()) { + itemTypeArgs = new TypeArgumentList(new TypeArgument[] { new TypeArgument(itemType, + itemTypeArgs.clone()) }); + itemType = itemType.Immutable ? LayoutType.ImmutableNullable : LayoutType.Nullable; + } + + typeArgs.argValue = new TypeArgumentList(new TypeArgument[] { new TypeArgument(itemType, + itemTypeArgs.clone()) }); + return immutable ? LayoutType.ImmutableTypedArray : LayoutType.TypedArray; + } + + return immutable ? LayoutType.ImmutableArray : LayoutType.Array; + case Set: + SetPropertyType sp = (SetPropertyType)logicalType; + if ((sp.getItems() != null) && (sp.getItems().getType() != TypeKind.Any)) { + TypeArgumentList itemTypeArgs = new TypeArgumentList(); + tangible.OutObject tempOut_itemTypeArgs2 = new tangible.OutObject(); + LayoutType itemType = LayoutCompiler.LogicalToPhysicalType(ns, sp.getItems(), + tempOut_itemTypeArgs2); + itemTypeArgs = tempOut_itemTypeArgs2.argValue; + if (sp.getItems().getNullable()) { + itemTypeArgs = new TypeArgumentList(new TypeArgument[] { new TypeArgument(itemType, + itemTypeArgs.clone()) }); + itemType = itemType.Immutable ? LayoutType.ImmutableNullable : LayoutType.Nullable; + } + + typeArgs.argValue = new TypeArgumentList(new TypeArgument[] { new TypeArgument(itemType, + itemTypeArgs.clone()) }); + return immutable ? LayoutType.ImmutableTypedSet : LayoutType.TypedSet; + } + + // TODO(283638): implement sparse set. + throw new LayoutCompilationException(String.format("Unknown property type: %1$s", + logicalType.getType())); + + case Map: + MapPropertyType mp = (MapPropertyType)logicalType; + if ((mp.getKeys() != null) && (mp.getKeys().getType() != TypeKind.Any) && (mp.getValues() != null) && (mp.getValues().getType() != TypeKind.Any)) { + TypeArgumentList keyTypeArgs = new TypeArgumentList(); + tangible.OutObject tempOut_keyTypeArgs = new tangible.OutObject(); + LayoutType keyType = LayoutCompiler.LogicalToPhysicalType(ns, mp.getKeys(), tempOut_keyTypeArgs); + keyTypeArgs = tempOut_keyTypeArgs.argValue; + if (mp.getKeys().getNullable()) { + keyTypeArgs = new TypeArgumentList(new TypeArgument[] { new TypeArgument(keyType, + keyTypeArgs.clone()) }); + keyType = keyType.Immutable ? LayoutType.ImmutableNullable : LayoutType.Nullable; + } + + TypeArgumentList valueTypeArgs = new TypeArgumentList(); + tangible.OutObject tempOut_valueTypeArgs = new tangible.OutObject(); + LayoutType valueType = LayoutCompiler.LogicalToPhysicalType(ns, mp.getValues(), + tempOut_valueTypeArgs); + valueTypeArgs = tempOut_valueTypeArgs.argValue; + if (mp.getValues().getNullable()) { + valueTypeArgs = new TypeArgumentList(new TypeArgument[] { new TypeArgument(valueType, + valueTypeArgs.clone()) }); + valueType = valueType.Immutable ? LayoutType.ImmutableNullable : LayoutType.Nullable; + } + + typeArgs.argValue = new TypeArgumentList(new TypeArgument[] + { + new TypeArgument(keyType, keyTypeArgs.clone()), + new TypeArgument(valueType, valueTypeArgs.clone()) + }); + return immutable ? LayoutType.ImmutableTypedMap : LayoutType.TypedMap; + } + + // TODO(283638): implement sparse map. + throw new LayoutCompilationException(String.format("Unknown property type: %1$s", + logicalType.getType())); + + case Tuple: + TuplePropertyType tp = (TuplePropertyType)logicalType; + TypeArgument[] args = new TypeArgument[tp.getItems().size()]; + for (int i = 0; i < tp.getItems().size(); i++) { + TypeArgumentList itemTypeArgs = new TypeArgumentList(); + tangible.OutObject tempOut_itemTypeArgs3 = new tangible.OutObject(); + LayoutType itemType = LayoutCompiler.LogicalToPhysicalType(ns, tp.getItems().get(i), + tempOut_itemTypeArgs3); + itemTypeArgs = tempOut_itemTypeArgs3.argValue; + if (tp.getItems().get(i).getNullable()) { + itemTypeArgs = new TypeArgumentList(new TypeArgument[] { new TypeArgument(itemType, + itemTypeArgs.clone()) }); + itemType = itemType.Immutable ? LayoutType.ImmutableNullable : LayoutType.Nullable; + } + + args[i] = new TypeArgument(itemType, itemTypeArgs.clone()); + } + + typeArgs.argValue = new TypeArgumentList(args); + return immutable ? LayoutType.ImmutableTypedTuple : LayoutType.TypedTuple; + + case Tagged: + TaggedPropertyType tg = (TaggedPropertyType)logicalType; + if ((tg.getItems().size() < TaggedPropertyType.MinTaggedArguments) || (tg.getItems().size() > TaggedPropertyType.MaxTaggedArguments)) { + throw new LayoutCompilationException(String.format("Invalid number of arguments in Tagged: %1$s " + + "<= %2$s <= %3$s", TaggedPropertyType.MinTaggedArguments, tg.getItems().size(), + TaggedPropertyType.MaxTaggedArguments)); + } + + TypeArgument[] tgArgs = new TypeArgument[tg.getItems().size() + 1]; + tgArgs[0] = new TypeArgument(LayoutType.UInt8, TypeArgumentList.Empty); + for (int i = 0; i < tg.getItems().size(); i++) { + TypeArgumentList itemTypeArgs = new TypeArgumentList(); + tangible.OutObject tempOut_itemTypeArgs4 = new tangible.OutObject(); + LayoutType itemType = LayoutCompiler.LogicalToPhysicalType(ns, tg.getItems().get(i), + tempOut_itemTypeArgs4); + itemTypeArgs = tempOut_itemTypeArgs4.argValue; + if (tg.getItems().get(i).getNullable()) { + itemTypeArgs = new TypeArgumentList(new TypeArgument[] { new TypeArgument(itemType, + itemTypeArgs.clone()) }); + itemType = itemType.Immutable ? LayoutType.ImmutableNullable : LayoutType.Nullable; + } + + tgArgs[i + 1] = new TypeArgument(itemType, itemTypeArgs.clone()); + } + + typeArgs.argValue = new TypeArgumentList(tgArgs); + switch (tg.getItems().size()) { + case 1: + return immutable ? LayoutType.ImmutableTagged : LayoutType.Tagged; + case 2: + return immutable ? LayoutType.ImmutableTagged2 : LayoutType.Tagged2; + default: + throw new LayoutCompilationException("Unexpected tagged arity"); + } + + case Schema: + UdtPropertyType up = (UdtPropertyType)logicalType; + Schema udtSchema; + if (azure.data.cosmos.serialization.hybridrow.SchemaId.opEquals(up.getSchemaId().clone(), + SchemaId.Invalid)) { + udtSchema = tangible.ListHelper.find(ns.getSchemas(), s = up.getName().equals( > s.Name)) + } else { + udtSchema = tangible.ListHelper.find(ns.getSchemas(), s = + azure.data.cosmos.serialization.hybridrow.SchemaId.opEquals( > s.SchemaId, + up.getSchemaId().clone())) + if (!udtSchema.getName().equals(up.getName())) { + throw new LayoutCompilationException(String.format("Ambiguous schema reference: '%1$s:%2$s'", + up.getName(), up.getSchemaId().clone())); + } + } + + if (udtSchema == null) { + throw new LayoutCompilationException(String.format("Cannot resolve schema reference '%1$s:%2$s'", + up.getName(), up.getSchemaId().clone())); + } + + typeArgs.argValue = new TypeArgumentList(udtSchema.getSchemaId().clone()); + return immutable ? LayoutType.ImmutableUDT : LayoutType.UDT; + + default: + throw new LayoutCompilationException(String.format("Unknown property type: %1$s", + logicalType.getType())); + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutDateTime.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutDateTime.java new file mode 100644 index 0000000..70ba623 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutDateTime.java @@ -0,0 +1,88 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.time.LocalDateTime; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutDateTime extends LayoutType { + public LayoutDateTime() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.DateTime, 8); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "datetime"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = LocalDateTime.MIN; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadDateTime(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = LocalDateTime.MIN; + return result; + } + + value.argValue = b.argValue.ReadSparseDateTime(edit); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + LocalDateTime value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteDateTime(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, DateTime value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + LocalDateTime value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseDateTime(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, DateTime value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutDecimal.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutDecimal.java new file mode 100644 index 0000000..0257514 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutDecimal.java @@ -0,0 +1,90 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.math.BigDecimal; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutDecimal extends LayoutType { + public LayoutDecimal() { + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'sizeof': + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Decimal, sizeof(BigDecimal)); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "decimal"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = new BigDecimal(0); + return Result.NotFound; + } + + value.argValue = b.argValue.ReadDecimal(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = new BigDecimal(0); + return result; + } + + value.argValue = b.argValue.ReadSparseDecimal(edit); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + BigDecimal value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteDecimal(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, decimal value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, BigDecimal value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseDecimal(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + java.math.BigDecimal value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutEndScope.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutEndScope.java new file mode 100644 index 0000000..17a8404 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutEndScope.java @@ -0,0 +1,43 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +public final class LayoutEndScope extends LayoutScope { + public LayoutEndScope() { + // TODO: C# TO JAVA CONVERTER: C# to Java Converter could not resolve the named parameters in the + // following line: + //ORIGINAL LINE: base(LayoutCode.EndScope, false, isSizedScope: false, isIndexedScope: false, isFixedArity: + // false, isUniqueScope: false, isTypedScope: false); + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.EndScope, false, isSizedScope:false, isIndexedScope:false, isFixedArity:false, isUniqueScope: + false, isTypedScope:false) + } + + @Override + public String getName() { + return "end"; + } + + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject scope, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, scope, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor scope, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject scope, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Contract.Fail("Cannot write an EndScope directly"); + value.argValue = null; + return Result.Failure; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat128.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat128.java new file mode 100644 index 0000000..e7efb86 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat128.java @@ -0,0 +1,87 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutFloat128 extends LayoutType { + public LayoutFloat128() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Float128, HybridRow.Float128.Size); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "float128"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = null; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadFloat128(scope.argValue.start + col.getOffset()).clone(); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + value.argValue = b.argValue.ReadSparseFloat128(edit).clone(); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + Float128 value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteFloat128(scope.argValue.start + col.getOffset(), value.clone()); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, Float128 value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, Float128 value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseFloat128(edit, value.clone(), options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, Float128 value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat32.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat32.java new file mode 100644 index 0000000..ef072da --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat32.java @@ -0,0 +1,86 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutFloat32 extends LayoutType { + public LayoutFloat32() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Float32, (Float.SIZE / Byte.SIZE)); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "float32"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadFloat32(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseFloat32(edit); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + float value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteFloat32(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, float value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, float value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseFloat32(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, float value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat64.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat64.java new file mode 100644 index 0000000..efb898b --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutFloat64.java @@ -0,0 +1,86 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutFloat64 extends LayoutType { + public LayoutFloat64() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Float64, (Double.SIZE / Byte.SIZE)); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "float64"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadFloat64(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseFloat64(edit); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + double value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteFloat64(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, double value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, double value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseFloat64(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, double value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutGuid.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutGuid.java new file mode 100644 index 0000000..8e3e2f8 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutGuid.java @@ -0,0 +1,89 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.util.UUID; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutGuid extends LayoutType { + public LayoutGuid() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Guid, 16); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "guid"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = null; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadGuid(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + value.argValue = b.argValue.ReadSparseGuid(edit); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + UUID value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteGuid(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, Guid value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, UUID value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseGuid(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + java.util.UUID value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutIndexedScope.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutIndexedScope.java new file mode 100644 index 0000000..a0d7b1b --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutIndexedScope.java @@ -0,0 +1,26 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +public abstract class LayoutIndexedScope extends LayoutScope { + protected LayoutIndexedScope(LayoutCode code, boolean immutable, boolean isSizedScope, boolean isFixedArity, + boolean isUniqueScope, boolean isTypedScope) { + // TODO: C# TO JAVA CONVERTER: C# to Java Converter could not resolve the named parameters in the + // following line: + //ORIGINAL LINE: base(code, immutable, isSizedScope, isIndexedScope: true, isFixedArity: isFixedArity, + // isUniqueScope: isUniqueScope, isTypedScope: isTypedScope); + super(code, immutable, isSizedScope, isIndexedScope:true, isFixedArity:isFixedArity, isUniqueScope: + isUniqueScope, isTypedScope:isTypedScope) + } + + @Override + public void ReadSparsePath(tangible.RefObject row, tangible.RefObject edit) { + edit.argValue.pathToken = 0; + edit.argValue.pathOffset = 0; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt16.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt16.java new file mode 100644 index 0000000..2a83dde --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt16.java @@ -0,0 +1,86 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutInt16 extends LayoutType { + public LayoutInt16() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Int16, (Short.SIZE / Byte.SIZE)); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "int16"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadInt16(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseInt16(edit); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + short value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteInt16(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, short value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, short value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseInt16(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, short value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt32.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt32.java new file mode 100644 index 0000000..720351c --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt32.java @@ -0,0 +1,86 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutInt32 extends LayoutType { + public LayoutInt32() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Int32, (Integer.SIZE / Byte.SIZE)); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "int32"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadInt32(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseInt32(edit); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + int value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteInt32(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, int value, UpdateOptions + // options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, int value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseInt32(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, int value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt64.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt64.java new file mode 100644 index 0000000..ad37b2e --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt64.java @@ -0,0 +1,86 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutInt64 extends LayoutType { + public LayoutInt64() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Int64, (Long.SIZE / Byte.SIZE)); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "int64"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadInt64(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseInt64(edit); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + long value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteInt64(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, long value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, long value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseInt64(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, long value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt8.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt8.java new file mode 100644 index 0000000..8734212 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutInt8.java @@ -0,0 +1,86 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutInt8 extends LayoutType { + public LayoutInt8() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Int8, (Byte.SIZE / Byte.SIZE)); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "int8"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadInt8(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseInt8(edit); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + byte value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteInt8(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, sbyte value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, byte value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseInt8(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, byte value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutMongoDbObjectId.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutMongoDbObjectId.java new file mode 100644 index 0000000..6163e84 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutMongoDbObjectId.java @@ -0,0 +1,88 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutMongoDbObjectId extends LayoutType { + public LayoutMongoDbObjectId() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.MongoDbObjectId, Microsoft.Azure.Cosmos.Serialization.HybridRow.MongoDbObjectId.Size); + } + + @Override + public boolean getIsFixed() { + return true; + } + + // ReSharper disable once StringLiteralTypo + @Override + public String getName() { + return "mongodbobjectid"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = null; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadMongoDbObjectId(scope.argValue.start + col.getOffset()).clone(); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + value.argValue = b.argValue.ReadSparseMongoDbObjectId(edit).clone(); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + MongoDbObjectId value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteMongoDbObjectId(scope.argValue.start + col.getOffset(), value.clone()); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, MongoDbObjectId value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + MongoDbObjectId value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseMongoDbObjectId(edit, value.clone(), options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, + MongoDbObjectId value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutNull.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutNull.java new file mode 100644 index 0000000..7c8d5c4 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutNull.java @@ -0,0 +1,90 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.NullValue; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutNull extends LayoutType { + public LayoutNull() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Null, 0); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public boolean getIsNull() { + return true; + } + + @Override + public String getName() { + return "null"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + value.argValue = NullValue.Default; + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + return Result.NotFound; + } + + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + value.argValue = b.argValue.ReadSparseNull(edit).clone(); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + NullValue value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, NullValue value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, NullValue value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseNull(edit, value.clone(), options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, NullValue value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutNullable.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutNullable.java new file mode 100644 index 0000000..4b7e14b --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutNullable.java @@ -0,0 +1,106 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableNullableScope; +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.NullableScope; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; + +public final class LayoutNullable extends LayoutIndexedScope { + public LayoutNullable(boolean immutable) { + super(immutable ? ImmutableNullableScope : NullableScope, immutable, true, true, false, true); + } + + @Override + public String getName() { + return this.Immutable ? "im_nullable" : "nullable"; + } + + @Override + public int CountTypeArgument(TypeArgumentList value) { + checkState(value.getCount() == 1); + return (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE) + value.get(0).getType().CountTypeArgument(value.get(0).getTypeArgs().clone()); + } + + @Override + public boolean HasImplicitTypeCode(tangible.RefObject edit) { + checkState(edit.argValue.index >= 0); + checkState(edit.argValue.scopeTypeArgs.getCount() == 1); + checkState(edit.argValue.index == 1); + return !LayoutCodeTraits.AlwaysRequiresTypeCode(edit.argValue.scopeTypeArgs.get(0).getType().LayoutCode); + } + + public static Result HasValue(tangible.RefObject b, tangible.RefObject scope) { + checkArgument(scope.argValue.scopeType instanceof LayoutNullable); + checkState(scope.argValue.index == 1 || scope.argValue.index == 2, "Nullable scopes always point at the value"); + checkState(scope.argValue.scopeTypeArgs.getCount() == 1); + boolean hasValue = b.argValue.ReadInt8(scope.argValue.start) != 0; + return hasValue ? Result.Success : Result.NotFound; + } + + @Override + public TypeArgumentList ReadTypeArgumentList(tangible.RefObject row, int offset, + tangible.OutObject lenInBytes) { + return new TypeArgumentList(new azure.data.cosmos.serialization.hybridrow.layouts.TypeArgument[] { LayoutType.ReadTypeArgument(row, offset, lenInBytes) }); + } + + @Override + public void SetImplicitTypeCode(tangible.RefObject edit) { + checkState(edit.argValue.index == 1); + edit.argValue.cellType = edit.argValue.scopeTypeArgs.get(0).getType(); + edit.argValue.cellTypeArgs = edit.argValue.scopeTypeArgs.get(0).getTypeArgs().clone(); + } + + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, boolean hasValue, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, hasValue, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList typeArgs, bool + // hasValue, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, boolean hasValue, tangible.OutObject value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, new TypeArgument(this, typeArgs.clone()), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteNullable(edit, this, typeArgs.clone(), options, hasValue, value.clone()); + return Result.Success; + } + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + return this.WriteScope(b, edit, typeArgs.clone(), true, value, options); + } + + @Override + public int WriteTypeArgument(tangible.RefObject row, int offset, TypeArgumentList value) { + checkState(value.getCount() == 1); + row.argValue.WriteSparseTypeCode(offset, this.LayoutCode); + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + lenInBytes += value.get(0).getType().WriteTypeArgument(row, offset + lenInBytes, + value.get(0).getTypeArgs().clone()); + return lenInBytes; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutObject.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutObject.java new file mode 100644 index 0000000..1368270 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutObject.java @@ -0,0 +1,50 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +public final class LayoutObject extends LayoutPropertyScope { + private TypeArgument TypeArg = new TypeArgument(); + + public LayoutObject(boolean immutable) { + super(immutable ? azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableObjectScope : azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ObjectScope, immutable); + this.TypeArg = new TypeArgument(this); + } + + @Override + public String getName() { + return this.Immutable ? "im_object" : "object"; + } + + public TypeArgument getTypeArg() { + return TypeArg; + } + + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteSparseObject(edit, this, options, value.clone()); + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutPropertyScope.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutPropertyScope.java new file mode 100644 index 0000000..6257af3 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutPropertyScope.java @@ -0,0 +1,14 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +public abstract class LayoutPropertyScope extends LayoutScope { + protected LayoutPropertyScope(LayoutCode code, boolean immutable) { + // TODO: C# TO JAVA CONVERTER: C# to Java Converter could not resolve the named parameters in the + // following line: + // base(code, immutable, isSizedScope: false, isIndexedScope: false, isFixedArity: false, isUniqueScope: false, isTypedScope: false); + super(code, immutable, false, false, false, false, false); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolver.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolver.java new file mode 100644 index 0000000..c172b0f --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolver.java @@ -0,0 +1,11 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +public abstract class LayoutResolver { + public abstract Layout Resolve(SchemaId schemaId); +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolverNamespace.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolverNamespace.java new file mode 100644 index 0000000..f95fb39 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolverNamespace.java @@ -0,0 +1,75 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.SchemaId; +import azure.data.cosmos.serialization.hybridrow.schemas.Namespace; +import azure.data.cosmos.serialization.hybridrow.schemas.Schema; + +/** + * An implementation of which dynamically compiles schema from + * a . + *

+ *

+ * This resolver assumes that within the have + * their properly populated. The resolver caches compiled schema. + *

+ * All members of this class are multi-thread safe. + */ +public final class LayoutResolverNamespace extends LayoutResolver { + private java.util.concurrent.ConcurrentHashMap layoutCache; + private LayoutResolver parent; + private Namespace schemaNamespace; + + + public LayoutResolverNamespace(Namespace schemaNamespace) { + this(schemaNamespace, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public LayoutResolverNamespace(Namespace schemaNamespace, LayoutResolver parent = default) + public LayoutResolverNamespace(Namespace schemaNamespace, LayoutResolver parent) { + this.schemaNamespace = schemaNamespace; + this.parent = parent; + this.layoutCache = new java.util.concurrent.ConcurrentHashMap(); + } + + public Namespace getNamespace() { + return this.schemaNamespace; + } + + @Override + public Layout Resolve(SchemaId schemaId) { + Layout layout; + // TODO: C# TO JAVA CONVERTER: There is no Java ConcurrentHashMap equivalent to this .NET + // ConcurrentDictionary method: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + if (this.layoutCache.TryGetValue(schemaId.getId(), out layout)) { + return layout; + } + + for (Schema s : this.schemaNamespace.getSchemas()) { + if (azure.data.cosmos.serialization.hybridrow.SchemaId.opEquals(s.getSchemaId().clone(), + schemaId.clone())) { + layout = s.Compile(this.schemaNamespace); + layout = this.layoutCache.putIfAbsent(schemaId.getId(), layout); + return layout; + } + } + + layout = this.parent == null ? null : this.parent.Resolve(schemaId.clone()); + if (layout != null) { + // TODO: C# TO JAVA CONVERTER: There is no Java ConcurrentHashMap equivalent to this .NET + // ConcurrentDictionary method: + boolean succeeded = this.layoutCache.TryAdd(schemaId.getId(), layout); + checkState(succeeded); + return layout; + } + + Contract.Fail(String.format("Failed to resolve schema %1$s", schemaId.clone())); + return null; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolverSimple.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolverSimple.java new file mode 100644 index 0000000..4b9384b --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutResolverSimple.java @@ -0,0 +1,20 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +public final class LayoutResolverSimple extends LayoutResolver { + private tangible.Func1Param resolver; + + public LayoutResolverSimple(tangible.Func1Param resolver) { + this.resolver = (SchemaId arg) -> resolver.invoke(arg); + } + + @Override + public Layout Resolve(SchemaId schemaId) { + return this.resolver.invoke(schemaId.clone()); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutScope.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutScope.java new file mode 100644 index 0000000..95f24bd --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutScope.java @@ -0,0 +1,157 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +public abstract class LayoutScope extends LayoutType { + /** + * Returns true if this is a fixed arity scope. + */ + public boolean IsFixedArity; + /** + * Returns true if this is an indexed scope. + */ + public boolean IsIndexedScope; + /** + * Returns true if this is a sized scope. + */ + public boolean IsSizedScope; + /** + * Returns true if this is a typed scope. + */ + public boolean IsTypedScope; + /** + * Returns true if the scope's elements cannot be updated directly. + */ + public boolean IsUniqueScope; + + protected LayoutScope(LayoutCode code, boolean immutable, boolean isSizedScope, boolean isIndexedScope, + boolean isFixedArity, boolean isUniqueScope, boolean isTypedScope) { + super(code, immutable, 0); + this.IsSizedScope = isSizedScope; + this.IsIndexedScope = isIndexedScope; + this.IsFixedArity = isFixedArity; + this.IsUniqueScope = isUniqueScope; + this.IsTypedScope = isTypedScope; + } + + @Override + public final boolean getIsFixed() { + return false; + } + + public final Result DeleteScope(tangible.RefObject b, tangible.RefObject edit) { + Result result = LayoutType.PrepareSparseDelete(b, edit, this.LayoutCode); + if (result != Result.Success) { + return result; + } + + b.argValue.DeleteSparse(edit); + return Result.Success; + } + + /** + * Returns true if writing an item in the specified typed scope would elide the type code + * because it is implied by the type arguments. + * + * @param edit + * @return True if the type code is implied (not written), false otherwise. + */ + public boolean HasImplicitTypeCode(tangible.RefObject edit) { + return false; + } + + public final Result ReadScope(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + value.argValue = b.argValue.SparseIteratorReadScope(edit, + this.Immutable || edit.argValue.immutable || edit.argValue.scopeType.IsUniqueScope).clone(); + return Result.Success; + } + + public void ReadSparsePath(tangible.RefObject row, tangible.RefObject edit) { + int pathLenInBytes; + tangible.OutObject tempOut_pathLenInBytes = new tangible.OutObject(); + tangible.OutObject tempOut_pathOffset = new tangible.OutObject(); + edit.argValue.pathToken = row.argValue.ReadSparsePathLen(edit.argValue.layout, edit.argValue.valueOffset, tempOut_pathLenInBytes, tempOut_pathOffset); + edit.argValue.argValue.pathOffset = tempOut_pathOffset.argValue; + pathLenInBytes = tempOut_pathLenInBytes.argValue; + edit.argValue.valueOffset += pathLenInBytes; + } + + public void SetImplicitTypeCode(tangible.RefObject edit) { + Contract.Fail("No implicit type codes."); + } + + public final abstract Result WriteScope(tangible.RefObject b, tangible.RefObject scope, + TypeArgumentList typeArgs, tangible.OutObject value); + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public abstract Result WriteScope(ref RowBuffer b, ref RowCursor scope, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert); + public abstract Result WriteScope(tangible.RefObject b, tangible.RefObject scope, + TypeArgumentList typeArgs, tangible.OutObject value, + UpdateOptions options); + + public Result WriteScope(tangible.RefObject b, tangible.RefObject scope, + TypeArgumentList typeArgs, TContext context, WriterFunc func) { + return WriteScope(b, scope, typeArgs, context, func, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public virtual Result WriteScope(ref RowBuffer b, ref RowCursor scope, + // TypeArgumentList typeArgs, TContext context, WriterFunc func, UpdateOptions options = UpdateOptions + // .Upsert) + public Result WriteScope(tangible.RefObject b, tangible.RefObject scope, + TypeArgumentList typeArgs, TContext context, WriterFunc func, + UpdateOptions options) { + RowCursor childScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = this.WriteScope(b, scope, typeArgs.clone(), out childScope, options); + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_childScope = + new tangible.RefObject(childScope); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + r = func == null ? null : func.Invoke(ref b, ref childScope, context) ??Result.Success; + childScope = tempRef_childScope.argValue; + if (r != Result.Success) { + this.DeleteScope(b, scope); + return r; + } + + tangible.RefObject tempRef_childScope2 = + new tangible.RefObject(childScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(scope.argValue.clone(), b, + tempRef_childScope2); + childScope = tempRef_childScope2.argValue; + return Result.Success; + } + + /** + * A function to write content into a . + * The type of the context value passed by the caller. + * + * @param b The row to write to. + * @param scope The type of the scope to write into. + * @param context A context value provided by the caller. + * @return The result. + */ + @FunctionalInterface + public interface WriterFunc { + Result invoke(tangible.RefObject b, tangible.RefObject scope, TContext context); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTagged.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTagged.java new file mode 100644 index 0000000..eaa6175 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTagged.java @@ -0,0 +1,83 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableTaggedScope; +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.TaggedScope; + +public final class LayoutTagged extends LayoutIndexedScope { + public LayoutTagged(boolean immutable) { + super(immutable ? ImmutableTaggedScope : TaggedScope, immutable, true, true, false, true); + } + + @Override + public String getName() { + return this.Immutable ? "im_tagged_t" : "tagged_t"; + } + + @Override + public int CountTypeArgument(TypeArgumentList value) { + checkState(value.getCount() == 2); + return (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE) + value.get(1).getType().CountTypeArgument(value.get(1).getTypeArgs().clone()); + } + + @Override + public boolean HasImplicitTypeCode(tangible.RefObject edit) { + Contract.Assert(edit.argValue.index >= 0); + Contract.Assert(edit.argValue.scopeTypeArgs.getCount() > edit.argValue.index); + return !LayoutCodeTraits.AlwaysRequiresTypeCode(edit.argValue.scopeTypeArgs.get(edit.argValue.index).getType().LayoutCode); + } + + @Override + public TypeArgumentList ReadTypeArgumentList(tangible.RefObject row, int offset, + tangible.OutObject lenInBytes) { + TypeArgument[] retval = new TypeArgument[2]; + retval[0] = new TypeArgument(LayoutType.UInt8, TypeArgumentList.Empty); + retval[1] = LayoutType.ReadTypeArgument(row, offset, lenInBytes); + return new TypeArgumentList(retval); + } + + @Override + public void SetImplicitTypeCode(tangible.RefObject edit) { + edit.argValue.cellType = edit.argValue.scopeTypeArgs.get(edit.argValue.index).getType(); + edit.argValue.cellTypeArgs = edit.argValue.scopeTypeArgs.get(edit.argValue.index).getTypeArgs().clone(); + } + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, new TypeArgument(this, typeArgs.clone()), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteTypedTuple(edit, this, typeArgs.clone(), options, value.clone()); + return Result.Success; + } + + @Override + public int WriteTypeArgument(tangible.RefObject row, int offset, TypeArgumentList value) { + Contract.Assert(value.getCount() == 2); + row.argValue.WriteSparseTypeCode(offset, this.LayoutCode); + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + lenInBytes += value.get(1).getType().WriteTypeArgument(row, offset + lenInBytes, + value.get(1).getTypeArgs().clone()); + return lenInBytes; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTagged2.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTagged2.java new file mode 100644 index 0000000..cd07dee --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTagged2.java @@ -0,0 +1,98 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +public final class LayoutTagged2 extends LayoutIndexedScope { + public LayoutTagged2(boolean immutable) { + super(immutable ? azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableTagged2Scope : azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Tagged2Scope, immutable, isSizedScope: + true, isFixedArity:true, isUniqueScope:false, isTypedScope:true) + } + + @Override + public String getName() { + return this.Immutable ? "im_tagged2_t" : "tagged2_t"; + } + + @Override + public int CountTypeArgument(TypeArgumentList value) { + checkState(value.getCount() == 3); + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + for (int i = 1; i < value.getCount(); i++) { + TypeArgument arg = value.get(i).clone(); + lenInBytes += arg.getType().CountTypeArgument(arg.getTypeArgs().clone()); + } + + return lenInBytes; + } + + @Override + public boolean HasImplicitTypeCode(tangible.RefObject edit) { + checkState(edit.argValue.index >= 0); + checkState(edit.argValue.scopeTypeArgs.getCount() > edit.argValue.index); + return !LayoutCodeTraits.AlwaysRequiresTypeCode(edit.argValue.scopeTypeArgs.get(edit.argValue.index).getType().LayoutCode); + } + + @Override + public TypeArgumentList ReadTypeArgumentList(tangible.RefObject row, int offset, + tangible.OutObject lenInBytes) { + lenInBytes.argValue = 0; + TypeArgument[] retval = new TypeArgument[3]; + retval[0] = new TypeArgument(LayoutType.UInt8, TypeArgumentList.Empty); + for (int i = 1; i < 3; i++) { + int itemLenInBytes; + tangible.OutObject tempOut_itemLenInBytes = new tangible.OutObject(); + retval[i] = LayoutType.ReadTypeArgument(row, offset + lenInBytes.argValue, tempOut_itemLenInBytes); + itemLenInBytes = tempOut_itemLenInBytes.argValue; + lenInBytes.argValue += itemLenInBytes; + } + + return new TypeArgumentList(retval); + } + + @Override + public void SetImplicitTypeCode(tangible.RefObject edit) { + edit.argValue.cellType = edit.argValue.scopeTypeArgs.get(edit.argValue.index).getType(); + edit.argValue.cellTypeArgs = edit.argValue.scopeTypeArgs.get(edit.argValue.index).getTypeArgs().clone(); + } + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, new TypeArgument(this, typeArgs.clone()), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteTypedTuple(edit, this, typeArgs.clone(), options, value.clone()); + return Result.Success; + } + + @Override + public int WriteTypeArgument(tangible.RefObject row, int offset, TypeArgumentList value) { + checkState(value.getCount() == 3); + row.argValue.WriteSparseTypeCode(offset, this.LayoutCode); + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + for (int i = 1; i < value.getCount(); i++) { + TypeArgument arg = value.get(i).clone(); + lenInBytes += arg.getType().WriteTypeArgument(row, offset + lenInBytes, arg.getTypeArgs().clone()); + } + + return lenInBytes; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTuple.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTuple.java new file mode 100644 index 0000000..46e5070 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTuple.java @@ -0,0 +1,86 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +public final class LayoutTuple extends LayoutIndexedScope { + public LayoutTuple(boolean immutable) { + super(immutable ? azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableTupleScope : azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.TupleScope, immutable, isSizedScope: + false, isFixedArity:true, isUniqueScope:false, isTypedScope:false) + } + + @Override + public String getName() { + return this.Immutable ? "im_tuple" : "tuple"; + } + + @Override + public int CountTypeArgument(TypeArgumentList value) { + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: lenInBytes += RowBuffer.Count7BitEncodedUInt((ulong)value.Count); + lenInBytes += RowBuffer.Count7BitEncodedUInt(value.getCount()); + for (TypeArgument arg : value) { + lenInBytes += arg.getType().CountTypeArgument(arg.getTypeArgs().clone()); + } + + return lenInBytes; + } + + @Override + public TypeArgumentList ReadTypeArgumentList(tangible.RefObject row, int offset, + tangible.OutObject lenInBytes) { + int numTypeArgs = row.argValue.intValue().Read7BitEncodedUInt(offset, lenInBytes); + TypeArgument[] retval = new TypeArgument[numTypeArgs]; + for (int i = 0; i < numTypeArgs; i++) { + int itemLenInBytes; + tangible.OutObject tempOut_itemLenInBytes = new tangible.OutObject(); + retval[i] = LayoutType.ReadTypeArgument(row, offset + lenInBytes.argValue, tempOut_itemLenInBytes); + itemLenInBytes = tempOut_itemLenInBytes.argValue; + lenInBytes.argValue += itemLenInBytes; + } + + return new TypeArgumentList(retval); + } + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, new TypeArgument(this, typeArgs.clone()), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteSparseTuple(edit, this, typeArgs.clone(), options, value.clone()); + return Result.Success; + } + + @Override + public int WriteTypeArgument(tangible.RefObject row, int offset, TypeArgumentList value) { + row.argValue.WriteSparseTypeCode(offset, this.LayoutCode); + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: lenInBytes += row.Write7BitEncodedUInt(offset + lenInBytes, (ulong)value.Count); + lenInBytes += row.argValue.Write7BitEncodedUInt(offset + lenInBytes, value.getCount()); + for (TypeArgument arg : value) { + lenInBytes += arg.getType().WriteTypeArgument(row, offset + lenInBytes, arg.getTypeArgs().clone()); + } + + return lenInBytes; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutType.java new file mode 100644 index 0000000..46651d1 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutType.java @@ -0,0 +1,525 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1402 // FileMayOnlyContainASingleType +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1201 // Elements should appear in the correct order +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Fields should be private +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1040 // Avoid empty interfaces +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1051 // Do not declare visible instance fields + + +/** + * The abstract base class for typed hybrid row field descriptors. + * is immutable. + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [DebuggerDisplay("{" + nameof(LayoutType.Name) + "}")] public abstract class LayoutType : ILayoutType +public abstract class LayoutType implements ILayoutType { + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutArray Array = new LayoutArray(immutable: + // false); + public static final LayoutArray Array = new LayoutArray(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutBinary Binary = new LayoutBinary(); + public static final LayoutBinary Binary = new LayoutBinary(); + /** + * The number of bits in a single byte on the current architecture. + */ + public static final int BitsPerByte = 8; + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutBoolean Boolean = new LayoutBoolean(true); + public static final LayoutBoolean Boolean = new LayoutBoolean(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutBoolean BooleanFalse = new LayoutBoolean + // (false); + public static final LayoutBoolean BooleanFalse = new LayoutBoolean(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutDateTime DateTime = new LayoutDateTime(); + public static final LayoutDateTime DateTime = new LayoutDateTime(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutDecimal Decimal = new LayoutDecimal(); + public static final LayoutDecimal Decimal = new LayoutDecimal(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] internal static readonly LayoutEndScope EndScope = new LayoutEndScope(); + public static final LayoutEndScope EndScope = new LayoutEndScope(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutFloat128 Float128 = new LayoutFloat128(); + public static final LayoutFloat128 Float128 = new LayoutFloat128(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutFloat32 Float32 = new LayoutFloat32(); + public static final LayoutFloat32 Float32 = new LayoutFloat32(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutFloat64 Float64 = new LayoutFloat64(); + public static final LayoutFloat64 Float64 = new LayoutFloat64(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutArray ImmutableArray = new LayoutArray + // (immutable: true); + public static final LayoutArray ImmutableArray = new LayoutArray(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutNullable ImmutableNullable = new + // LayoutNullable(immutable: true); + public static final LayoutNullable ImmutableNullable = new LayoutNullable(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutObject ImmutableObject = new LayoutObject + // (immutable: true); + public static final LayoutObject ImmutableObject = new LayoutObject(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTagged ImmutableTagged = new LayoutTagged + // (immutable: true); + public static final LayoutTagged ImmutableTagged = new LayoutTagged(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTagged2 ImmutableTagged2 = new + // LayoutTagged2(immutable: true); + public static final LayoutTagged2 ImmutableTagged2 = new LayoutTagged2(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTuple ImmutableTuple = new LayoutTuple + // (immutable: true); + public static final LayoutTuple ImmutableTuple = new LayoutTuple(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTypedArray ImmutableTypedArray = new + // LayoutTypedArray(immutable: true); + public static final LayoutTypedArray ImmutableTypedArray = new LayoutTypedArray(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTypedMap ImmutableTypedMap = new + // LayoutTypedMap(immutable: true); + public static final LayoutTypedMap ImmutableTypedMap = new LayoutTypedMap(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTypedSet ImmutableTypedSet = new + // LayoutTypedSet(immutable: true); + public static final LayoutTypedSet ImmutableTypedSet = new LayoutTypedSet(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTypedTuple ImmutableTypedTuple = new + // LayoutTypedTuple(immutable: true); + public static final LayoutTypedTuple ImmutableTypedTuple = new LayoutTypedTuple(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUDT ImmutableUDT = new LayoutUDT + // (immutable: true); + public static final LayoutUDT ImmutableUDT = new LayoutUDT(true); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutInt16 Int16 = new LayoutInt16(); + public static final LayoutInt16 Int16 = new LayoutInt16(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutInt32 Int32 = new LayoutInt32(); + public static final LayoutInt32 Int32 = new LayoutInt32(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutInt64 Int64 = new LayoutInt64(); + public static final LayoutInt64 Int64 = new LayoutInt64(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutInt8 Int8 = new LayoutInt8(); + public static final LayoutInt8 Int8 = new LayoutInt8(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutMongoDbObjectId MongoDbObjectId = new + // LayoutMongoDbObjectId(); + public static final LayoutMongoDbObjectId MongoDbObjectId = new LayoutMongoDbObjectId(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutNull Null = new LayoutNull(); + public static final LayoutNull Null = new LayoutNull(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutNullable Nullable = new LayoutNullable + // (immutable: false); + public static final LayoutNullable Nullable = new LayoutNullable(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutObject Object = new LayoutObject + // (immutable: false); + public static final LayoutObject Object = new LayoutObject(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTagged Tagged = new LayoutTagged + // (immutable: false); + public static final LayoutTagged Tagged = new LayoutTagged(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTagged2 Tagged2 = new LayoutTagged2 + // (immutable: false); + public static final LayoutTagged2 Tagged2 = new LayoutTagged2(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTuple Tuple = new LayoutTuple(immutable: + // false); + public static final LayoutTuple Tuple = new LayoutTuple(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTypedArray TypedArray = new + // LayoutTypedArray(immutable: false); + public static final LayoutTypedArray TypedArray = new LayoutTypedArray(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTypedMap TypedMap = new LayoutTypedMap + // (immutable: false); + public static final LayoutTypedMap TypedMap = new LayoutTypedMap(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTypedSet TypedSet = new LayoutTypedSet + // (immutable: false); + public static final LayoutTypedSet TypedSet = new LayoutTypedSet(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutTypedTuple TypedTuple = new + // LayoutTypedTuple(immutable: false); + public static final LayoutTypedTuple TypedTuple = new LayoutTypedTuple(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUDT UDT = new LayoutUDT(immutable: false); + public static final LayoutUDT UDT = new LayoutUDT(false); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUInt16 UInt16 = new LayoutUInt16(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUInt16 UInt16 = new LayoutUInt16(); + public static final LayoutUInt16 UInt16 = new LayoutUInt16(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUInt32 UInt32 = new LayoutUInt32(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUInt32 UInt32 = new LayoutUInt32(); + public static final LayoutUInt32 UInt32 = new LayoutUInt32(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUInt64 UInt64 = new LayoutUInt64(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUInt64 UInt64 = new LayoutUInt64(); + public static final LayoutUInt64 UInt64 = new LayoutUInt64(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUInt8 UInt8 = new LayoutUInt8(); + public static final LayoutUInt8 UInt8 = new LayoutUInt8(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutGuid Guid = new LayoutGuid(); + public static final LayoutGuid Guid = new LayoutGuid(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUnixDateTime UnixDateTime = new + // LayoutUnixDateTime(); + public static final LayoutUnixDateTime UnixDateTime = new LayoutUnixDateTime(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutUtf8 Utf8 = new LayoutUtf8(); + public static final LayoutUtf8 Utf8 = new LayoutUtf8(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutVarInt VarInt = new LayoutVarInt(); + public static final LayoutVarInt VarInt = new LayoutVarInt(); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutVarUInt VarUInt = new LayoutVarUInt(); + public static final LayoutVarUInt VarUInt = new LayoutVarUInt(); + private static final LayoutType[] CodeIndex = new LayoutType[azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.EndScope.getValue() + 1]; + /** + * If true, this edit's nested fields cannot be updated individually. + * The entire edit can still be replaced. + */ + public boolean Immutable; + /** + * The physical layout code used to represent the type within the serialization. + */ + public LayoutCode LayoutCode = azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.values()[0]; + /** + * If fixed, the fixed size of the type's serialization in bytes, otherwise undefined. + */ + public int Size; + + /** + * Initializes a new instance of the class. + */ + public LayoutType(LayoutCode code, boolean immutable, int size) { + this.LayoutCode = code; + this.Immutable = immutable; + this.Size = size; + LayoutType.CodeIndex[code.getValue()] = this; + } + + /** + * True if this type can be used in the variable-length segment. + */ + public final boolean getAllowVariable() { + return !this.getIsFixed(); + } + + /** + * True if this type is a boolean. + */ + public boolean getIsBool() { + return false; + } + + /** + * True if this type is always fixed length. + */ + public abstract boolean getIsFixed(); + + /** + * True if this type is a literal null. + */ + public boolean getIsNull() { + return false; + } + + /** + * True if this type is a variable-length encoded integer type (either signed or unsigned). + */ + public boolean getIsVarint() { + return false; + } + + /** + * Human readable name of the type. + */ + public abstract String getName(); + + public int CountTypeArgument(TypeArgumentList value) { + return (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static LayoutType FromCode + // (LayoutCode code) + public static LayoutType FromCode(LayoutCode code) { + LayoutType type = LayoutType.CodeIndex[code.getValue()]; + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + if (type == null) { + Contract.Fail(String.format("Not Implemented: %1$s", code)); + } + //#endif + + return type; + } + + /** + * Helper for preparing the delete of a sparse field. + * + * @param b The row to delete from. + * @param edit The parent edit containing the field to delete. + * @param code The expected type of the field. + * @return Success if the delete is permitted, the error code otherwise. + */ + public static Result PrepareSparseDelete(tangible.RefObject b, tangible.RefObject edit, + LayoutCode code) { + if (edit.argValue.scopeType.IsFixedArity) { + return Result.TypeConstraint; + } + + if (edit.argValue.immutable) { + return Result.InsufficientPermissions; + } + + if (edit.argValue.exists && LayoutCodeTraits.Canonicalize(edit.argValue.cellType.LayoutCode) != code) { + return Result.TypeMismatch; + } + + return Result.Success; + } + + /** + * Helper for preparing the move of a sparse field into an existing restricted edit. + * + * @param b The row to read from. + * @param destinationScope The parent set edit into which the field should be moved. + * @param destinationCode The expected type of the edit moving within. + * @param elementType The expected type of the elements within the edit. + * @param srcEdit The field to be moved. + * @param options The move options. + * @param dstEdit If successful, a prepared insertion cursor for the destination. + * @return Success if the move is permitted, the error code otherwise. + * The source field is delete if the move prepare fails with a destination error. + */ + public static Result PrepareSparseMove(tangible.RefObject b, + tangible.RefObject destinationScope, + LayoutScope destinationCode, TypeArgument elementType, + tangible.RefObject srcEdit, UpdateOptions options, + tangible.OutObject dstEdit) { + checkArgument(destinationScope.argValue.scopeType == destinationCode); + checkArgument(destinationScope.argValue.index == 0, "Can only insert into a edit at the root"); + + // Prepare the delete of the source. + Result result = LayoutType.PrepareSparseDelete(b, srcEdit, elementType.getType().LayoutCode); + if (result != Result.Success) { + dstEdit.argValue = null; + return result; + } + + if (!srcEdit.argValue.exists) { + dstEdit.argValue = null; + return Result.NotFound; + } + + if (destinationScope.argValue.immutable) { + b.argValue.DeleteSparse(srcEdit); + dstEdit.argValue = null; + return Result.InsufficientPermissions; + } + + if (!srcEdit.argValue.cellTypeArgs.equals(elementType.getTypeArgs().clone())) { + b.argValue.DeleteSparse(srcEdit); + dstEdit.argValue = null; + return Result.TypeConstraint; + } + + if (options == UpdateOptions.InsertAt) { + b.argValue.DeleteSparse(srcEdit); + dstEdit.argValue = null; + return Result.TypeConstraint; + } + + // Prepare the insertion at the destination. + dstEdit.argValue = b.argValue.PrepareSparseMove(destinationScope, srcEdit).clone(); + if ((options == UpdateOptions.Update) && (!dstEdit.argValue.exists)) { + b.argValue.DeleteSparse(srcEdit); + dstEdit.argValue = null; + return Result.NotFound; + } + + if ((options == UpdateOptions.Insert) && dstEdit.argValue.exists) { + b.argValue.DeleteSparse(srcEdit); + dstEdit.argValue = null; + return Result.Exists; + } + + return Result.Success; + } + + /** + * Helper for preparing the read of a sparse field. + * + * @param b The row to read from. + * @param edit The parent edit containing the field to read. + * @param code The expected type of the field. + * @return Success if the read is permitted, the error code otherwise. + */ + public static Result PrepareSparseRead(tangible.RefObject b, tangible.RefObject edit, + LayoutCode code) { + if (!edit.argValue.exists) { + return Result.NotFound; + } + + if (LayoutCodeTraits.Canonicalize(edit.argValue.cellType.LayoutCode) != code) { + return Result.TypeMismatch; + } + + return Result.Success; + } + + /** + * Helper for preparing the write of a sparse field. + * + * @param b The row to write to. + * @param edit The cursor for the field to write. + * @param typeArg The (optional) type constraints. + * @param options The write options. + * @return Success if the write is permitted, the error code otherwise. + */ + public static Result PrepareSparseWrite(tangible.RefObject b, tangible.RefObject edit, + TypeArgument typeArg, UpdateOptions options) { + if (edit.argValue.immutable || (edit.argValue.scopeType.IsUniqueScope && !edit.argValue.deferUniqueIndex)) { + return Result.InsufficientPermissions; + } + + if (edit.argValue.scopeType.IsFixedArity && !(edit.argValue.scopeType instanceof LayoutNullable)) { + if ((edit.argValue.index < edit.argValue.scopeTypeArgs.getCount()) && !typeArg.equals(edit.argValue.scopeTypeArgs.get(edit.argValue.index).clone())) { + return Result.TypeConstraint; + } + } else if (edit.argValue.scopeType instanceof LayoutTypedMap) { + if (!((typeArg.getType() instanceof LayoutTypedTuple) && typeArg.getTypeArgs().equals(edit.argValue.scopeTypeArgs.clone()))) { + return Result.TypeConstraint; + } + } else if (edit.argValue.scopeType.IsTypedScope && !typeArg.equals(edit.argValue.scopeTypeArgs.get(0).clone())) { + return Result.TypeConstraint; + } + + if ((options == UpdateOptions.InsertAt) && edit.argValue.scopeType.IsFixedArity) { + return Result.TypeConstraint; + } + + if ((options == UpdateOptions.InsertAt) && !edit.argValue.scopeType.IsFixedArity) { + edit.argValue.exists = false; // InsertAt never overwrites an existing item. + } + + if ((options == UpdateOptions.Update) && (!edit.argValue.exists)) { + return Result.NotFound; + } + + if ((options == UpdateOptions.Insert) && edit.argValue.exists) { + return Result.Exists; + } + + return Result.Success; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static TypeArgument ReadTypeArgument(ref RowBuffer row, int offset, out int lenInBytes) + public static TypeArgument ReadTypeArgument(tangible.RefObject row, int offset, tangible.OutObject lenInBytes) { + LayoutType itemCode = row.argValue.ReadSparseTypeCode(offset); + int argsLenInBytes; + tangible.OutObject tempOut_argsLenInBytes = new tangible.OutObject(); + TypeArgumentList itemTypeArgs = itemCode.ReadTypeArgumentList(row, offset + (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE), tempOut_argsLenInBytes).clone(); + argsLenInBytes = tempOut_argsLenInBytes.argValue; + lenInBytes.argValue = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE) + argsLenInBytes; + return new TypeArgument(itemCode, itemTypeArgs.clone()); + } + + public TypeArgumentList ReadTypeArgumentList(tangible.RefObject row, int offset, tangible.OutObject lenInBytes) { + lenInBytes.argValue = 0; + return TypeArgumentList.Empty; + } + + /** + * The physical layout type of the field cast to the specified type. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DebuggerHidden] public T TypeAs() where T : ILayoutType + public final T TypeAs() { + return (T)this; + } + + public int WriteTypeArgument(tangible.RefObject row, int offset, TypeArgumentList value) { + row.argValue.WriteSparseTypeCode(offset, this.LayoutCode); + return (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutType1.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutType1.java new file mode 100644 index 0000000..3ffdb33 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutType1.java @@ -0,0 +1,124 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +/** + * Describes the physical byte layout of a hybrid row field of a specific physical type + * . + * + * + * is an immutable, stateless, helper class. It provides + * methods for manipulating hybrid row fields of a particular type, and properties that describe the + * layout of fields of that type. + * + * is immutable. + */ +public abstract class LayoutType extends LayoutType { + private TypeArgument typeArg = new TypeArgument(); + + public LayoutType(LayoutCode code, int size) { + super(code, false, size); + this.typeArg = new TypeArgument(this); + } + + public final Result DeleteFixed(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + if (col.getNullBit().getIsInvalid()) { + // Cannot delete a non-nullable fixed column. + return Result.TypeMismatch; + } + + b.argValue.UnsetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + /** + * Delete an existing value. + *

+ * If a value exists, then it is removed. The remainder of the row is resized to accomodate + * a decrease in required space. If no value exists this operation is a no-op. + */ + public final Result DeleteSparse(tangible.RefObject b, tangible.RefObject edit) { + Result result = LayoutType.PrepareSparseDelete(b, edit, this.LayoutCode); + if (result != Result.Success) { + return result; + } + + b.argValue.DeleteSparse(edit); + return Result.Success; + } + + /** + * Delete an existing value. + *

+ * If a value exists, then it is removed. The remainder of the row is resized to accomodate + * a decrease in required space. If no value exists this operation is a no-op. + */ + public final Result DeleteVariable(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + boolean exists = b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone()); + if (exists) { + int varOffset = b.argValue.ComputeVariableValueOffset(scope.argValue.layout, scope.argValue.start, + col.getOffset()); + b.argValue.DeleteVariable(varOffset, this.getIsVarint()); + b.argValue.UnsetBit(scope.argValue.start, col.getNullBit().clone()); + } + + return Result.Success; + } + + public final Result HasValue(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col) { + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + return Result.NotFound; + } + + return Result.Success; + } + + public abstract Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col, tangible.OutObject value); + + public abstract Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, tangible.OutObject value); + + public Result ReadVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col + , tangible.OutObject value) { + value.argValue = null; + return Result.Failure; + } + + public abstract Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col, T value); + + public abstract Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, T value); + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public abstract Result WriteSparse(ref RowBuffer b, ref RowCursor edit, T value, UpdateOptions + // options = UpdateOptions.Upsert); + public abstract Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, T value, UpdateOptions options); + + public Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col, T value) { + return Result.Failure; + } + + abstract TypeArgument getTypeArg(); +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedArray.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedArray.java new file mode 100644 index 0000000..fb6a336 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedArray.java @@ -0,0 +1,81 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableTypedArrayScope; +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE; +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.TypedArrayScope; + +public final class LayoutTypedArray extends LayoutIndexedScope { + public LayoutTypedArray(boolean immutable) { + super(immutable ? ImmutableTypedArrayScope : TypedArrayScope, immutable, true, false, false, true); + } + + @Override + public String getName() { + return this.Immutable ? "im_array_t" : "array_t"; + } + + @Override + public int CountTypeArgument(TypeArgumentList value) { + checkState(value.getCount() == 1); + return (SIZE / Byte.SIZE) + value.get(0).getType().CountTypeArgument(value.get(0).getTypeArgs().clone()); + } + + @Override + public boolean HasImplicitTypeCode(tangible.RefObject edit) { + checkState(edit.argValue.index >= 0); + checkState(edit.argValue.scopeTypeArgs.getCount() == 1); + return !LayoutCodeTraits.AlwaysRequiresTypeCode(edit.argValue.scopeTypeArgs.get(0).getType().LayoutCode); + } + + @Override + public TypeArgumentList ReadTypeArgumentList(tangible.RefObject row, int offset, + tangible.OutObject lenInBytes) { + return new TypeArgumentList(new azure.data.cosmos.serialization.hybridrow.layouts.TypeArgument[] { LayoutType.ReadTypeArgument(row, offset, lenInBytes) }); + } + + @Override + public void SetImplicitTypeCode(tangible.RefObject edit) { + edit.argValue.cellType = edit.argValue.scopeTypeArgs.get(0).getType(); + edit.argValue.cellTypeArgs = edit.argValue.scopeTypeArgs.get(0).getTypeArgs().clone(); + } + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, new TypeArgument(this, typeArgs.clone()), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteTypedArray(edit, this, typeArgs.clone(), options, value.clone()); + return Result.Success; + } + + @Override + public int WriteTypeArgument(tangible.RefObject row, int offset, TypeArgumentList value) { + checkState(value.getCount() == 1); + row.argValue.WriteSparseTypeCode(offset, this.LayoutCode); + int lenInBytes = (SIZE / Byte.SIZE); + lenInBytes += value.get(0).getType().WriteTypeArgument(row, offset + lenInBytes, + value.get(0).getTypeArgs().clone()); + return lenInBytes; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedMap.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedMap.java new file mode 100644 index 0000000..cc78a97 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedMap.java @@ -0,0 +1,100 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +public final class LayoutTypedMap extends LayoutUniqueScope { + public LayoutTypedMap(boolean immutable) { + super(immutable ? azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableTypedMapScope : azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.TypedMapScope, immutable, isSizedScope: + true, isTypedScope:true) + } + + @Override + public String getName() { + return this.Immutable ? "im_map_t" : "map_t"; + } + + @Override + public int CountTypeArgument(TypeArgumentList value) { + checkState(value.getCount() == 2); + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + for (TypeArgument arg : value) { + lenInBytes += arg.getType().CountTypeArgument(arg.getTypeArgs().clone()); + } + + return lenInBytes; + } + + @Override + public TypeArgument FieldType(tangible.RefObject scope) { + return new TypeArgument(scope.argValue.scopeType.Immutable ? LayoutType.ImmutableTypedTuple : + LayoutType.TypedTuple, scope.argValue.scopeTypeArgs.clone()); + } + + @Override + public boolean HasImplicitTypeCode(tangible.RefObject edit) { + return true; + } + + @Override + public TypeArgumentList ReadTypeArgumentList(tangible.RefObject row, int offset, + tangible.OutObject lenInBytes) { + lenInBytes.argValue = 0; + TypeArgument[] retval = new TypeArgument[2]; + for (int i = 0; i < 2; i++) { + int itemLenInBytes; + tangible.OutObject tempOut_itemLenInBytes = new tangible.OutObject(); + retval[i] = LayoutType.ReadTypeArgument(row, offset + lenInBytes.argValue, tempOut_itemLenInBytes); + itemLenInBytes = tempOut_itemLenInBytes.argValue; + lenInBytes.argValue += itemLenInBytes; + } + + return new TypeArgumentList(retval); + } + + @Override + public void SetImplicitTypeCode(tangible.RefObject edit) { + edit.argValue.cellType = edit.argValue.scopeType.Immutable ? LayoutType.ImmutableTypedTuple : + LayoutType.TypedTuple; + edit.argValue.cellTypeArgs = edit.argValue.scopeTypeArgs.clone(); + } + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, new TypeArgument(this, typeArgs.clone()), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteTypedMap(edit, this, typeArgs.clone(), options, value.clone()); + return Result.Success; + } + + @Override + public int WriteTypeArgument(tangible.RefObject row, int offset, TypeArgumentList value) { + checkState(value.getCount() == 2); + row.argValue.WriteSparseTypeCode(offset, this.LayoutCode); + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + for (TypeArgument arg : value) { + lenInBytes += arg.getType().WriteTypeArgument(row, offset + lenInBytes, arg.getTypeArgs().clone()); + } + + return lenInBytes; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedSet.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedSet.java new file mode 100644 index 0000000..52af67b --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedSet.java @@ -0,0 +1,85 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableTypedSetScope; +import static azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.TypedSetScope; + +public final class LayoutTypedSet extends LayoutUniqueScope { + public LayoutTypedSet(boolean immutable) { + super(immutable ? ImmutableTypedSetScope : TypedSetScope, immutable, true, true); + } + + @Override + public String getName() { + return this.Immutable ? "im_set_t" : "set_t"; + } + + @Override + public int CountTypeArgument(TypeArgumentList value) { + checkState(value.getCount() == 1); + return (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE) + value.get(0).getType().CountTypeArgument(value.get(0).getTypeArgs().clone()); + } + + @Override + public TypeArgument FieldType(tangible.RefObject scope) { + return scope.argValue.scopeTypeArgs.get(0).clone(); + } + + @Override + public boolean HasImplicitTypeCode(tangible.RefObject edit) { + checkState(edit.argValue.index >= 0); + checkState(edit.argValue.scopeTypeArgs.getCount() == 1); + return !LayoutCodeTraits.AlwaysRequiresTypeCode(edit.argValue.scopeTypeArgs.get(0).getType().LayoutCode); + } + + @Override + public TypeArgumentList ReadTypeArgumentList(tangible.RefObject row, int offset, + tangible.OutObject lenInBytes) { + return new TypeArgumentList(new azure.data.cosmos.serialization.hybridrow.layouts.TypeArgument[] { LayoutType.ReadTypeArgument(row, offset, lenInBytes) }); + } + + @Override + public void SetImplicitTypeCode(tangible.RefObject edit) { + edit.argValue.cellType = edit.argValue.scopeTypeArgs.get(0).getType(); + edit.argValue.cellTypeArgs = edit.argValue.scopeTypeArgs.get(0).getTypeArgs().clone(); + } + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, new TypeArgument(this, typeArgs.clone()), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteTypedSet(edit, this, typeArgs.clone(), options, value.clone()); + return Result.Success; + } + + @Override + public int WriteTypeArgument(tangible.RefObject row, int offset, TypeArgumentList value) { + Contract.Assert(value.getCount() == 1); + row.argValue.WriteSparseTypeCode(offset, this.LayoutCode); + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + lenInBytes += value.get(0).getType().WriteTypeArgument(row, offset + lenInBytes, + value.get(0).getTypeArgs().clone()); + return lenInBytes; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedTuple.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedTuple.java new file mode 100644 index 0000000..f0badbb --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutTypedTuple.java @@ -0,0 +1,99 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +public final class LayoutTypedTuple extends LayoutIndexedScope { + public LayoutTypedTuple(boolean immutable) { + super(immutable ? azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableTypedTupleScope : azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.TypedTupleScope, immutable, isSizedScope: + true, isFixedArity:true, isUniqueScope:false, isTypedScope:true) + } + + @Override + public String getName() { + return this.Immutable ? "im_tuple_t" : "tuple_t"; + } + + @Override + public int CountTypeArgument(TypeArgumentList value) { + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: lenInBytes += RowBuffer.Count7BitEncodedUInt((ulong)value.Count); + lenInBytes += RowBuffer.Count7BitEncodedUInt(value.getCount()); + for (TypeArgument arg : value) { + lenInBytes += arg.getType().CountTypeArgument(arg.getTypeArgs().clone()); + } + + return lenInBytes; + } + + @Override + public boolean HasImplicitTypeCode(tangible.RefObject edit) { + Contract.Assert(edit.argValue.index >= 0); + Contract.Assert(edit.argValue.scopeTypeArgs.getCount() > edit.argValue.index); + return !LayoutCodeTraits.AlwaysRequiresTypeCode(edit.argValue.scopeTypeArgs.get(edit.argValue.index).getType().LayoutCode); + } + + @Override + public TypeArgumentList ReadTypeArgumentList(tangible.RefObject row, int offset, + tangible.OutObject lenInBytes) { + int numTypeArgs = row.argValue.intValue().Read7BitEncodedUInt(offset, lenInBytes); + TypeArgument[] retval = new TypeArgument[numTypeArgs]; + for (int i = 0; i < numTypeArgs; i++) { + int itemLenInBytes; + tangible.OutObject tempOut_itemLenInBytes = new tangible.OutObject(); + retval[i] = LayoutType.ReadTypeArgument(row, offset + lenInBytes.argValue, tempOut_itemLenInBytes); + itemLenInBytes = tempOut_itemLenInBytes.argValue; + lenInBytes.argValue += itemLenInBytes; + } + + return new TypeArgumentList(retval); + } + + @Override + public void SetImplicitTypeCode(tangible.RefObject edit) { + edit.argValue.cellType = edit.argValue.scopeTypeArgs.get(edit.argValue.index).getType(); + edit.argValue.cellTypeArgs = edit.argValue.scopeTypeArgs.get(edit.argValue.index).getTypeArgs().clone(); + } + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, new TypeArgument(this, typeArgs.clone()), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteTypedTuple(edit, this, typeArgs.clone(), options, value.clone()); + return Result.Success; + } + + @Override + public int WriteTypeArgument(tangible.RefObject row, int offset, TypeArgumentList value) { + row.argValue.WriteSparseTypeCode(offset, this.LayoutCode); + int lenInBytes = (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: lenInBytes += row.Write7BitEncodedUInt(offset + lenInBytes, (ulong)value.Count); + lenInBytes += row.argValue.Write7BitEncodedUInt(offset + lenInBytes, value.getCount()); + for (TypeArgument arg : value) { + lenInBytes += arg.getType().WriteTypeArgument(row, offset + lenInBytes, arg.getTypeArgs().clone()); + } + + return lenInBytes; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUDT.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUDT.java new file mode 100644 index 0000000..dcf743f --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUDT.java @@ -0,0 +1,64 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +public final class LayoutUDT extends LayoutPropertyScope { + public LayoutUDT(boolean immutable) { + super(immutable ? azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.ImmutableSchema : azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Schema, immutable); + } + + @Override + public String getName() { + return this.Immutable ? "im_udt" : "udt"; + } + + @Override + public int CountTypeArgument(TypeArgumentList value) { + return (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE) + SchemaId.Size; + } + + @Override + public TypeArgumentList ReadTypeArgumentList(tangible.RefObject row, int offset, + tangible.OutObject lenInBytes) { + SchemaId schemaId = row.argValue.ReadSchemaId(offset).clone(); + lenInBytes.argValue = SchemaId.Size; + return new TypeArgumentList(schemaId.clone()); + } + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value) { + return WriteScope(b, edit, typeArgs, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor edit, TypeArgumentList + // typeArgs, out RowCursor value, UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject edit, + TypeArgumentList typeArgs, tangible.OutObject value, UpdateOptions options) { + Layout udt = b.argValue.getResolver().Resolve(typeArgs.getSchemaId().clone()); + Result result = LayoutType.PrepareSparseWrite(b, edit, new TypeArgument(this, typeArgs.clone()), options); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + b.argValue.WriteSparseUDT(edit, this, udt, options, value.clone()); + return Result.Success; + } + + @Override + public int WriteTypeArgument(tangible.RefObject row, int offset, TypeArgumentList value) { + row.argValue.WriteSparseTypeCode(offset, this.LayoutCode); + row.argValue.WriteSchemaId(offset + (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE), value.getSchemaId().clone()); + return (azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.SIZE / Byte.SIZE) + SchemaId.Size; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt16.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt16.java new file mode 100644 index 0000000..0b4697c --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt16.java @@ -0,0 +1,97 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +//C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: +//ORIGINAL LINE: public sealed class LayoutUInt16 : LayoutType +public final class LayoutUInt16 extends LayoutType { + public LayoutUInt16() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.UInt16, (Short.SIZE / Byte.SIZE)); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "uint16"; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, out + // ushort value) + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadUInt16(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadSparse(ref RowBuffer b, ref RowCursor edit, out ushort value) + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseUInt16(edit); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result WriteFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, ushort + // value) + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + short value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteUInt16(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, ushort value, + // UpdateOptions options = UpdateOptions.Upsert) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, short value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseUInt16(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, short value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt32.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt32.java new file mode 100644 index 0000000..20fcd2d --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt32.java @@ -0,0 +1,97 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +//C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: +//ORIGINAL LINE: public sealed class LayoutUInt32 : LayoutType +public final class LayoutUInt32 extends LayoutType { + public LayoutUInt32() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.UInt32, (Integer.SIZE / Byte.SIZE)); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "uint32"; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, out + // uint value) + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadUInt32(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadSparse(ref RowBuffer b, ref RowCursor edit, out uint value) + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseUInt32(edit); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result WriteFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, uint + // value) + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + int value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteUInt32(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, uint value, + // UpdateOptions options = UpdateOptions.Upsert) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, int value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseUInt32(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, int value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt64.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt64.java new file mode 100644 index 0000000..52686a4 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt64.java @@ -0,0 +1,97 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +//C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: +//ORIGINAL LINE: public sealed class LayoutUInt64 : LayoutType +public final class LayoutUInt64 extends LayoutType { + public LayoutUInt64() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.UInt64, (Long.SIZE / Byte.SIZE)); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "uint64"; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, out + // ulong value) + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadUInt64(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadSparse(ref RowBuffer b, ref RowCursor edit, out ulong value) + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseUInt64(edit); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result WriteFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, ulong + // value) + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + long value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteUInt64(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, ulong value, + // UpdateOptions options = UpdateOptions.Upsert) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, long value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseUInt64(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, long value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt8.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt8.java new file mode 100644 index 0000000..75eac1a --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUInt8.java @@ -0,0 +1,97 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +//C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: +//ORIGINAL LINE: public sealed class LayoutUInt8 : LayoutType +public final class LayoutUInt8 extends LayoutType { + public LayoutUInt8() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.UInt8, 1); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "uint8"; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, out + // byte value) + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadUInt8(scope.argValue.start + col.getOffset()); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadSparse(ref RowBuffer b, ref RowCursor edit, out byte value) + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseUInt8(edit); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result WriteFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, byte + // value) + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + byte value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteUInt8(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, byte value, + // UpdateOptions options = UpdateOptions.Upsert) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, byte value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseUInt8(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, byte value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUniqueScope.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUniqueScope.java new file mode 100644 index 0000000..390fbe7 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUniqueScope.java @@ -0,0 +1,151 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; +import azure.data.cosmos.serialization.hybridrow.RowOptions; + +public abstract class LayoutUniqueScope extends LayoutIndexedScope { + protected LayoutUniqueScope(LayoutCode code, boolean immutable, boolean isSizedScope, boolean isTypedScope) { + // TODO: C# TO JAVA CONVERTER: C# to Java Converter could not resolve the named parameters in the + // following line: + //ORIGINAL LINE: base(code, immutable, isSizedScope, isFixedArity: false, isUniqueScope: true, isTypedScope: + // isTypedScope); + super(code, immutable, isSizedScope, isFixedArity:false, isUniqueScope:true, isTypedScope:isTypedScope) + } + + public abstract TypeArgument FieldType(tangible.RefObject scope); + + /** + * Search for a matching field within a unique index. + * + * @param b The row to search. + * @param scope The parent unique index edit to search. + * @param patternScope The parent edit from which the match pattern is read. + * @param value If successful, the updated edit. + * @return Success a matching field exists in the unique index, NotFound if no match is found, the + * error code otherwise. + *

+ * The pattern field is delete whether the find succeeds or fails. + */ + public final Result Find(tangible.RefObject b, tangible.RefObject scope, + tangible.RefObject patternScope, tangible.OutObject value) { + Result result = LayoutType.PrepareSparseMove(b, scope, this, this.FieldType(scope).clone(), patternScope, UpdateOptions.Update, value.clone()); + + if (result != Result.Success) { + return result; + } + + // Check if the search found the result. + b.argValue.DeleteSparse(patternScope); + + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public Result MoveField(ref RowBuffer b, ref RowCursor destinationScope, ref RowCursor + // sourceEdit, UpdateOptions options = UpdateOptions.Upsert) + public final Result MoveField(tangible.RefObject b, tangible.RefObject destinationScope, + tangible.RefObject sourceEdit, UpdateOptions options) { + RowCursor dstEdit; + tangible.OutObject tempOut_dstEdit = + new tangible.OutObject(); + Result result = LayoutType.PrepareSparseMove(b, destinationScope, this, + this.FieldType(destinationScope).clone(), sourceEdit, options, tempOut_dstEdit); + dstEdit = tempOut_dstEdit.argValue; + + if (result != Result.Success) { + return result; + } + + // Perform the move. + tangible.RefObject tempRef_dstEdit = + new tangible.RefObject(dstEdit); + b.argValue.TypedCollectionMoveField(tempRef_dstEdit, sourceEdit, RowOptions.forValue(options)); + dstEdit = tempRef_dstEdit.argValue; + + // TODO: it would be "better" if the destinationScope were updated to point to the + // highest item seen. Then we would avoid the maximum reparse. + destinationScope.argValue.count = dstEdit.count; + return Result.Success; + } + + /** + * Moves an existing sparse field into the unique index. + * + * @param b The row to move within. + * @param destinationScope The parent unique indexed edit into which the field should be moved. + * @param sourceEdit The field to be moved. + * @param options The move options. + * @return Success if the field is permitted within the unique index, the error code otherwise. + *

+ * The source field MUST be a field whose type arguments match the element type of the + * destination unique index. + * + * The source field is delete whether the move succeeds or fails. + */ + + public final Result MoveField(tangible.RefObject b, tangible.RefObject destinationScope, + tangible.RefObject sourceEdit) { + return MoveField(b, destinationScope, sourceEdit, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteScope(ref RowBuffer b, ref RowCursor scope, + // TypeArgumentList typeArgs, TContext context, WriterFunc func, UpdateOptions options = UpdateOptions + // .Upsert) + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject scope, + TypeArgumentList typeArgs, TContext context, WriterFunc func, + UpdateOptions options) { + RowCursor uniqueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = this.WriteScope(b, scope, typeArgs.clone(), out uniqueScope, options); + if (r != Result.Success) { + return r; + } + + RowCursor childScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + uniqueScope.Clone(out childScope); + childScope.deferUniqueIndex = true; + tangible.RefObject tempRef_childScope = + new tangible.RefObject(childScope); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + r = func == null ? null : func.Invoke(ref b, ref childScope, context) ??Result.Success; + childScope = tempRef_childScope.argValue; + if (r != Result.Success) { + this.DeleteScope(b, scope); + return r; + } + + uniqueScope.count = childScope.count; + tangible.RefObject tempRef_uniqueScope = + new tangible.RefObject(uniqueScope); + r = b.argValue.TypedCollectionUniqueIndexRebuild(tempRef_uniqueScope); + uniqueScope = tempRef_uniqueScope.argValue; + if (r != Result.Success) { + this.DeleteScope(b, scope); + return r; + } + + tangible.RefObject tempRef_childScope2 = + new tangible.RefObject(childScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(scope.argValue.clone(), b, + tempRef_childScope2); + childScope = tempRef_childScope2.argValue; + return Result.Success; + } + + @Override + public Result WriteScope(tangible.RefObject b, tangible.RefObject scope, + TypeArgumentList typeArgs, TContext context, WriterFunc func) { + return WriteScope(b, scope, typeArgs, context, func, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUnixDateTime.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUnixDateTime.java new file mode 100644 index 0000000..181bd6f --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUnixDateTime.java @@ -0,0 +1,87 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutUnixDateTime extends LayoutType { + public LayoutUnixDateTime() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.UnixDateTime, Microsoft.Azure.Cosmos.Serialization.HybridRow.UnixDateTime.Size); + } + + @Override + public boolean getIsFixed() { + return true; + } + + @Override + public String getName() { + return "unixdatetime"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = null; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadUnixDateTime(scope.argValue.start + col.getOffset()).clone(); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + value.argValue = b.argValue.ReadSparseUnixDateTime(edit).clone(); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + UnixDateTime value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteUnixDateTime(scope.argValue.start + col.getOffset(), value.clone()); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, UnixDateTime value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, UnixDateTime value + , UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseUnixDateTime(edit, value.clone(), options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, UnixDateTime value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUtf8.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUtf8.java new file mode 100644 index 0000000..b02514d --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutUtf8.java @@ -0,0 +1,188 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutUtf8 extends LayoutType implements ILayoutUtf8SpanWritable, ILayoutUtf8SpanReadable { + public LayoutUtf8() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.Utf8, 0); + } + + @Override + public boolean getIsFixed() { + return false; + } + + @Override + public String getName() { + return "utf8"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + Utf8Span span; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = this.ReadFixed(b, scope, col, out span); + value.argValue = (r == Result.Success) ? span.toString() : + default + return r; + } + + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + checkArgument(col.getSize() >= 0); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = null; + return Result.NotFound; + } + + value.argValue = b.argValue.ReadFixedString(scope.argValue.start + col.getOffset(), col.getSize()); + return Result.Success; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, + tangible.OutObject value) { + Utf8Span span; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = this.ReadSparse(b, edit, out span); + value.argValue = (r == Result.Success) ? span.toString() : + default + return r; + } + + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = null; + return result; + } + + value.argValue = b.argValue.ReadSparseString(edit); + return Result.Success; + } + + @Override + public Result ReadVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col + , tangible.OutObject value) { + Utf8Span span; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = this.ReadVariable(b, scope, col, out span); + value.argValue = (r == Result.Success) ? span.toString() : + default + return r; + } + + public Result ReadVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col + , tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = null; + return Result.NotFound; + } + + int varOffset = b.argValue.ComputeVariableValueOffset(scope.argValue.layout, scope.argValue.start, + col.getOffset()); + value.argValue = b.argValue.ReadVariableString(varOffset); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + String value) { + checkArgument(value != null); + return this.WriteFixed(b, scope, col, Utf8Span.TranscodeUtf16(value)); + } + + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + Utf8Span value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + checkArgument(col.getSize() >= 0); + checkArgument(value.Length == col.getSize()); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + b.argValue.WriteFixedString(scope.argValue.start + col.getOffset(), value); + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, String value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, string value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, String value, + UpdateOptions options) { + checkArgument(value != null); + return this.WriteSparse(b, edit, Utf8Span.TranscodeUtf16(value), options); + } + + + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, Utf8Span value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public Result WriteSparse(ref RowBuffer b, ref RowCursor edit, Utf8Span value, UpdateOptions + // options = UpdateOptions.Upsert) + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, Utf8Span value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseString(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col, String value) { + checkArgument(value != null); + return this.WriteVariable(b, scope, col, Utf8Span.TranscodeUtf16(value)); + } + + public Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col, Utf8Span value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + int length = value.Length; + if ((col.getSize() > 0) && (length > col.getSize())) { + return Result.TooBig; + } + + boolean exists = b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone()); + int varOffset = b.argValue.ComputeVariableValueOffset(scope.argValue.layout, scope.argValue.start, + col.getOffset()); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + b.argValue.WriteVariableString(varOffset, value, exists, tempOut_shift); + shift = tempOut_shift.argValue; + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + scope.argValue.metaOffset += shift; + scope.argValue.valueOffset += shift; + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutVarInt.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutVarInt.java new file mode 100644 index 0000000..3090752 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutVarInt.java @@ -0,0 +1,114 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +public final class LayoutVarInt extends LayoutType { + public LayoutVarInt() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.VarInt, 0); + } + + @Override + public boolean getIsFixed() { + return false; + } + + @Override + public boolean getIsVarint() { + return true; + } + + @Override + public String getName() { + return "varint"; + } + + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + Contract.Fail("Not Implemented"); + value.argValue = 0; + return Result.Failure; + } + + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseVarInt(edit); + return Result.Success; + } + + @Override + public Result ReadVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + int varOffset = b.argValue.ComputeVariableValueOffset(scope.argValue.layout, scope.argValue.start, + col.getOffset()); + value.argValue = b.argValue.ReadVariableInt(varOffset); + return Result.Success; + } + + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + long value) { + Contract.Fail("Not Implemented"); + return Result.Failure; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, long value, + // UpdateOptions options = UpdateOptions.Upsert) + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, long value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseVarInt(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, long value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } + + @Override + public Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col, long value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + boolean exists = b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone()); + int varOffset = b.argValue.ComputeVariableValueOffset(scope.argValue.layout, scope.argValue.start, + col.getOffset()); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + b.argValue.WriteVariableInt(varOffset, value, exists, tempOut_shift); + shift = tempOut_shift.argValue; + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + scope.argValue.metaOffset += shift; + scope.argValue.valueOffset += shift; + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutVarUInt.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutVarUInt.java new file mode 100644 index 0000000..63b45f0 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/LayoutVarUInt.java @@ -0,0 +1,131 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import static com.google.common.base.Preconditions.checkArgument; + +//C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: +//ORIGINAL LINE: public sealed class LayoutVarUInt : LayoutType +public final class LayoutVarUInt extends LayoutType { + public LayoutVarUInt() { + super(azure.data.cosmos.serialization.hybridrow.layouts.LayoutCode.VarUInt, 0); + } + + @Override + public boolean getIsFixed() { + return false; + } + + @Override + public boolean getIsVarint() { + return true; + } + + @Override + public String getName() { + return "varuint"; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, out + // ulong value) + @Override + public Result ReadFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + tangible.OutObject value) { + Contract.Fail("Not Implemented"); + value.argValue = 0; + return Result.Failure; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadSparse(ref RowBuffer b, ref RowCursor edit, out ulong value) + @Override + public Result ReadSparse(tangible.RefObject b, tangible.RefObject edit, tangible.OutObject value) { + Result result = LayoutType.PrepareSparseRead(b, edit, this.LayoutCode); + if (result != Result.Success) { + value.argValue = 0; + return result; + } + + value.argValue = b.argValue.ReadSparseVarUInt(edit); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result ReadVariable(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, out + // ulong value) + @Override + public Result ReadVariable(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, tangible.OutObject value) { + checkArgument(scope.argValue.scopeType instanceof LayoutUDT); + if (!b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone())) { + value.argValue = 0; + return Result.NotFound; + } + + int varOffset = b.argValue.ComputeVariableValueOffset(scope.argValue.layout, scope.argValue.start, + col.getOffset()); + value.argValue = b.argValue.ReadVariableUInt(varOffset); + return Result.Success; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result WriteFixed(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, ulong + // value) + @Override + public Result WriteFixed(tangible.RefObject b, tangible.RefObject scope, LayoutColumn col, + long value) { + Contract.Fail("Not Implemented"); + return Result.Failure; + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public override Result WriteSparse(ref RowBuffer b, ref RowCursor edit, ulong value, + // UpdateOptions options = UpdateOptions.Upsert) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, long value, + UpdateOptions options) { + Result result = LayoutType.PrepareSparseWrite(b, edit, this.getTypeArg().clone(), options); + if (result != Result.Success) { + return result; + } + + b.argValue.WriteSparseVarUInt(edit, value, options); + return Result.Success; + } + + @Override + public Result WriteSparse(tangible.RefObject b, tangible.RefObject edit, long value) { + return WriteSparse(b, edit, value, UpdateOptions.Upsert); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public override Result WriteVariable(ref RowBuffer b, ref RowCursor scope, LayoutColumn col, + // ulong value) + @Override + public Result WriteVariable(tangible.RefObject b, tangible.RefObject scope, + LayoutColumn col, long value) { + Contract.Requires(scope.argValue.scopeType instanceof LayoutUDT); + if (scope.argValue.immutable) { + return Result.InsufficientPermissions; + } + + boolean exists = b.argValue.ReadBit(scope.argValue.start, col.getNullBit().clone()); + int varOffset = b.argValue.ComputeVariableValueOffset(scope.argValue.layout, scope.argValue.start, + col.getOffset()); + int shift; + tangible.OutObject tempOut_shift = new tangible.OutObject(); + b.argValue.WriteVariableUInt(varOffset, value, exists, tempOut_shift); + shift = tempOut_shift.argValue; + b.argValue.SetBit(scope.argValue.start, col.getNullBit().clone()); + scope.argValue.metaOffset += shift; + scope.argValue.valueOffset += shift; + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SamplingStringComparer.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SamplingStringComparer.java new file mode 100644 index 0000000..c11ad88 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SamplingStringComparer.java @@ -0,0 +1,48 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +public class SamplingStringComparer implements IEqualityComparer { + public static final SamplingStringComparer Default = new SamplingStringComparer(); + + public final boolean equals(String x, String y) { + Contract.Assert(x != null); + Contract.Assert(y != null); + + return x.equals(y); + } + + public final int hashCode(String obj) { + Contract.Assert(obj != null); + + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint hash1 = 5381; + int hash1 = 5381; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint hash2 = hash1; + int hash2 = hash1; + final int numSamples = 4; + final int modulus = 13; + + ReadOnlySpan utf16 = obj.AsSpan(); + int max = Math.min(utf16.Length, numSamples); + for (int i = 0; i < max; i++) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint c = utf16[(i * modulus) % utf16.Length]; + int c = utf16[(i * modulus) % utf16.Length]; + if (i % 2 == 0) { + hash1 = ((hash1 << 5) + hash1) ^ c; + } else { + hash2 = ((hash2 << 5) + hash2) ^ c; + } + } + + return hash1 + (hash2 * 1566083941); + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SamplingUtf8StringComparer.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SamplingUtf8StringComparer.java new file mode 100644 index 0000000..f7a04cc --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SamplingUtf8StringComparer.java @@ -0,0 +1,50 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +public class SamplingUtf8StringComparer implements IEqualityComparer { + public static final SamplingUtf8StringComparer Default = new SamplingUtf8StringComparer(); + + public final boolean equals(Utf8String x, Utf8String y) { + Contract.Assert(x != null); + Contract.Assert(y != null); + + return x.Span.equals(y.Span); + } + + public final int hashCode(Utf8String obj) { + Contract.Assert(obj != null); + + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint hash1 = 5381; + int hash1 = 5381; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint hash2 = hash1; + int hash2 = hash1; + final int numSamples = 4; + final int modulus = 13; + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ReadOnlySpan utf8 = obj.Span.Span; + ReadOnlySpan utf8 = obj.Span.Span; + int max = Math.min(utf8.Length, numSamples); + for (int i = 0; i < max; i++) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint c = utf8[(i * modulus) % utf8.Length]; + int c = utf8[(i * modulus) % utf8.Length]; + if (i % 2 == 0) { + hash1 = ((hash1 << 5) + hash1) ^ c; + } else { + hash2 = ((hash2 << 5) + hash2) ^ c; + } + } + + return hash1 + (hash2 * 1566083941); + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/StringToken.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/StringToken.java new file mode 100644 index 0000000..273a1b1 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/StringToken.java @@ -0,0 +1,90 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public readonly struct StringToken +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: +public final class StringToken { + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + ///#pragma warning disable CA1051 // Do not declare visible instance fields + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public readonly ulong Id; + public long Id; + public Utf8String Path; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public readonly byte[] Varint; + public byte[] Varint; + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + ///#pragma warning restore CA1051 // Do not declare visible instance fields + + public StringToken() { + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public StringToken(ulong id, Utf8String path) + public StringToken(long id, Utf8String path) { + this.Id = id; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.Varint = new byte[StringToken.Count7BitEncodedUInt(id)]; + this.Varint = new byte[StringToken.Count7BitEncodedUInt(id)]; + StringToken.Write7BitEncodedUInt(this.Varint.AsSpan(), id); + this.Path = path; + } + + public StringToken clone() { + StringToken varCopy = new StringToken(); + + varCopy.Id = this.Id; + varCopy.Varint = this.Varint; + varCopy.Path = this.Path; + + return varCopy; + } + + boolean getIsNull() + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private static int Count7BitEncodedUInt(ulong value) + private static int Count7BitEncodedUInt(long value) { + // Count the number of bytes needed to write out an int 7 bits at a time. + int i = 0; + while (value >= 0x80L) { + i++; + //C# TO JAVA CONVERTER WARNING: The right shift operator was replaced by Java's logical right shift + // operator since the left operand was originally of an unsigned type, but you should confirm this replacement: + value >>>= 7; + } + + i++; + return i; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private static int Write7BitEncodedUInt(Span buffer, ulong value) + private static int Write7BitEncodedUInt(Span buffer, long value) { + // Write out an unsigned long 7 bits at a time. The high bit of the byte, + // when set, indicates there are more bytes. + int i = 0; + while (value >= 0x80L) { + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: buffer[i] = unchecked((byte)(value | 0x80)); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + buffer[i] = (byte)(value | 0x80); + i++; + //C# TO JAVA CONVERTER WARNING: The right shift operator was replaced by Java's logical right shift + // operator since the left operand was originally of an unsigned type, but you should confirm this + // replacement: + value >>>= 7; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: buffer[i] = (byte)value; + buffer[i] = (byte)value; + i++; + return i; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/StringTokenizer.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/StringTokenizer.java new file mode 100644 index 0000000..1fa74ca --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/StringTokenizer.java @@ -0,0 +1,123 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public final class StringTokenizer { + /** + * The number of unique tokens described by the encoding. + */ + private int Count; + private HashMap stringTokens; + private ArrayList strings; + private HashMap tokens; + + /** + * Initializes a new instance of the class. + */ + public StringTokenizer() { + this.tokens = new HashMap(Map.ofEntries(Map.entry(Utf8String.Empty, + new StringToken(0, Utf8String.Empty)))); + this.stringTokens = new HashMap(Map.ofEntries(Map.entry("", new StringToken(0, + Utf8String.Empty)))); + this.strings = new ArrayList(Arrays.asList(Utf8String.Empty)); + this.setCount(1); + } + + public int getCount() { + return Count; + } + + private void setCount(int value) { + Count = value; + } + + /** + * Assign a token to the string. + * If the string already has a token, that token is returned instead. + * + * @param path The string to assign a new token. + * @return The token assigned to the string. + */ + public StringToken Add(Utf8String path) { + Contract.Requires(path != null); + + StringToken token; + if (this.tokens.containsKey(path) && (token = this.tokens.get(path)) == token) { + return token; + } + + token = this.AllocateToken(path).clone(); + return token; + } + + /** + * Looks up a token's corresponding string. + * + * @param token The token to look up. + * @param path If successful, the token's assigned string. + * @return True if successful, false otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public bool TryFindString(ulong token, out Utf8String path) + public boolean TryFindString(long token, tangible.OutObject path) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: if (token >= (ulong)this.strings.Count) + if (token >= (long)this.strings.size()) { + path.argValue = null; + return false; + } + + path.argValue = this.strings.get((int)token); + return true; + } + + /** + * Looks up a string's corresponding token. + * + * @param path The string to look up. + * @param token If successful, the string's assigned token. + * @return True if successful, false otherwise. + */ + public boolean TryFindToken(UtfAnyString path, tangible.OutObject token) { + if (path.IsNull) { + token.argValue = null; + return false; + } + + if (path.IsUtf8) { + return (this.tokens.containsKey(path.ToUtf8String()) && (token.argValue = + this.tokens.get(path.ToUtf8String())) == token.argValue); + } + + return (this.stringTokens.containsKey(path.toString()) && (token.argValue = + this.stringTokens.get(path.toString())) == token.argValue); + } + + /** + * Allocates a new token and assigns the string to it. + * + * @param path The string that needs a new token. + * @return The new allocated token. + */ + private StringToken AllocateToken(Utf8String path) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong id = (ulong)this.Count++; + long id = this.getCount(); + this.setCount(this.getCount() + 1); + StringToken token = new StringToken(id, path); + this.tokens.put(path, token.clone()); + this.stringTokens.put(path.toString(), token.clone()); + this.strings.add(path); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Contract.Assert((ulong)this.strings.Count - 1 == id); + Contract.Assert((long)this.strings.size() - 1 == id); + return token.clone(); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SystemSchema.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SystemSchema.java new file mode 100644 index 0000000..2673810 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/SystemSchema.java @@ -0,0 +1,53 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +public final class SystemSchema { + /** + * SchemaId of the empty schema. This schema has no defined cells but can accomodate + * unschematized sparse content. + */ + public static final SchemaId EmptySchemaId = new SchemaId(2147473650); + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", + // Justification = "Type is immutable.")] public static readonly LayoutResolver LayoutResolver = SystemSchema + // .LoadSchema(); + public static final LayoutResolver LayoutResolver = SystemSchema.LoadSchema(); + /** + * SchemaId of HybridRow RecordIO Record Headers. + */ + public static final SchemaId RecordSchemaId = new SchemaId(2147473649); + /** + * SchemaId of HybridRow RecordIO Segments. + */ + public static final SchemaId SegmentSchemaId = new SchemaId(2147473648); + + private static String FormatResourceName(Assembly assembly, String resourceName) { + return assembly.GetName().Name + "." + resourceName.replace(" ", "_").replace("\\", ".").replace("/", "."); + } + + private static String GetEmbeddedResource(String resourceName) { + Assembly assembly = Assembly.GetAssembly(RecordIOFormatter.class); + resourceName = SystemSchema.FormatResourceName(assembly, resourceName); + try (Stream resourceStream = assembly.GetManifestResourceStream(resourceName)) { + if (resourceStream == null) { + return null; + } + + try (InputStreamReader reader = new InputStreamReader(resourceStream)) { + return reader.ReadToEnd(); + } + } + } + + private static LayoutResolver LoadSchema() { + String json = SystemSchema.GetEmbeddedResource("SystemSchemas\\SystemSchema.json"); + Namespace ns = Namespace.Parse(json); + LayoutResolverNamespace resolver = new LayoutResolverNamespace(ns); + return resolver; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/TypeArgument.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/TypeArgument.java new file mode 100644 index 0000000..223190a --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/TypeArgument.java @@ -0,0 +1,125 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import static com.google.common.base.Preconditions.checkArgument; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [DebuggerDisplay("{this.type == null ? null : ToString()}")] public readonly struct TypeArgument : +// IEquatable +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: [DebuggerDisplay("{this.type == null ? null : ToString()}")] public readonly struct TypeArgument : +// IEquatable +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: +public final class TypeArgument implements IEquatable { + private LayoutType type; + private TypeArgumentList typeArgs = new TypeArgumentList(); + + /** + * Initializes a new instance of the struct. + * + * @param type The type of the constraint. + */ + public TypeArgument() { + } + + public TypeArgument(LayoutType type) { + checkArgument(type != null); + + this.type = type; + this.typeArgs = TypeArgumentList.Empty; + } + + /** + * Initializes a new instance of the struct. + * + * @param type The type of the constraint. + * @param typeArgs For generic types the type parameters. + */ + public TypeArgument(LayoutType type, TypeArgumentList typeArgs) { + checkArgument(type != null); + + this.type = type; + this.typeArgs = typeArgs.clone(); + } + + /** + * The physical layout type. + */ + public LayoutType getType() { + return this.type; + } + + /** + * If the type argument is itself generic, then its type arguments. + */ + public TypeArgumentList getTypeArgs() { + return this.typeArgs.clone(); + } + + /** + * The physical layout type of the field cast to the specified type. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DebuggerHidden] public T TypeAs() where T : ILayoutType + public T TypeAs() { + return this.type.TypeAs(); + } + + public TypeArgument clone() { + TypeArgument varCopy = new TypeArgument(); + + varCopy.type = this.type; + varCopy.typeArgs = this.typeArgs.clone(); + + return varCopy; + } + + public boolean equals(TypeArgument other) { + return this.type.equals(other.type) && this.typeArgs.equals(other.typeArgs.clone()); + } + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + boolean tempVar = obj instanceof TypeArgument; + TypeArgument ota = tempVar ? (TypeArgument)obj : null; + if (tempVar) { + return this.equals(ota); + } + + return false; + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + return (this.type.hashCode() * 397) ^ this.typeArgs.hashCode(); + } + } + + public static boolean opEquals(TypeArgument left, TypeArgument right) { + return left.equals(right.clone()); + } + + public static boolean opNotEquals(TypeArgument left, TypeArgument right) { + return !left.equals(right.clone()); + } + + @Override + public String toString() { + if (this.type == null) { + return ""; + } + + return this.type.getName() + this.typeArgs.toString(); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/TypeArgumentList.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/TypeArgumentList.java new file mode 100644 index 0000000..51ca94b --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/TypeArgumentList.java @@ -0,0 +1,206 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +import static com.google.common.base.Preconditions.checkArgument; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1034 // Nested types should not be visible + + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [DebuggerDisplay("{this.args == null ? null : ToString()}")] public readonly struct TypeArgumentList +// : IEquatable +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: [DebuggerDisplay("{this.args == null ? null : ToString()}")] public readonly struct TypeArgumentList +// : IEquatable +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# readonly struct: +public final class TypeArgumentList implements IEquatable { + public static final TypeArgumentList Empty = new TypeArgumentList(Array.Empty()); + + private TypeArgument[] args; + + /** + * For UDT fields, the schema id of the nested layout. + */ + private SchemaId schemaId = new SchemaId(); + + public TypeArgumentList() { + } + + public TypeArgumentList(TypeArgument[] args) { + checkArgument(args != null); + + this.args = args; + this.schemaId = getSchemaId().Invalid; + } + + /** + * Initializes a new instance of the struct. + * + * @param schemaId For UDT fields, the schema id of the nested layout. + */ + public TypeArgumentList(SchemaId schemaId) { + this.args = Array.Empty(); + this.schemaId = schemaId.clone(); + } + + public int getCount() { + return this.args.length; + } + + /** + * For UDT fields, the schema id of the nested layout. + */ + public SchemaId getSchemaId() { + return this.schemaId.clone(); + } + + /** + * Gets an enumerator for this span. + */ + public Enumerator GetEnumerator() { + return new Enumerator(this.args); + } + + public TypeArgumentList clone() { + TypeArgumentList varCopy = new TypeArgumentList(); + + varCopy.args = this.args.clone(); + varCopy.schemaId = this.schemaId.clone(); + + return varCopy; + } + + public boolean equals(TypeArgumentList other) { + //C# TO JAVA CONVERTER WARNING: Java Arrays.equals is not always identical to LINQ 'SequenceEqual': + //ORIGINAL LINE: return (this.schemaId == other.schemaId) && this.args.SequenceEqual(other.args); + return (azure.data.cosmos.serialization.hybridrow.SchemaId.opEquals(this.schemaId.clone(), + other.schemaId.clone())) && Arrays.equals(this.args, other.args); + } + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + boolean tempVar = obj instanceof TypeArgumentList; + TypeArgumentList ota = tempVar ? (TypeArgumentList)obj : null; + if (tempVar) { + return this.equals(ota); + } + + return false; + } + + public TypeArgument get(int i) { + return this.args[i].clone(); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + int hash = 19; + hash = (hash * 397) ^ this.schemaId.hashCode(); + for (TypeArgument a : this.args) { + hash = (hash * 397) ^ a.hashCode(); + } + + return hash; + } + } + + public static boolean opEquals(TypeArgumentList left, TypeArgumentList right) { + return left.equals(right.clone()); + } + + public static boolean opNotEquals(TypeArgumentList left, TypeArgumentList right) { + return !left.equals(right.clone()); + } + + @Override + public String toString() { + if (azure.data.cosmos.serialization.hybridrow.SchemaId.opNotEquals(this.schemaId.clone(), + getSchemaId().Invalid)) { + return String.format("<%1$s>", this.schemaId.toString()); + } + + if (this.args == null || this.args == null ? null : this.args.length == 0) { + return ""; + } + + return String.format("<%1$s>", tangible.StringHelper.join(", ", this.args)); + } + + /** + * Enumerates the elements of a . + */ + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Enumerator + public final static class Enumerator { + /** + * The next index to yield. + */ + private int index; + /** + * The list being enumerated. + */ + private TypeArgument[] list; + + /** + * Initializes a new instance of the struct. + * + * @param list The list to enumerate. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(TypeArgument[] list) + public Enumerator() { + } + + public Enumerator(TypeArgument[] list) { + this.list = list; + this.index = -1; + } + + /** + * Advances the enumerator to the next element of the span. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() + public boolean MoveNext() { + int i = this.index + 1; + if (i < this.list.length) { + this.index = i; + return true; + } + + return false; + } + + /** + * Gets the element at the current position of the enumerator. + */ + // TODO: C# TO JAVA CONVERTER: 'ref return' methods are not converted by C# to Java Converter: + // public ref readonly TypeArgument Current + // { + // [MethodImpl(MethodImplOptions.AggressiveInlining)] get => ref this.list[this.index]; + // } + public Enumerator clone() { + Enumerator varCopy = new Enumerator(); + + varCopy.list = this.list.clone(); + varCopy.index = this.index; + + return varCopy; + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/UpdateOptions.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/UpdateOptions.java new file mode 100644 index 0000000..d8b5ea6 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/layouts/UpdateOptions.java @@ -0,0 +1,74 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.layouts; + +/** + * Describes the desired behavior when writing a . + */ +public enum UpdateOptions { + None(0), + + /** + * Overwrite an existing value. + *

+ * An existing value is assumed to exist at the offset provided. The existing value is + * replaced inline. The remainder of the row is resized to accomodate either an increase or decrease + * in required space. + */ + Update(1), + + /** + * Insert a new value. + *

+ * An existing value is assumed NOT to exist at the offset provided. The new value is + * inserted immediately at the offset. The remainder of the row is resized to accomodate either an + * increase or decrease in required space. + */ + Insert(2), + + /** + * Update an existing value or insert a new value, if no value exists. + *

+ * If a value exists, then this operation becomes , otherwise it becomes + * . + */ + Upsert(3), + + /** + * Insert a new value moving existing values to the right. + *

+ * Within an array scope, inserts a new value immediately at the index moving all subsequent + * items to the right. In any other scope behaves the same as . + */ + InsertAt(4); + + public static final int SIZE = java.lang.Integer.SIZE; + private static java.util.HashMap mappings; + private int intValue; + + UpdateOptions(int value) { + intValue = value; + getMappings().put(value, this); + } + + public int getValue() { + return intValue; + } + + public static UpdateOptions forValue(int value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (UpdateOptions.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/Record.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/Record.java new file mode 100644 index 0000000..403bb3d --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/Record.java @@ -0,0 +1,38 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.recordio; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1051 // Do not declare visible instance fields + + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public struct Record +public final class Record { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public uint Crc32; + public int Crc32; + public int Length; + + public Record() { + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Record(int length, uint crc32) + public Record(int length, int crc32) { + this.Length = length; + this.Crc32 = crc32; + } + + public Record clone() { + Record varCopy = new Record(); + + varCopy.Length = this.Length; + varCopy.Crc32 = this.Crc32; + + return varCopy; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOFormatter.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOFormatter.java new file mode 100644 index 0000000..2289853 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOFormatter.java @@ -0,0 +1,76 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.recordio; + +import azure.data.cosmos.serialization.hybridrow.DefaultSpanResizer; +import azure.data.cosmos.serialization.hybridrow.HybridRowHeader; +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.ISpanResizer; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; + +public final class RecordIOFormatter { + public static final Layout RecordLayout = SystemSchema.LayoutResolver.Resolve(SystemSchema.RecordSchemaId); + public static final Layout SegmentLayout = SystemSchema.LayoutResolver.Resolve(SystemSchema.SegmentSchemaId); + + public static Result FormatRecord(ReadOnlyMemory body, tangible.OutObject row) { + return FormatRecord(body, row, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public static Result FormatRecord(ReadOnlyMemory body, out RowBuffer row, + // ISpanResizer resizer = default) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public static Result FormatRecord(ReadOnlyMemory body, tangible.OutObject row, + ISpanResizer resizer) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: resizer = resizer != null ? resizer : DefaultSpanResizer.Default; + resizer = resizer != null ? resizer : DefaultSpanResizer < Byte >.Default; + int estimatedSize = HybridRowHeader.Size + RecordIOFormatter.RecordLayout.getSize() + body.Length; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint crc32 = Crc32.Update(0, body.Span); + int crc32 = Crc32.Update(0, body.Span); + Record record = new Record(body.Length, crc32); + return RecordIOFormatter.FormatObject(resizer, estimatedSize, RecordIOFormatter.RecordLayout, record.clone(), + RecordSerializer.Write, row.clone()); + } + + public static Result FormatSegment(Segment segment, tangible.OutObject row) { + return FormatSegment(segment, row, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public static Result FormatSegment(Segment segment, out RowBuffer row, ISpanResizer + // resizer = default) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public static Result FormatSegment(Segment segment, tangible.OutObject row, ISpanResizer resizer) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: resizer = resizer != null ? resizer : DefaultSpanResizer.Default; + resizer = resizer != null ? resizer : DefaultSpanResizer < Byte >.Default; + int estimatedSize = + HybridRowHeader.Size + RecordIOFormatter.SegmentLayout.getSize() + segment.Comment == null ? null : + segment.Comment.length() != null ? segment.Comment.length() : 0 + segment.SDL == null ? null : + segment.SDL.length() != null ? segment.SDL.length() : 0 + 20; + + return RecordIOFormatter.FormatObject(resizer, estimatedSize, RecordIOFormatter.SegmentLayout, + segment.clone(), SegmentSerializer.Write, row.clone()); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private static Result FormatObject(ISpanResizer resizer, int initialCapacity, Layout + // layout, T obj, RowWriter.WriterFunc writer, out RowBuffer row) + private static Result FormatObject(ISpanResizer resizer, int initialCapacity, Layout layout, T obj, + RowWriter.WriterFunc writer, tangible.OutObject row) { + row.argValue = new RowBuffer(initialCapacity, resizer); + row.argValue.InitLayout(HybridRowVersion.V1, layout, SystemSchema.LayoutResolver); + Result r = RowWriter.WriteBuffer(row.clone(), obj, writer); + if (r != Result.Success) { + row.argValue = null; + return r; + } + + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOParser.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOParser.java new file mode 100644 index 0000000..90f70ad --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOParser.java @@ -0,0 +1,335 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.recordio; + +import azure.data.cosmos.serialization.hybridrow.HybridRowHeader; +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.io.RowReader; +import azure.data.cosmos.serialization.hybridrow.layouts.SystemSchema; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public struct RecordIOParser +public final class RecordIOParser { + private Record record = new Record(); + private Segment segment = new Segment(); + private State state = State.values()[0]; + + /** + * True if a valid segment has been parsed. + */ + public boolean getHaveSegment() { + return this.state.getValue() >= State.NeedHeader.getValue(); + } + + /** + * If a valid segment has been parsed then current active segment, otherwise undefined. + */ + public Segment getSegment() { + Contract.Requires(this.getHaveSegment()); + return this.segment.clone(); + } + + /** + * Processes one buffers worth of data possibly advancing the parser state. + * + * @param buffer The buffer to consume. + * @param type Indicates the type of Hybrid Row produced in . + * @param record If non-empty, then the body of the next record in the sequence. + * @param need The smallest number of bytes needed to advanced the parser state further. It is + * recommended that Process not be called again until at least this number of bytes are available. + * @param consumed The number of bytes consumed from the input buffer. This number may be less + * than the total buffer size if the parser moved to a new state. + * @return if no error + * has occurred, otherwise a valid + * of the last error encountered + * during parsing. + *

+ * > + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result Process(Memory buffer, out ProductionType type, out Memory record, out + // int need, out int consumed) + public Result Process(Memory buffer, tangible.OutObject type, + tangible.OutObject> record, tangible.OutObject need, + tangible.OutObject consumed) { + Result r = Result.Failure; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Memory b = buffer; + Memory b = buffer; + type.argValue = ProductionType.None; + record.argValue = null; + switch (this.state) { + case Start: + this.state = State.NeedSegmentLength; + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + case NeedSegmentLength: { + int minimalSegmentRowSize = HybridRowHeader.Size + RecordIOFormatter.SegmentLayout.getSize(); + if (b.Length < minimalSegmentRowSize) { + need.argValue = minimalSegmentRowSize; + consumed.argValue = buffer.Length - b.Length; + return Result.InsufficientBuffer; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Span span = b.Span.Slice(0, minimalSegmentRowSize); + Span span = b.Span.Slice(0, minimalSegmentRowSize); + RowBuffer row = new RowBuffer(span, HybridRowVersion.V1, SystemSchema.LayoutResolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row); + row = tempRef_row.argValue; + tangible.RefObject tempRef_reader = + new tangible.RefObject(reader); + tangible.OutObject tempOut_segment = + new tangible.OutObject(); + r = SegmentSerializer.Read(tempRef_reader, tempOut_segment); + this.segment = tempOut_segment.argValue; + reader = tempRef_reader.argValue; + if (r != Result.Success) { + break; + } + + this.state = State.NeedSegment; + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case State.NeedSegment + } + + case NeedSegment: { + if (b.Length < this.segment.Length) { + need.argValue = this.segment.Length; + consumed.argValue = buffer.Length - b.Length; + return Result.InsufficientBuffer; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Span span = b.Span.Slice(0, this.segment.Length); + Span span = b.Span.Slice(0, this.segment.Length); + RowBuffer row = new RowBuffer(span, HybridRowVersion.V1, SystemSchema.LayoutResolver); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row2); + row = tempRef_row2.argValue; + tangible.RefObject tempRef_reader2 = + new tangible.RefObject(reader); + tangible.OutObject tempOut_segment2 + = new tangible.OutObject(); + r = SegmentSerializer.Read(tempRef_reader2, tempOut_segment2); + this.segment = tempOut_segment2.argValue; + reader = tempRef_reader2.argValue; + if (r != Result.Success) { + break; + } + + record.argValue = b.Slice(0, span.Length); + b = b.Slice(span.Length); + need.argValue = 0; + this.state = State.NeedHeader; + consumed.argValue = buffer.Length - b.Length; + type.argValue = ProductionType.Segment; + return Result.Success; + } + + case NeedHeader: { + if (b.Length < HybridRowHeader.Size) { + need.argValue = HybridRowHeader.Size; + consumed.argValue = buffer.Length - b.Length; + return Result.InsufficientBuffer; + } + + HybridRowHeader header; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + MemoryMarshal.TryRead(b.Span, out header); + if (header.Version != HybridRowVersion.V1) { + r = Result.InvalidRow; + break; + } + + if (azure.data.cosmos.serialization.hybridrow.SchemaId.opEquals(header.SchemaId, + SystemSchema.SegmentSchemaId)) { + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case State.NeedSegment + } + + if (azure.data.cosmos.serialization.hybridrow.SchemaId.opEquals(header.SchemaId, + SystemSchema.RecordSchemaId)) { + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case State.NeedRecord + } + + r = Result.InvalidRow; + break; + } + + case NeedRecord: { + int minimalRecordRowSize = HybridRowHeader.Size + RecordIOFormatter.RecordLayout.getSize(); + if (b.Length < minimalRecordRowSize) { + need.argValue = minimalRecordRowSize; + consumed.argValue = buffer.Length - b.Length; + return Result.InsufficientBuffer; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Span span = b.Span.Slice(0, minimalRecordRowSize); + Span span = b.Span.Slice(0, minimalRecordRowSize); + RowBuffer row = new RowBuffer(span, HybridRowVersion.V1, SystemSchema.LayoutResolver); + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row3); + row = tempRef_row3.argValue; + tangible.RefObject tempRef_reader3 = new tangible.RefObject(reader); + tangible.OutObject tempOut_record = new tangible.OutObject(); + r = RecordSerializer.Read(tempRef_reader3, tempOut_record); + this.record = tempOut_record.argValue; + reader = tempRef_reader3.argValue; + if (r != Result.Success) { + break; + } + + b = b.Slice(span.Length); + this.state = State.NeedRow; + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case State.NeedRow + } + + case NeedRow: { + if (b.Length < this.record.Length) { + need.argValue = this.record.Length; + consumed.argValue = buffer.Length - b.Length; + return Result.InsufficientBuffer; + } + + record.argValue = b.Slice(0, this.record.Length); + + // Validate that the record has not been corrupted. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint crc32 = Crc32.Update(0, record.Span); + int crc32 = Crc32.Update(0, record.argValue.Span); + if (crc32 != this.record.Crc32) { + r = Result.InvalidRow; + break; + } + + b = b.Slice(this.record.Length); + need.argValue = 0; + this.state = State.NeedHeader; + consumed.argValue = buffer.Length - b.Length; + type.argValue = ProductionType.Record; + return Result.Success; + } + } + + this.state = State.Error; + need.argValue = 0; + consumed.argValue = buffer.Length - b.Length; + return r; + } + + public RecordIOParser clone() { + RecordIOParser varCopy = new RecordIOParser(); + + varCopy.state = this.state; + varCopy.segment = this.segment.clone(); + varCopy.record = this.record.clone(); + + return varCopy; + } + + /** + * Describes the type of Hybrid Rows produced by the parser. + */ + public enum ProductionType { + /** + * No hybrid row was produced. The parser needs more data. + */ + None(0), + + /** + * A new segment row was produced. + */ + Segment(1), + + /** + * A record in the current segment was produced. + */ + Record(2); + + public static final int SIZE = java.lang.Integer.SIZE; + private static java.util.HashMap mappings; + private int intValue; + + ProductionType(int value) { + intValue = value; + getMappings().put(value, this); + } + + public int getValue() { + return intValue; + } + + public static ProductionType forValue(int value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (ProductionType.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } + } + + /** + * The states for the internal state machine. + * Note: numerical ordering of these states matters. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private enum State : byte + private enum State { + Start((byte)0), // Start: no buffers have yet been provided to the parser. + Error(((byte)0) + 1), // Unrecoverable parse error encountered. + NeedSegmentLength(((byte)0) + 2), // Parsing segment header length + NeedSegment(((byte)0) + 3), // Parsing segment header + NeedHeader(((byte)0) + 4), // Parsing HybridRow header + NeedRecord(((byte)0) + 5), // Parsing record header + NeedRow(((byte)0) + 6); // Parsing row body + + public static final int SIZE = java.lang.Byte.SIZE; + private static java.util.HashMap mappings; + private byte byteValue; + + State(byte value) { + byteValue = value; + getMappings().put(value, this); + } + + public byte getValue() { + return byteValue; + } + + public static State forValue(byte value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (State.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOStream.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOStream.java new file mode 100644 index 0000000..18374c7 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordIOStream.java @@ -0,0 +1,368 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.recordio; + +import azure.data.cosmos.serialization.hybridrow.MemorySpanResizer; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; + +import java.io.InputStream; +import java.io.OutputStream; + +public final class RecordIOStream { +/** + * A function that produces RecordIO record bodies. + *

+ * Record bodies are returned as memory blocks. It is expected that each block is a + * HybridRow, but any binary data is allowed. + * + * @param index The 0-based index of the record within the segment to be produced. + * @return A tuple with: Success if the body was produced without error, the error code otherwise. + * And, the byte sequence of the record body's row buffer. + */ + public delegate ValueTask + + ProduceFuncAsync(long index);<(Result,ReadOnlyMemory)> + + /** + * Reads an entire RecordIO stream. + * + * @param stm The stream to read from. + * @param visitRecord A (required) delegate that is called once for each record. + *

+ * is passed a of the byte sequence + * of the + * record body's row buffer. + *

+ *

If returns an error then the sequence is aborted.

+ * @param visitSegment An (optional) delegate that is called once for each segment header. + *

+ * If is not provided then segment headers are parsed but + * skipped + * over. + *

+ *

+ * is passed a of the byte sequence of + * the segment header's row buffer. + *

+ *

If returns an error then the sequence is aborted.

+ * @param resizer Optional memory resizer. + * @return Success if the stream is parsed without error, the error code otherwise. + */ + + public static Task ReadRecordIOAsync(Stream stm, Func, Result> visitRecord, + Func, Result> visitSegment) { + return ReadRecordIOAsync(stm, visitRecord, visitSegment, null); + } + + public static Task ReadRecordIOAsync(Stream stm, Func, Result> visitRecord) { + return ReadRecordIOAsync(stm, visitRecord, null, null); + } + + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: public static async Task ReadRecordIOAsync(this Stream stm, Func, Result> + // visitRecord, Func, Result> visitSegment = default, MemorySpanResizer resizer = default) + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public static Task ReadRecordIOAsync(InputStream stm, + tangible.Func1Param, Result> visitRecord, + tangible.Func1Param, Result> visitSegment, + MemorySpanResizer resizer) { + Contract.Requires(stm != null); + Contract.Requires(visitRecord != null); + + // Create a reusable, resizable buffer if the caller didn't provide one. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: resizer = resizer != null ? resizer : new MemorySpanResizer(); + resizer = resizer != null ? resizer : new MemorySpanResizer(); + + RecordIOParser parser = null; + int need = 0; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Memory active = resizer.Memory; + Memory active = resizer.getMemory(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Memory avail = default; + Memory avail = null; + while (true) { + checkState(avail.Length < active.Length); + checkState(active.Length > 0); + checkState(active.Length >= need); + + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + int read = await stm.ReadAsync(active.Slice(avail.Length)); + if (read == 0) { + break; + } + + avail = active.Slice(0, avail.Length + read); + + // If there isn't enough data to move the parser forward then just read again. + if (avail.Length < need) { + continue; + } + + // Process the available data until no more forward progress is possible. + while (avail.Length > 0) { + // Loop around processing available data until we don't have anymore + RecordIOParser.ProductionType prodType; + tangible.OutObject tempOut_prodType = new tangible.OutObject(); + Memory record; + tangible.OutObject> tempOut_record = new tangible.OutObject>(); + tangible.OutObject tempOut_need = new tangible.OutObject(); + int consumed; + tangible.OutObject tempOut_consumed = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Result r = parser.Process(avail, out RecordIOParser.ProductionType prodType, out + // Memory record, out need, out int consumed); + Result r = parser.Process(avail, tempOut_prodType, tempOut_record, tempOut_need, tempOut_consumed); + consumed = tempOut_consumed.argValue; + need = tempOut_need.argValue; + record = tempOut_record.argValue; + prodType = tempOut_prodType.argValue; + + if ((r != Result.Success) && (r != Result.InsufficientBuffer)) { + return r; + } + + active = active.Slice(consumed); + avail = avail.Slice(consumed); + if (avail.IsEmpty) { + active = resizer.getMemory(); + } + + // If there wasn't enough data to move the parser forward then get more data. + if (r == Result.InsufficientBuffer) { + if (need > active.Length) { + resizer.Resize(need, avail.Span); + active = resizer.getMemory(); + avail = resizer.getMemory().Slice(0, avail.Length); + } + + break; + } + + // Validate the Segment + if (prodType == RecordIOParser.ProductionType.Segment) { + checkState(!record.IsEmpty); + r = visitSegment == null ? null : visitSegment.invoke(record) != null ? + visitSegment.invoke(record) : Result.Success; + if (r != Result.Success) { + return r; + } + } + + // Consume the record. + if (prodType == RecordIOParser.ProductionType.Record) { + checkState(!record.IsEmpty); + + r = visitRecord.invoke(record); + if (r != Result.Success) { + return r; + } + } + } + } + + // Make sure we processed all of the available data. + Contract.Assert(avail.Length == 0); + return Result.Success; + } + + /** + * Writes a RecordIO segment into a stream. + * + * @param stm The stream to write to. + * @param segment The segment header to write. + * @param produce A function to produces the record bodies for the segment. + *

+ * The function is called until either an error is encountered or it + * produces an empty body. An empty body terminates the segment. + *

+ *

If returns an error then the sequence is aborted.

+ * @param resizer Optional memory resizer for RecordIO metadata row buffers. + *

+ * Note: This should NOT be the same resizer used to process any rows as both + * blocks of memory are used concurrently. + *

+ * @return Success if the stream is written without error, the error code otherwise. + */ + + public static Task WriteRecordIOAsync(Stream stm, Segment segment, ProduceFunc produce) { + return WriteRecordIOAsync(stm, segment, produce, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public static Task WriteRecordIOAsync(this Stream stm, Segment segment, ProduceFunc + // produce, MemorySpanResizer resizer = default) + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.Stream is input or + // output: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public static Task WriteRecordIOAsync(Stream stm, Segment segment, ProduceFunc produce, + MemorySpanResizer resizer) { + return Microsoft.Azure.Cosmos.Serialization.HybridRow.RecordIO.RecordIOStream.WriteRecordIOAsync(stm, + segment.clone(), index -> + { + ReadOnlyMemory buffer; + tangible.OutObject> tempOut_buffer = new tangible.OutObject>(); + buffer = tempOut_buffer.argValue; + return new ValueTask<(Result, ReadOnlyMemory < Byte >) > ((r,buffer)) + }, resizer); + } + + /** + * Writes a RecordIO segment into a stream. + * + * @param stm The stream to write to. + * @param segment The segment header to write. + * @param produce A function to produces the record bodies for the segment. + *

+ * The function is called until either an error is encountered or it + * produces an empty body. An empty body terminates the segment. + *

+ *

If returns an error then the sequence is aborted.

+ * @param resizer Optional memory resizer for RecordIO metadata row buffers. + *

+ * Note: This should NOT be the same resizer used to process any rows as both + * blocks of memory are used concurrently. + *

+ * @return Success if the stream is written without error, the error code otherwise. + */ + + public static Task WriteRecordIOAsync(Stream stm, Segment segment, ProduceFuncAsync produce) { + return WriteRecordIOAsync(stm, segment, produce, null); + } + + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: public static async Task WriteRecordIOAsync(this Stream stm, Segment segment, + // ProduceFuncAsync produce, MemorySpanResizer resizer = default) + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public static Task WriteRecordIOAsync(OutputStream stm, Segment segment, ProduceFuncAsync produce, + MemorySpanResizer resizer) { + // Create a reusable, resizable buffer if the caller didn't provide one. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: resizer = resizer != null ? resizer : new MemorySpanResizer(); + resizer = resizer != null ? resizer : new MemorySpanResizer(); + + // Write a RecordIO stream. + Memory metadata; + tangible.OutObject> tempOut_metadata = new tangible.OutObject>(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Result r = RecordIOStream.FormatSegment(segment, resizer, out Memory metadata); + Result r = RecordIOStream.FormatSegment(segment.clone(), resizer, tempOut_metadata); + metadata = tempOut_metadata.argValue; + if (r != Result.Success) { + return r; + } + + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await stm.WriteAsync(metadata); + + long index = 0; + while (true) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ReadOnlyMemory body; + ReadOnlyMemory body; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# deconstruction assignments: + (r, body) =await produce (index++); + if (r != Result.Success) { + return r; + } + + if (body.IsEmpty) { + break; + } + + tangible.OutObject> tempOut_metadata2 = new tangible.OutObject>(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = RecordIOStream.FormatRow(body, resizer, out metadata); + r = RecordIOStream.FormatRow(body, resizer, tempOut_metadata2); + metadata = tempOut_metadata2.argValue; + if (r != Result.Success) { + return r; + } + + // Metadata and Body memory blocks should not overlap since they are both in + // play at the same time. If they do this usually means that the same resizer + // was incorrectly used for both. Check the resizer parameter passed to + // WriteRecordIOAsync for metadata. + Contract.Assert(!metadata.Span.Overlaps(body.Span)); + + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await stm.WriteAsync(metadata); + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await stm.WriteAsync(body); + } + + return Result.Success; + } + + /** + * Compute and format a record header for the given record body. + * + * @param body The body whose record header should be formatted. + * @param resizer The resizer to use in allocating a buffer for the record header. + * @param block The byte sequence of the written row buffer. + * @return Success if the write completes without error, the error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private static Result FormatRow(ReadOnlyMemory body, MemorySpanResizer resizer, out Memory block) + private static Result FormatRow(ReadOnlyMemory body, MemorySpanResizer resizer, tangible.OutObject> block) { + RowBuffer row; + tangible.OutObject tempOut_row = new tangible.OutObject(); + Result r = RecordIOFormatter.FormatRecord(body, tempOut_row, resizer); + row = tempOut_row.argValue; + if (r != Result.Success) { + block.argValue = null; + return r; + } + + block.argValue = resizer.getMemory().Slice(0, row.Length); + return Result.Success; + } + + /** + * Format a segment. + * + * @param segment The segment to format. + * @param resizer The resizer to use in allocating a buffer for the segment. + * @param block The byte sequence of the written row buffer. + * @return Success if the write completes without error, the error code otherwise. + */ + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private static Result FormatSegment(Segment segment, MemorySpanResizer resizer, out + // Memory block) + private static Result FormatSegment(Segment segment, MemorySpanResizer resizer, + tangible.OutObject> block) { + RowBuffer row; + tangible.OutObject tempOut_row = + new tangible.OutObject(); + Result r = RecordIOFormatter.FormatSegment(segment.clone(), tempOut_row, resizer); + row = tempOut_row.argValue; + if (r != Result.Success) { + block.argValue = null; + return r; + } + + block.argValue = resizer.getMemory().Slice(0, row.Length); + return Result.Success; + } + + /** + * A function that produces RecordIO record bodies. + *

+ * Record bodies are returned as memory blocks. It is expected that each block is a + * HybridRow, but any binary data is allowed. + * + * @param index The 0-based index of the record within the segment to be produced. + * @param buffer The byte sequence of the record body's row buffer. + * @return Success if the body was produced without error, the error code otherwise. + */ + @FunctionalInterface + public interface ProduceFunc { + Result invoke(long index, tangible.OutObject> buffer); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordSerializer.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordSerializer.java new file mode 100644 index 0000000..7c17e6b --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/RecordSerializer.java @@ -0,0 +1,53 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.recordio; + +import azure.data.cosmos.serialization.hybridrow.Result; + +public final class RecordSerializer { + public static Result Read(tangible.RefObject reader, tangible.OutObject obj) { + obj.argValue = null; + while (reader.argValue.Read()) { + Result r; + + // TODO: use Path tokens here. + switch (reader.argValue.getPath().toString()) { + case "length": + tangible.OutObject tempOut_Length = new tangible.OutObject(); + r = reader.argValue.ReadInt32(tempOut_Length); + obj.argValue.argValue.Length = tempOut_Length.argValue; + if (r != Result.Success) { + return r; + } + + break; + case "crc32": + tangible.OutObject tempOut_Crc32 = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = reader.ReadUInt32(out obj.Crc32); + r = reader.argValue.ReadUInt32(tempOut_Crc32); + obj.argValue.argValue.Crc32 = tempOut_Crc32.argValue; + if (r != Result.Success) { + return r; + } + + break; + } + } + + return Result.Success; + } + + public static Result Write(tangible.RefObject writer, TypeArgument typeArg, Record obj) { + Result r; + r = writer.argValue.WriteInt32("length", obj.Length); + if (r != Result.Success) { + return r; + } + + r = writer.argValue.WriteUInt32("crc32", obj.Crc32); + return r; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/Segment.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/Segment.java new file mode 100644 index 0000000..8fd7dcc --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/Segment.java @@ -0,0 +1,37 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.recordio; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1051 // Do not declare visible instance fields + + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public struct Segment +public final class Segment { + public String Comment; + public int Length; + public String SDL; + + public Segment() { + } + + public Segment(String comment, String sdl) { + this.Length = 0; + this.Comment = comment; + this.SDL = sdl; + } + + public Segment clone() { + Segment varCopy = new Segment(); + + varCopy.Length = this.Length; + varCopy.Comment = this.Comment; + varCopy.SDL = this.SDL; + + return varCopy; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/SegmentSerializer.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/SegmentSerializer.java new file mode 100644 index 0000000..54586e2 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/recordio/SegmentSerializer.java @@ -0,0 +1,101 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.recordio; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; + +public final class SegmentSerializer { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public static Result Read(Span span, LayoutResolver resolver, out Segment obj) + public static Result Read(Span span, LayoutResolver resolver, tangible.OutObject obj) { + RowBuffer row = new RowBuffer(span, HybridRowVersion.V1, resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row); + row = tempRef_row.argValue; + tangible.RefObject tempRef_reader = + new tangible.RefObject(reader); + Result tempVar = SegmentSerializer.Read(tempRef_reader, obj.clone()); + reader = tempRef_reader.argValue; + return tempVar; + } + + public static Result Read(tangible.RefObject reader, tangible.OutObject obj) { + obj.argValue = null; + while (reader.argValue.Read()) { + Result r; + + // TODO: use Path tokens here. + switch (reader.argValue.getPath().toString()) { + case "length": + tangible.OutObject tempOut_Length = new tangible.OutObject(); + r = reader.argValue.ReadInt32(tempOut_Length); + obj.argValue.argValue.Length = tempOut_Length.argValue; + if (r != Result.Success) { + return r; + } + + // If the RowBuffer isn't big enough to contain the rest of the header, then just + // return the length. + if (reader.argValue.getLength() < obj.argValue.Length) { + return Result.Success; + } + + break; + case "comment": + tangible.OutObject tempOut_Comment = new tangible.OutObject(); + r = reader.argValue.ReadString(tempOut_Comment); + obj.argValue.argValue.Comment = tempOut_Comment.argValue; + if (r != Result.Success) { + return r; + } + + break; + case "sdl": + tangible.OutObject tempOut_SDL = new tangible.OutObject(); + r = reader.argValue.ReadString(tempOut_SDL); + obj.argValue.argValue.SDL = tempOut_SDL.argValue; + if (r != Result.Success) { + return r; + } + + break; + } + } + + return Result.Success; + } + + public static Result Write(tangible.RefObject writer, TypeArgument typeArg, Segment obj) { + Result r; + if (obj.Comment != null) { + r = writer.argValue.WriteString("comment", obj.Comment); + if (r != Result.Success) { + return r; + } + } + + if (obj.SDL != null) { + r = writer.argValue.WriteString("sdl", obj.SDL); + if (r != Result.Success) { + return r; + } + } + + // Defer writing the length until all other fields of the segment header are written. + // The length is then computed based on the current size of the underlying RowBuffer. + // Because the length field is itself fixed, writing the length can never change the length. + int length = writer.argValue.getLength(); + r = writer.argValue.WriteInt32("length", length); + if (r != Result.Success) { + return r; + } + + Contract.Assert(length == writer.argValue.getLength()); + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ArrayPropertyType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ArrayPropertyType.java new file mode 100644 index 0000000..fa07797 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ArrayPropertyType.java @@ -0,0 +1,30 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * Array properties represent an unbounded set of zero or more items. + *

+ * Arrays may be typed or untyped. Within typed arrays, all items MUST be the same type. The + * type of items is specified via . Typed arrays may be stored more efficiently + * than untyped arrays. When is unspecified, the array is untyped and its items + * may be heterogeneous. + */ +public class ArrayPropertyType extends ScopePropertyType { + /** + * (Optional) type of the elements of the array, if a typed array, otherwise null. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "items")] public PropertyType Items {get;set;} + private PropertyType Items; + + public final PropertyType getItems() { + return Items; + } + + public final void setItems(PropertyType value) { + Items = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/MapPropertyType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/MapPropertyType.java new file mode 100644 index 0000000..d8f95a6 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/MapPropertyType.java @@ -0,0 +1,47 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * Map properties represent an unbounded set of zero or more key-value pairs with unique + * keys. + *

+ *

+ * Maps are typed or untyped. Within typed maps, all key MUST be the same type, and all + * values MUST be the same type. The type of both key and values is specified via + * and respectively. Typed maps may be stored more efficiently than untyped + * maps. When or is unspecified or marked + * , the map is untyped and its key and/or values may be heterogeneous. + */ +public class MapPropertyType extends ScopePropertyType { + /** + * (Optional) type of the keys of the map, if a typed map, otherwise null. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "keys")] public PropertyType Keys {get;set;} + private PropertyType Keys; + /** + * (Optional) type of the values of the map, if a typed map, otherwise null. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "values")] public PropertyType Values {get;set;} + private PropertyType Values; + + public final PropertyType getKeys() { + return Keys; + } + + public final void setKeys(PropertyType value) { + Keys = value; + } + + public final PropertyType getValues() { + return Values; + } + + public final void setValues(PropertyType value) { + Values = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Namespace.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Namespace.java new file mode 100644 index 0000000..647a0e5 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Namespace.java @@ -0,0 +1,93 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import Newtonsoft.Json.*; + +import java.util.ArrayList; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1716 // Identifiers should not match keywords + + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [JsonObject] public class Namespace +public class Namespace { + /** + * The standard settings used by the JSON parser for interpreting + * documents. + */ + private static final JsonSerializerSettings NamespaceParseSettings = new JsonSerializerSettings() { + CheckAdditionalContent =true + }; + /** + * The fully qualified identifier of the namespace. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "name")] public string Name {get;set;} + private String Name; + /** + * The version of the HybridRow Schema Definition Language used to encode this namespace. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "version")] public SchemaLanguageVersion Version {get;set;} + private SchemaLanguageVersion Version = SchemaLanguageVersion.values()[0]; + /** + * The set of schemas that make up the . + */ + private ArrayList schemas; + + /** + * Initializes a new instance of the class. + */ + public Namespace() { + this.setSchemas(new ArrayList()); + } + + public final String getName() { + return Name; + } + + public final void setName(String value) { + Name = value; + } + + /** + * The set of schemas that make up the . + *

+ * Namespaces may consist of zero or more table schemas along with zero or more UDT schemas. + * Table schemas can only reference UDT schemas defined in the same namespace. UDT schemas can + * contain nested UDTs whose schemas are defined within the same namespace. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "schemas")] public List Schemas + public final ArrayList getSchemas() { + return this.schemas; + } + + public final void setSchemas(ArrayList value) { + this.schemas = value != null ? value : new ArrayList(); + } + + public final SchemaLanguageVersion getVersion() { + return Version; + } + + public final void setVersion(SchemaLanguageVersion value) { + Version = value; + } + + /** + * Parse a JSON document and return a full namespace. + * + * @param json The JSON text to parse. + * @return A namespace containing a set of logical schemas. + */ + public static Namespace Parse(String json) { + Namespace ns = JsonConvert.DeserializeObject(json, Namespace.NamespaceParseSettings); + SchemaValidator.Validate(ns); + return ns; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ObjectPropertyType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ObjectPropertyType.java new file mode 100644 index 0000000..56c6fcc --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ObjectPropertyType.java @@ -0,0 +1,42 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import java.util.ArrayList; + +/** + * Object properties represent nested structures. + *

+ * Object properties map to multiple columns depending on the number of internal properties + * within the defined object structure. Object properties are provided as a convince in schema + * design. They are effectively equivalent to defining the same properties explicitly via + * with nested property paths. + */ +public class ObjectPropertyType extends ScopePropertyType { + /** + * A list of zero or more property definitions that define the columns within the schema. + */ + private ArrayList properties; + + /** + * Initializes a new instance of the class. + */ + public ObjectPropertyType() { + this.properties = new ArrayList(); + } + + /** + * A list of zero or more property definitions that define the columns within the schema. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "properties")] public List Properties + public final ArrayList getProperties() { + return this.properties; + } + + public final void setProperties(ArrayList value) { + this.properties = value != null ? value : new ArrayList(); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PartitionKey.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PartitionKey.java new file mode 100644 index 0000000..3ff54b7 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PartitionKey.java @@ -0,0 +1,26 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * Describes a property or set of properties used to partition the data set across machines. + */ +public class PartitionKey { + /** + * The logical path of the referenced property. + * Partition keys MUST refer to properties defined within the same . + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "path", Required = Required.Always)] public string Path {get;set;} + private String Path; + + public final String getPath() { + return Path; + } + + public final void setPath(String value) { + Path = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PrimarySortKey.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PrimarySortKey.java new file mode 100644 index 0000000..a1ff8e0 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PrimarySortKey.java @@ -0,0 +1,43 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * Describes a property or set of properties used to order the data set within a single + * partition. + */ +public class PrimarySortKey { + /** + * The logical path of the referenced property. + * Primary keys MUST refer to properties defined within the same . + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "direction", Required = Required.DisallowNull)] public + // SortDirection Direction {get;set;} + private SortDirection Direction = SortDirection.values()[0]; + /** + * The logical path of the referenced property. + * Primary keys MUST refer to properties defined within the same . + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "path", Required = Required.Always)] public string Path {get;set;} + private String Path; + + public final SortDirection getDirection() { + return Direction; + } + + public final void setDirection(SortDirection value) { + Direction = value; + } + + public final String getPath() { + return Path; + } + + public final void setPath(String value) { + Path = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PrimitivePropertyType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PrimitivePropertyType.java new file mode 100644 index 0000000..3c484e0 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PrimitivePropertyType.java @@ -0,0 +1,46 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * A primitive property. + *

+ * Primitive properties map to columns one-to-one. Primitive properties indicate how the + * column should be represented within the row. + */ +public class PrimitivePropertyType extends PropertyType { + /** + * The maximum allowable length in bytes. + *

+ * This annotation is only valid for non-fixed length types. A value of 0 means the maximum + * allowable length. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "length")][JsonConverter(typeof(StrictIntegerConverter))] public + // int Length {get;set;} + private int Length; + /** + * Storage requirements of the property. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "storage")] public StorageKind Storage {get;set;} + private StorageKind Storage = StorageKind.values()[0]; + + public final int getLength() { + return Length; + } + + public final void setLength(int value) { + Length = value; + } + + public final StorageKind getStorage() { + return Storage; + } + + public final void setStorage(StorageKind value) { + Storage = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Property.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Property.java new file mode 100644 index 0000000..128a81e --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Property.java @@ -0,0 +1,68 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1716 // Identifiers should not match keywords + + +/** + * Describes a single property definition. + */ +public class Property { + /** + * An (optional) comment describing the purpose of this property. + * Comments are for documentary purpose only and do not affect the property at runtime. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "comment", DefaultValueHandling = DefaultValueHandling + // .IgnoreAndPopulate)] public string Comment {get;set;} + private String Comment; + /** + * The logical path of this property. + *

+ * For complex properties (e.g. objects) the logical path forms a prefix to relative paths of + * properties defined within nested structures. + * + * See the logical path specification for full details on both relative and absolute paths. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "path", Required = Required.Always)] public string Path {get;set;} + private String Path; + /** + * The type of the property. + *

+ * Types may be simple (e.g. int8) or complex (e.g. object). Simple types always define a + * single column. Complex types may define one or more columns depending on their structure. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "type", Required = Required.Always)] public PropertyType + // PropertyType {get;set;} + private PropertyType PropertyType; + + public final String getComment() { + return Comment; + } + + public final void setComment(String value) { + Comment = value; + } + + public final String getPath() { + return Path; + } + + public final void setPath(String value) { + Path = value; + } + + public final PropertyType getPropertyType() { + return PropertyType; + } + + public final void setPropertyType(PropertyType value) { + PropertyType = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PropertySchemaConverter.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PropertySchemaConverter.java new file mode 100644 index 0000000..88084e6 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PropertySchemaConverter.java @@ -0,0 +1,85 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import Newtonsoft.Json.*; +import Newtonsoft.Json.Converters.*; +import Newtonsoft.Json.Linq.*; + +/** + * Helper class for parsing the polymorphic subclasses from JSON. + */ +public class PropertySchemaConverter extends JsonConverter { + @Override + public boolean getCanWrite() { + return false; + } + + @Override + public boolean CanConvert(java.lang.Class objectType) { + return objectType.isAssignableFrom(PropertyType.class); + } + + @Override + public Object ReadJson(JsonReader reader, java.lang.Class objectType, Object existingValue, + JsonSerializer serializer) { + PropertyType p; + if (reader.TokenType != JsonToken.StartObject) { + throw new JsonSerializationException(); + } + + JObject propSchema = JObject.Load(reader); + TypeKind propType; + + JToken value; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + if (!propSchema.TryGetValue("type", out value)) { + throw new JsonSerializationException("Required \"type\" property missing."); + } + + try (JsonReader typeReader = value.CreateReader()) { + typeReader.Read(); // Move to the start token + propType = TypeKind.forValue((new StringEnumConverter(true)).ReadJson(typeReader, TypeKind.class, null, + serializer)); + } + + switch (propType) { + case Array: + p = new ArrayPropertyType(); + break; + case Set: + p = new SetPropertyType(); + break; + case Map: + p = new MapPropertyType(); + break; + case Object: + p = new ObjectPropertyType(); + break; + case Tuple: + p = new TuplePropertyType(); + break; + case Tagged: + p = new TaggedPropertyType(); + break; + case Schema: + p = new UdtPropertyType(); + break; + default: + p = new PrimitivePropertyType(); + break; + } + + serializer.Populate(propSchema.CreateReader(), p); + return p; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [ExcludeFromCodeCoverage] public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + @Override + public void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer) { + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PropertyType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PropertyType.java new file mode 100644 index 0000000..0817952 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/PropertyType.java @@ -0,0 +1,62 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * The base class for property types both primitive and complex. + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [JsonConverter(typeof(PropertySchemaConverter))] public abstract class PropertyType +public abstract class PropertyType { + /** + * Api-specific type annotations for the property. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "apitype")] public string ApiType {get;set;} + private String ApiType; + /** + * True if the property can be null. + * Default: true. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DefaultValue(true)][JsonProperty(PropertyName = "nullable", DefaultValueHandling = + // DefaultValueHandling.IgnoreAndPopulate)][JsonConverter(typeof(StrictBooleanConverter))] public bool Nullable + // {get;set;} + private boolean Nullable; + /** + * The logical type of the property. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "type")] public TypeKind Type {get;set;} + private TypeKind Type = TypeKind.values()[0]; + + protected PropertyType() { + this.setNullable(true); + } + + public final String getApiType() { + return ApiType; + } + + public final void setApiType(String value) { + ApiType = value; + } + + public final boolean getNullable() { + return Nullable; + } + + public final void setNullable(boolean value) { + Nullable = value; + } + + public final TypeKind getType() { + return Type; + } + + public final void setType(TypeKind value) { + Type = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Schema.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Schema.java new file mode 100644 index 0000000..1aef147 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/Schema.java @@ -0,0 +1,235 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import Newtonsoft.Json.*; +import azure.data.cosmos.serialization.hybridrow.SchemaId; +import azure.data.cosmos.serialization.hybridrow.layouts.Layout; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutCompiler; + +import java.util.ArrayList; + +import static com.google.common.base.Preconditions.checkArgument; + +/** + * A schema describes either table or UDT metadata. + *

+ * The schema of a table or UDT describes the structure of row (i.e. which columns and the + * types of those columns). A table schema represents the description of the contents of a collection + * level row directly. UDTs described nested structured objects that may appear either within a table + * column or within another UDT (i.e. nested UDTs). + */ +public class Schema { + /** + * An (optional) comment describing the purpose of this schema. + * Comments are for documentary purpose only and do not affect the schema at runtime. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "comment", DefaultValueHandling = DefaultValueHandling + // .IgnoreAndPopulate)] public string Comment {get;set;} + private String Comment; + /** + * The name of the schema. + *

+ * The name of a schema MUST be unique within its namespace. + * + * Names must begin with an alpha-numeric character and can only contain alpha-numeric characters and + * underscores. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "name", Required = Required.Always)] public string Name {get;set;} + private String Name; + /** + * Schema-wide operations. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "options")] public SchemaOptions Options {get;set;} + private SchemaOptions Options; + /** + * The unique identifier for a schema. + * Identifiers must be unique within the scope of the database in which they are used. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "id", Required = Required.Always)] public SchemaId SchemaId {get;set;} + private SchemaId SchemaId = new SchemaId(); + /** + * The type of this schema. This value MUST be . + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [DefaultValue(TypeKind.Schema)][JsonProperty(PropertyName = "type", Required = Required + // .DisallowNull, DefaultValueHandling = DefaultValueHandling.Populate)] public TypeKind Type {get;set;} + private TypeKind Type = TypeKind.values()[0]; + /** + * The version of the HybridRow Schema Definition Language used to encode this schema. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "version")] public SchemaLanguageVersion Version {get;set;} + private SchemaLanguageVersion Version = SchemaLanguageVersion.values()[0]; + /** + * An (optional) list of zero or more logical paths that form the partition key. + */ + private ArrayList partitionKeys; + /** + * An (optional) list of zero or more logical paths that form the primary sort key. + */ + private ArrayList primaryKeys; + /** + * A list of zero or more property definitions that define the columns within the schema. + */ + private ArrayList properties; + /** + * An (optional) list of zero or more logical paths that hold data shared by all documents that have the same + * partition key. + */ + private ArrayList staticKeys; + + /** + * Initializes a new instance of the class. + */ + public Schema() { + this.setType(TypeKind.Schema); + this.properties = new ArrayList(); + this.partitionKeys = new ArrayList(); + this.primaryKeys = new ArrayList(); + this.staticKeys = new ArrayList(); + } + + public final String getComment() { + return Comment; + } + + public final void setComment(String value) { + Comment = value; + } + + public final String getName() { + return Name; + } + + public final void setName(String value) { + Name = value; + } + + public final SchemaOptions getOptions() { + return Options; + } + + public final void setOptions(SchemaOptions value) { + Options = value; + } + + /** + * An (optional) list of zero or more logical paths that form the partition key. + * All paths referenced MUST map to a property within the schema. + * + * This field is never null. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "partitionkeys")] public List PartitionKeys + public final ArrayList getPartitionKeys() { + return this.partitionKeys; + } + + public final void setPartitionKeys(ArrayList value) { + this.partitionKeys = value != null ? value : new ArrayList(); + } + + /** + * An (optional) list of zero or more logical paths that form the primary sort key. + * All paths referenced MUST map to a property within the schema. + * + * This field is never null. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "primarykeys")] public List PrimarySortKeys + public final ArrayList getPrimarySortKeys() { + return this.primaryKeys; + } + + public final void setPrimarySortKeys(ArrayList value) { + this.primaryKeys = value != null ? value : new ArrayList(); + } + + /** + * A list of zero or more property definitions that define the columns within the schema. + * This field is never null. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "properties")] public List Properties + public final ArrayList getProperties() { + return this.properties; + } + + public final void setProperties(ArrayList value) { + this.properties = value != null ? value : new ArrayList(); + } + + public final SchemaId getSchemaId() { + return SchemaId; + } + + public final void setSchemaId(SchemaId value) { + SchemaId = value.clone(); + } + + /** + * An (optional) list of zero or more logical paths that hold data shared by all documents with same partition key. + * All paths referenced MUST map to a property within the schema. + * + * This field is never null. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "statickeys", DefaultValueHandling = DefaultValueHandling + // .IgnoreAndPopulate)] public List StaticKeys + public final ArrayList getStaticKeys() { + return this.staticKeys; + } + + public final void setStaticKeys(ArrayList value) { + this.staticKeys = value != null ? value : new ArrayList(); + } + + public final TypeKind getType() { + return Type; + } + + public final void setType(TypeKind value) { + Type = value; + } + + public final SchemaLanguageVersion getVersion() { + return Version; + } + + public final void setVersion(SchemaLanguageVersion value) { + Version = value; + } + + /** + * Compiles this logical schema into a physical layout that can be used to read and write + * rows. + * + * @param ns The namespace within which this schema is defined. + * @return The layout for the schema. + */ + public final Layout Compile(Namespace ns) { + checkArgument(ns != null); + checkArgument(ns.getSchemas().contains(this)); + + return LayoutCompiler.Compile(ns, this); + } + + /** + * Parse a JSON fragment and return a schema. + * + * @param json The JSON text to parse. + * @return A logical schema. + */ + public static Schema Parse(String json) { + return JsonConvert.DeserializeObject(json); + + // TODO: perform structural validation on the Schema after JSON parsing. + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaException.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaException.java new file mode 100644 index 0000000..a63d61f --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaException.java @@ -0,0 +1,26 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import java.io.Serializable; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [Serializable][ExcludeFromCodeCoverage] public sealed class SchemaException : Exception +public final class SchemaException extends RuntimeException implements Serializable { + public SchemaException() { + } + + public SchemaException(String message) { + super(message); + } + + public SchemaException(String message, RuntimeException innerException) { + super(message, innerException); + } + + private SchemaException(SerializationInfo info, StreamingContext context) { + super(info, context); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaHash.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaHash.java new file mode 100644 index 0000000..b49912f --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaHash.java @@ -0,0 +1,232 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +public final class SchemaHash { + /** Computes the logical hash for a logical schema. + @param ns The namespace within which is defined. + @param schema The logical schema to compute the hash of. + @param seed The seed to initialized the hash function. + @return The logical 128-bit hash as a two-tuple (low, high). + */ + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // public static(ulong low, ulong high) ComputeHash(Namespace ns, Schema schema, (ulong low, ulong high) seed = + // default) + // { + // (ulong low, ulong high) hash = seed; + // hash = MurmurHash3.Hash128(schema.SchemaId, hash); + // hash = MurmurHash3.Hash128(schema.Type, hash); + // hash = SchemaHash.ComputeHash(ns, schema.Options, hash); + // if (schema.PartitionKeys != null) + // { + // foreach (PartitionKey p in schema.PartitionKeys) + // { + // hash = SchemaHash.ComputeHash(ns, p, hash); + // } + // } + // + // if (schema.PrimarySortKeys != null) + // { + // foreach (PrimarySortKey p in schema.PrimarySortKeys) + // { + // hash = SchemaHash.ComputeHash(ns, p, hash); + // } + // } + // + // if (schema.StaticKeys != null) + // { + // foreach (StaticKey p in schema.StaticKeys) + // { + // hash = SchemaHash.ComputeHash(ns, p, hash); + // } + // } + // + // if (schema.Properties != null) + // { + // foreach (Property p in schema.Properties) + // { + // hash = SchemaHash.ComputeHash(ns, p, hash); + // } + // } + // + // return hash; + // } + + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // private static(ulong low, ulong high) ComputeHash(Namespace ns, SchemaOptions options, (ulong low, ulong high) + // seed = default) + // { + // (ulong low, ulong high) hash = seed; + // hash = MurmurHash3.Hash128(options == null ? null : options.DisallowUnschematized ?? false, hash); + // hash = MurmurHash3.Hash128(options == null ? null : options.EnablePropertyLevelTimestamp ?? false, + // hash); + // if (options == null ? null : options.DisableSystemPrefix ?? false) + // { + // hash = MurmurHash3.Hash128(true, hash); + // } + // + // return hash; + // } + + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // private static(ulong low, ulong high) ComputeHash(Namespace ns, Property p, (ulong low, ulong high) seed = + // default) + // { + // Contract.Requires(p != null); + // (ulong low, ulong high) hash = seed; + // hash = MurmurHash3.Hash128(p.Path, hash); + // hash = SchemaHash.ComputeHash(ns, p.PropertyType, hash); + // return hash; + // } + + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // private static(ulong low, ulong high) ComputeHash(Namespace ns, PropertyType p, (ulong low, ulong high) seed = + // default) + // { + // Contract.Requires(p != null); + // (ulong low, ulong high) hash = seed; + // hash = MurmurHash3.Hash128(p.Type, hash); + // hash = MurmurHash3.Hash128(p.Nullable, hash); + // if (p.ApiType != null) + // { + // hash = MurmurHash3.Hash128(p.ApiType, hash); + // } + // + // switch (p) + // { + // case PrimitivePropertyType pp: + // hash = MurmurHash3.Hash128(pp.Storage, hash); + // hash = MurmurHash3.Hash128(pp.Length, hash); + // break; + // case ScopePropertyType pp: + // hash = MurmurHash3.Hash128(pp.Immutable, hash); + // switch (p) + // { + // case ArrayPropertyType spp: + // if (spp.Items != null) + // { + // hash = SchemaHash.ComputeHash(ns, spp.Items, hash); + // } + // + // break; + // case ObjectPropertyType spp: + // if (spp.Properties != null) + // { + // foreach (Property opp in spp.Properties) + // { + // hash = SchemaHash.ComputeHash(ns, opp, hash); + // } + // } + // + // break; + // case MapPropertyType spp: + // if (spp.Keys != null) + // { + // hash = SchemaHash.ComputeHash(ns, spp.Keys, hash); + // } + // + // if (spp.Values != null) + // { + // hash = SchemaHash.ComputeHash(ns, spp.Values, hash); + // } + // + // break; + // case SetPropertyType spp: + // if (spp.Items != null) + // { + // hash = SchemaHash.ComputeHash(ns, spp.Items, hash); + // } + // + // break; + // case TaggedPropertyType spp: + // if (spp.Items != null) + // { + // foreach (PropertyType pt in spp.Items) + // { + // hash = SchemaHash.ComputeHash(ns, pt, hash); + // } + // } + // + // break; + // case TuplePropertyType spp: + // if (spp.Items != null) + // { + // foreach (PropertyType pt in spp.Items) + // { + // hash = SchemaHash.ComputeHash(ns, pt, hash); + // } + // } + // + // break; + // case UdtPropertyType spp: + // Schema udtSchema; + // if (spp.SchemaId == SchemaId.Invalid) + // { + // udtSchema = ns.Schemas.Find(s => s.Name == spp.Name); + // } + // else + // { + // udtSchema = ns.Schemas.Find(s => s.SchemaId == spp.SchemaId); + // if (udtSchema.Name != spp.Name) + // { + // throw new Exception(string.Format("Ambiguous schema reference: '{0}:{1}'", spp + // .Name, spp.SchemaId)); + // } + // } + // + // if (udtSchema == null) + // { + // throw new Exception(string.Format("Cannot resolve schema reference '{0}:{1}'", spp + // .Name, spp.SchemaId)); + // } + // + // hash = SchemaHash.ComputeHash(ns, udtSchema, hash); + // break; + // } + // + // break; + // } + // + // return hash; + // } + + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // private static(ulong low, ulong high) ComputeHash(Namespace ns, PartitionKey key, (ulong low, ulong high) seed + // = default) + // { + // (ulong low, ulong high) hash = seed; + // if (key != null) + // { + // hash = MurmurHash3.Hash128(key.Path, hash); + // } + // + // return hash; + // } + + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // private static(ulong low, ulong high) ComputeHash(Namespace ns, PrimarySortKey key, (ulong low, ulong high) seed = default) + // { + // (ulong low, ulong high) hash = seed; + // if (key != null) + // { + // hash = MurmurHash3.Hash128(key.Path, hash); + // hash = MurmurHash3.Hash128(key.Direction, hash); + // } + // + // return hash; + // } + + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // private static(ulong low, ulong high) ComputeHash(Namespace ns, StaticKey key, (ulong low, ulong high) seed = default) + // { + // (ulong low, ulong high) hash = seed; + // if (key != null) + // { + // hash = MurmurHash3.Hash128(key.Path, hash); + // } + // + // return hash; + // } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaLanguageVersion.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaLanguageVersion.java new file mode 100644 index 0000000..3007315 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaLanguageVersion.java @@ -0,0 +1,51 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1028 // Enum Storage should be Int32 + + +/** + * Versions of the HybridRow Schema Description Language. + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [JsonConverter(typeof(StringEnumConverter), true)] public enum SchemaLanguageVersion : byte +//C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: +//ORIGINAL LINE: [JsonConverter(typeof(StringEnumConverter), true)] public enum SchemaLanguageVersion : byte +public enum SchemaLanguageVersion { + /** + * Initial version of the HybridRow Schema Description Lanauge. + */ + V1((byte)0); + + public static final int SIZE = java.lang.Byte.SIZE; + private static java.util.HashMap mappings; + private byte byteValue; + + SchemaLanguageVersion(byte value) { + byteValue = value; + getMappings().put(value, this); + } + + public byte getValue() { + return byteValue; + } + + public static SchemaLanguageVersion forValue(byte value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (SchemaLanguageVersion.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaOptions.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaOptions.java new file mode 100644 index 0000000..b94d2d9 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaOptions.java @@ -0,0 +1,67 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * Describes the set of options that apply to the entire schema and the way it is validated. + */ +public class SchemaOptions { + /** + * If the is value true, then disables prefixing the system properties with a prefix __sys_ + * for reserved properties owned by the store layer. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "disableSystemPrefix", DefaultValueHandling = DefaultValueHandling + // .IgnoreAndPopulate)][JsonConverter(typeof(StrictBooleanConverter))] public bool DisableSystemPrefix {get;set;} + private boolean DisableSystemPrefix; + /** + * If true then structural schema validation is enabled. + *

+ * When structural schema validation is enabled then attempting to store an unschematized + * path in the row, or a value whose type does not conform to the type constraints defined for that + * path within the schema will lead to a schema validation error. When structural schema validation is + * NOT enabled, then storing an unschematized path or non-confirming value will lead to a sparse + * column override of the path. The value will be stored (and any existing value at that path will be + * overwritten). No error will be given. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "disallowUnschematized")][JsonConverter(typeof + // (StrictBooleanConverter))] public bool DisallowUnschematized {get;set;} + private boolean DisallowUnschematized; + /** + * If set and has the value true, then triggers behavior in the Schema that acts based on property + * level timestamps. In Cassandra, this means that new columns are added for each top level property + * that has values of the client side timestamp. This is then used in conflict resolution to independently + * resolve each property based on the timestamp value of that property. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "enablePropertyLevelTimestamp")][JsonConverter(typeof + // (StrictBooleanConverter))] public bool EnablePropertyLevelTimestamp {get;set;} + private boolean EnablePropertyLevelTimestamp; + + public final boolean getDisableSystemPrefix() { + return DisableSystemPrefix; + } + + public final void setDisableSystemPrefix(boolean value) { + DisableSystemPrefix = value; + } + + public final boolean getDisallowUnschematized() { + return DisallowUnschematized; + } + + public final void setDisallowUnschematized(boolean value) { + DisallowUnschematized = value; + } + + public final boolean getEnablePropertyLevelTimestamp() { + return EnablePropertyLevelTimestamp; + } + + public final void setEnablePropertyLevelTimestamp(boolean value) { + EnablePropertyLevelTimestamp = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaValidator.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaValidator.java new file mode 100644 index 0000000..dad528b --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SchemaValidator.java @@ -0,0 +1,277 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +import java.util.HashMap; + +public final class SchemaValidator { +HashMap ids +HashMap ids>schemas, + HashMap ids) +HashMap ids + + { + for (Schema s : ns.getSchemas()) { + SchemaValidator.Visit(s, schemas, ids); + } + }>schemas, + + { + ValidateAssert.AreEqual(s.getType(), TypeKind.Schema, String.format("The type of a schema MUST be %1$s: %2$s" + , TypeKind.Schema, s.getType())); + HashMap pathDupCheck = new HashMap(s.getProperties().size()); + for (Property p : s.getProperties()) { + ValidateAssert.DuplicateCheck(p.getPath(), p, pathDupCheck, "Property path", "Schema"); + } + + for (PartitionKey pk : s.getPartitionKeys()) { + ValidateAssert.Exists(pk.getPath(), pathDupCheck, "Partition key column", "Schema"); + } + + for (PrimarySortKey ps : s.getPrimarySortKeys()) { + ValidateAssert.Exists(ps.getPath(), pathDupCheck, "Primary sort key column", "Schema"); + } + + for (StaticKey sk : s.getStaticKeys()) { + ValidateAssert.Exists(sk.getPath(), pathDupCheck, "Static key column", "Schema"); + } + + for (Property p : s.getProperties()) { + SchemaValidator.Visit(p, s, schemas, ids); + } + }) + + { + ValidateAssert.IsValidIdentifier(p.getPath(), "Property path"); + SchemaValidator.Visit(p.getPropertyType(), null, schemas, ids); + } + + { + switch (p) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case PrimitivePropertyType pp: + case PrimitivePropertyType + pp: + ValidateAssert.IsTrue(pp.Length >= 0, "Length MUST be positive"); + if (parent != null) { + ValidateAssert.AreEqual(pp.Storage, StorageKind.Sparse, String.format("Nested fields MUST have " + + "storage %1$s", StorageKind.Sparse)); + } + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case ArrayPropertyType ap: + case ArrayPropertyType + ap: + if (ap.Items != null) { + SchemaValidator.Visit(ap.Items, p, schemas, ids); + } + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case MapPropertyType mp: + case MapPropertyType + mp: + SchemaValidator.Visit(mp.keySet(), p, schemas, ids); + SchemaValidator.Visit(mp.Values, p, schemas, ids); + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case SetPropertyType sp: + case SetPropertyType + sp: + SchemaValidator.Visit(sp.Items, p, schemas, ids); + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case TaggedPropertyType gp: + case TaggedPropertyType + gp: + for (PropertyType item : gp.Items) { + SchemaValidator.Visit(item, p, schemas, ids); + } + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case TuplePropertyType tp: + case TuplePropertyType + tp: + for (PropertyType item : tp.Items) { + SchemaValidator.Visit(item, p, schemas, ids); + } + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case ObjectPropertyType op: + case ObjectPropertyType + op: + HashMap pathDupCheck = new HashMap(op.Properties.Count); + for (Property nested : op.Properties) { + ValidateAssert.DuplicateCheck(nested.getPath(), nested, pathDupCheck, "Property path", "Object"); + SchemaValidator.Visit(nested.getPropertyType(), p, schemas, ids); + } + + break; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case UdtPropertyType up: + case UdtPropertyType + up: + ValidateAssert.Exists((up.Name, up.SchemaId), schemas, "Schema reference", "Namespace") + if (azure.data.cosmos.serialization.hybridrow.SchemaId.opNotEquals(up.SchemaId, + SchemaId.Invalid)) { + Schema s = ValidateAssert.Exists(up.SchemaId, ids, "Schema id", "Namespace"); + ValidateAssert.AreEqual(up.Name, s.getName(), String.format("Schema name '%1$s' does not match " + + "the name of schema with id '%2$s': %3$s", up.Name, up.SchemaId, s.getName())); + } + + break; + default: + Contract.Fail("Unknown property type"); + break; + } + }>schemas, + + public static void Validate(Namespace ns) { + HashMap nameVersioningCheck = new HashMap(ns.getSchemas().size()); + HashMap< (String, SchemaId), + Schema > nameDupCheck = new HashMap<(String, SchemaId), Schema > (ns.getSchemas().size()); + HashMap idDupCheck = new HashMap(ns.getSchemas().size()); + for (Schema s : ns.getSchemas()) { + ValidateAssert.IsValidSchemaId(s.getSchemaId().clone(), "Schema id"); + ValidateAssert.IsValidIdentifier(s.getName(), "Schema name"); + ValidateAssert.DuplicateCheck(s.getSchemaId().clone(), s, idDupCheck, "Schema id", "Namespace"); + ValidateAssert.DuplicateCheck((s.getName(), s.getSchemaId().clone()), s, nameDupCheck, "Schema reference" + , "Namespace") + + // Count the versions of each schema by name. + int count; + count = nameVersioningCheck.get(s.getName()); + nameVersioningCheck.put(s.getName(), count + 1); + } + + // Enable id-less Schema references for all types with a unique version in the namespace. + for (Schema s : ns.getSchemas()) { + if (nameVersioningCheck.get(s.getName()).equals(1)) { + ValidateAssert.DuplicateCheck((s.getName(), SchemaId.Invalid), s, nameDupCheck, "Schema reference", + "Namespace") + } + } + + SchemaValidator.Visit(ns, nameDupCheck, idDupCheck); + }) + +/** + * Visit an entire namespace and validate its constraints. + * + * @param ns The to validate. + * @param schemas A map from schema names within the namespace to their schemas. + * @param ids A map from schema ids within the namespace to their schemas. + */ + private static void Visit(Namespace ns, HashMap<(String, SchemaId),Schema + + /** + * Visit a single schema and validate its constraints. + * + * @param s The to validate. + * @param schemas A map from schema names within the namespace to their schemas. + * @param ids A map from schema ids within the namespace to their schemas. + */ + private static void Visit(Schema s, HashMap<(String, SchemaId),Schema>schemas, + +private static void Visit(Property p, Schema s, HashMap<(String, SchemaId),Schema) + +private static void Visit(PropertyType p, PropertyType parent, HashMap<(String, SchemaId),Schema + + private static class ValidateAssert { + /** + * Validate two values are equal. + * Type of the values to compare. + * + * @param left The left value to compare. + * @param right The right value to compare. + * @param message Diagnostic message if the comparison fails. + */ + public static void AreEqual(T left, T right, String message) { + if (!left.equals(right)) { + throw new SchemaException(message); + } + } + + /** + * Validate does not already appear within the given scope. + * The type of the keys within the scope. + * The type of the values within the scope. + * + * @param key The key to check. + * @param value The value to add to the scope if there is no duplicate. + * @param scope The set of existing values within the scope. + * @param label Diagnostic label describing . + * @param scopeLabel Diagnostic label describing . + */ + public static void DuplicateCheck(TKey key, TValue value, HashMap scope, String label, String scopeLabel) { + if (scope.containsKey(key)) { + throw new SchemaException(String.format("%1$s must be unique within a %2$s: %3$s", label, scopeLabel, key)); + } + + scope.put(key, value); + } + + /** + * Validate does appear within the given scope. + * The type of the keys within the scope. + * The type of the values within the scope. + * + * @param key The key to check. + * @param scope The set of existing values within the scope. + * @param label Diagnostic label describing . + * @param scopeLabel Diagnostic label describing . + */ + public static TValue Exists(TKey key, HashMap scope, String label, String scopeLabel) { + TValue value; + if (!(scope.containsKey(key) && (value = scope.get(key)) == value)) { + throw new SchemaException(String.format("%1$s must exist within a %2$s: %3$s", label, scopeLabel, key)); + } + + return value; + } + + /** + * Validate a predicate is true. + * + * @param predicate The predicate to check. + * @param message Diagnostic message if the comparison fails. + */ + public static void IsTrue(boolean predicate, String message) { + if (!predicate) { + throw new SchemaException(message); + } + } + + /** + * Validate contains only characters valid in a schema + * identifier. + * + * @param identifier The identifier to check. + * @param label Diagnostic label describing . + */ + public static void IsValidIdentifier(String identifier, String label) { + if (tangible.StringHelper.isNullOrWhiteSpace(identifier)) { + throw new SchemaException(String.format("%1$s must be a valid identifier: %2$s", label, identifier)); + } + } + + /** + * Validate is a valid . + * + * @param id The id to check. + * @param label Diagnostic label describing . + */ + public static void IsValidSchemaId(SchemaId id, String label) { + if (azure.data.cosmos.serialization.hybridrow.SchemaId.opEquals(id.clone(), SchemaId.Invalid)) { + throw new SchemaException(String.format("%1$s cannot be 0", label)); + } + } + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ScopePropertyType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ScopePropertyType.java new file mode 100644 index 0000000..7c67cdf --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/ScopePropertyType.java @@ -0,0 +1,24 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +public abstract class ScopePropertyType extends PropertyType { + /** + * True if the property's child elements cannot be mutated in place. + * Immutable properties can still be replaced in their entirety. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "immutable")][JsonConverter(typeof(StrictBooleanConverter))] public + // bool Immutable {get;set;} + private boolean Immutable; + + public final boolean getImmutable() { + return Immutable; + } + + public final void setImmutable(boolean value) { + Immutable = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SetPropertyType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SetPropertyType.java new file mode 100644 index 0000000..33f7801 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SetPropertyType.java @@ -0,0 +1,33 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * Set properties represent an unbounded set of zero or more unique items. + *

+ * Sets may be typed or untyped. Within typed sets, all items MUST be the same type. The + * type of items is specified via . Typed sets may be stored more efficiently + * than untyped sets. When is unspecified, the set is untyped and its items + * may be heterogeneous. + *

+ * Each item within a set must be unique. Uniqueness is defined by the HybridRow encoded sequence + * of bytes for the item. + */ +public class SetPropertyType extends ScopePropertyType { + /** + * (Optional) type of the elements of the set, if a typed set, otherwise null. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "items")] public PropertyType Items {get;set;} + private PropertyType Items; + + public final PropertyType getItems() { + return Items; + } + + public final void setItems(PropertyType value) { + Items = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SortDirection.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SortDirection.java new file mode 100644 index 0000000..6a48557 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/SortDirection.java @@ -0,0 +1,54 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * Describes the sort order direction. + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [JsonConverter(typeof(StringEnumConverter), true)] public enum SortDirection +public enum SortDirection { + /** + * Sorts from the lowest to the highest value. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "asc")] Ascending = 0, + Ascending(0), + + /** + * Sorts from the highests to the lowest value. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "desc")] Descending, + Descending(1); + + public static final int SIZE = java.lang.Integer.SIZE; + private static java.util.HashMap mappings; + private int intValue; + + SortDirection(int value) { + intValue = value; + getMappings().put(value, this); + } + + public int getValue() { + return intValue; + } + + public static SortDirection forValue(int value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (SortDirection.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StaticKey.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StaticKey.java new file mode 100644 index 0000000..48b81b0 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StaticKey.java @@ -0,0 +1,27 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * Describes a property or set of properties whose values MUST be the same for all rows that share the same partition + * key. + */ +public class StaticKey { + /** + * The logical path of the referenced property. + * Static path MUST refer to properties defined within the same . + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "path", Required = Required.Always)] public string Path {get;set;} + private String Path; + + public final String getPath() { + return Path; + } + + public final void setPath(String value) { + Path = value; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StorageKind.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StorageKind.java new file mode 100644 index 0000000..fce9e45 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StorageKind.java @@ -0,0 +1,72 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * Describes the storage placement for primitive properties. + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [JsonConverter(typeof(StringEnumConverter), true)] public enum StorageKind +public enum StorageKind { + /** + * The property defines a sparse column. + *

+ * Columns marked consume no space in the row when not present. When + * present they appear in an unordered linked list at the end of the row. Access time for + * columns is proportional to the number of columns in the + * row. + */ + Sparse(0), + + /** + * The property is a fixed-length, space-reserved column. + *

+ * The column will consume 1 null-bit, and its byte-width regardless of whether the value is + * present in the row. + */ + Fixed(1), + + /** + * The property is a variable-length column. + *

+ * The column will consume 1 null-bit regardless of whether the value is present. When the value is + * present it will also consume a variable number of bytes to encode the length preceding the actual + * value. + *

+ * When a long value is marked then a null-bit is reserved and + * the value is optionally encoded as if small enough to fit, otherwise the + * null-bit is set and the value is encoded as . + *

+ */ + Variable(2); + + public static final int SIZE = java.lang.Integer.SIZE; + private static java.util.HashMap mappings; + private int intValue; + + StorageKind(int value) { + intValue = value; + getMappings().put(value, this); + } + + public int getValue() { + return intValue; + } + + public static StorageKind forValue(int value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (StorageKind.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StrictBooleanConverter.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StrictBooleanConverter.java new file mode 100644 index 0000000..773f9d4 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StrictBooleanConverter.java @@ -0,0 +1,38 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import Newtonsoft.Json.*; + +public class StrictBooleanConverter extends JsonConverter { + @Override + public boolean getCanWrite() { + return false; + } + + @Override + public boolean CanConvert(java.lang.Class objectType) { + return objectType == Boolean.class; + } + + @Override + public Object ReadJson(JsonReader reader, java.lang.Class objectType, Object existingValue, + JsonSerializer serializer) { + switch (reader.TokenType) { + case JsonToken.Boolean: + return serializer.Deserialize(reader, objectType); + default: + throw new JsonSerializationException(String.format("Token \"%1$s\" of type %2$s was not a JSON bool", + reader.Value, reader.TokenType)); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [ExcludeFromCodeCoverage] public override void WriteJson(JsonWriter writer, object value, + // JsonSerializer serializer) + @Override + public void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer) { + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StrictIntegerConverter.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StrictIntegerConverter.java new file mode 100644 index 0000000..5dcf291 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/StrictIntegerConverter.java @@ -0,0 +1,48 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import Newtonsoft.Json.*; + +import java.math.BigInteger; + +public class StrictIntegerConverter extends JsonConverter { + @Override + public boolean getCanWrite() { + return false; + } + + @Override + public boolean CanConvert(java.lang.Class objectType) { + return StrictIntegerConverter.IsIntegerType(objectType); + } + + @Override + public Object ReadJson(JsonReader reader, java.lang.Class objectType, Object existingValue, + JsonSerializer serializer) { + switch (reader.TokenType) { + case JsonToken.Integer: + return serializer.Deserialize(reader, objectType); + default: + throw new JsonSerializationException(String.format("Token \"%1$s\" of type %2$s was not a JSON " + + "integer", reader.Value, reader.TokenType)); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [ExcludeFromCodeCoverage] public override void WriteJson(JsonWriter writer, object value, + // JsonSerializer serializer) + @Override + public void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer) { + } + + private static boolean IsIntegerType(java.lang.Class type) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: if (type == typeof(long) || type == typeof(ulong) || type == typeof(int) || type == typeof + // (uint) || type == typeof(short) || type == typeof(ushort) || type == typeof(byte) || type == typeof(sbyte) + // || type == typeof(BigInteger)) + return type == Long.class || type == Long.class || type == Integer.class || type == Integer.class || type == Short.class || type == Short.class || type == Byte.class || type == Byte.class || type == BigInteger.class; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TaggedPropertyType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TaggedPropertyType.java new file mode 100644 index 0000000..1015279 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TaggedPropertyType.java @@ -0,0 +1,42 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import java.util.ArrayList; + +/** + * Tagged properties pair one or more typed values with an API-specific uint8 type code. + *

+ * The uint8 type code is implicitly in position 0 within the resulting tagged and should not + * be specified in . + */ +public class TaggedPropertyType extends ScopePropertyType { + public static final int MaxTaggedArguments = 2; + public static final int MinTaggedArguments = 1; + /** + * Types of the elements of the tagged in element order. + */ + private ArrayList items; + + /** + * Initializes a new instance of the class. + */ + public TaggedPropertyType() { + this.items = new ArrayList(); + } + + /** + * Types of the elements of the tagged in element order. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "items")] public List Items + public final ArrayList getItems() { + return this.items; + } + + public final void setItems(ArrayList value) { + this.items = value != null ? value : new ArrayList(); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TuplePropertyType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TuplePropertyType.java new file mode 100644 index 0000000..2e411c4 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TuplePropertyType.java @@ -0,0 +1,37 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import java.util.ArrayList; + +/** + * Tuple properties represent a typed, finite, ordered set of two or more items. + */ +public class TuplePropertyType extends ScopePropertyType { + /** + * Types of the elements of the tuple in element order. + */ + private ArrayList items; + + /** + * Initializes a new instance of the class. + */ + public TuplePropertyType() { + this.items = new ArrayList(); + } + + /** + * Types of the elements of the tuple in element order. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "items")] public List Items + public final ArrayList getItems() { + return this.items; + } + + public final void setItems(ArrayList value) { + this.items = value != null ? value : new ArrayList(); + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TypeKind.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TypeKind.java new file mode 100644 index 0000000..27f8677 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/TypeKind.java @@ -0,0 +1,227 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +/** + * Describes the logical type of a property. + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [JsonConverter(typeof(StringEnumConverter), true)] public enum TypeKind +public enum TypeKind { + /** + * Reserved. + */ + Invalid(0), + + /** + * The literal null. + *

+ * When used as a fixed column, only a presence bit is allocated. When used as a sparse + * column, a sparse value with 0-length payload is written. + */ + Null(1), + + /** + * A boolean property. Boolean properties are allocated a single bit when schematized within + * a row. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "bool")] Boolean, + Boolean(2), + + /** + * 8-bit signed integer. + */ + Int8(3), + + /** + * 16-bit signed integer. + */ + Int16(4), + + /** + * 32-bit signed integer. + */ + Int32(5), + + /** + * 64-bit signed integer. + */ + Int64(6), + + /** + * 8-bit unsigned integer. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "uint8")] UInt8, + UInt8(7), + + /** + * 16-bit unsigned integer. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "uint16")] UInt16, + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [EnumMember(Value = "uint16")] UInt16, + UInt16(8), + + /** + * 32-bit unsigned integer. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "uint32")] UInt32, + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [EnumMember(Value = "uint32")] UInt32, + UInt32(9), + + /** + * 64-bit unsigned integer. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "uint64")] UInt64, + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [EnumMember(Value = "uint64")] UInt64, + UInt64(10), + + /** + * Variable length encoded signed integer. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "varint")] VarInt, + VarInt(11), + + /** + * Variable length encoded unsigned integer. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "varuint")] VarUInt, + VarUInt(12), + + /** + * 32-bit IEEE 754 floating point value. + */ + Float32(13), + + /** + * 64-bit IEEE 754 floating point value. + */ + Float64(14), + + /** + * 128-bit IEEE 754-2008 floating point value. + */ + Float128(15), + + /** + * 128-bit floating point value. See + */ + Decimal(16), + + /** + * 64-bit date/time value in 100ns increments from C# epoch. See + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "datetime")] DateTime, + DateTime(17), + + /** + * 64-bit date/time value in milliseconds increments from Unix epoch. See + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "unixdatetime")] UnixDateTime, + UnixDateTime(18), + + /** + * 128-bit globally unique identifier (in little-endian byte order). + */ + Guid(19), + + /** + * 12-byte MongoDB Object Identifier (in little-endian byte order). + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [EnumMember(Value = "mongodbobjectid")] MongoDbObjectId, + MongoDbObjectId(20), + + /** + * Zero to MAX_ROW_SIZE bytes encoded as UTF-8 code points. + */ + Utf8(21), + + /** + * Zero to MAX_ROW_SIZE untyped bytes. + */ + Binary(22), + + /** + * An object property. + */ + Object(23), + + /** + * An array property, either typed or untyped. + */ + Array(24), + + /** + * A set property, either typed or untyped. + */ + Set(25), + + /** + * A map property, either typed or untyped. + */ + Map(26), + + /** + * A tuple property. Tuples are typed, finite, ordered, sets. + */ + Tuple(27), + + /** + * A tagged property. Tagged properties pair one or more typed values with an API-specific uint8 type code. + */ + Tagged(28), + + /** + * A row with schema. + * May define either a top-level table schema or a UDT (nested row). + */ + Schema(29), + + /** + * An untyped sparse field. + * May only be used to define the type within a nested scope (e.g. or . + */ + Any(30); + + public static final int SIZE = java.lang.Integer.SIZE; + private static java.util.HashMap mappings; + private int intValue; + + TypeKind(int value) { + intValue = value; + getMappings().put(value, this); + } + + public int getValue() { + return intValue; + } + + public static TypeKind forValue(int value) { + return getMappings().get(value); + } + + private static java.util.HashMap getMappings() { + if (mappings == null) { + synchronized (TypeKind.class) { + if (mappings == null) { + mappings = new java.util.HashMap(); + } + } + } + return mappings; + } +} \ No newline at end of file diff --git a/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/UdtPropertyType.java b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/UdtPropertyType.java new file mode 100644 index 0000000..04805d9 --- /dev/null +++ b/jre/src/main/java/azure/data/cosmos/serialization/hybridrow/schemas/UdtPropertyType.java @@ -0,0 +1,59 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.schemas; + +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +/** + * UDT properties represent nested structures with an independent schema. + *

+ * UDT properties include a nested row within an existing row as a column. The schema of the + * nested row may be evolved independently of the outer row. Changes to the independent schema affect + * all outer schemas where the UDT is used. + */ +public class UdtPropertyType extends ScopePropertyType { + /** + * The identifier of the UDT schema defining the structure for the nested row. + *

+ * The UDT schema MUST be defined within the same as the schema that + * references it. + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "name", Required = Required.Always)] public string Name {get;set;} + private String Name; + /** + * The unique identifier for a schema. + *

+ * Optional uniquifier if multiple versions of appears within the Namespace. + *

+ * If multiple versions of a UDT are defined within the then the globally + * unique identifier of the specific version referenced MUST be provided. + *

+ */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [JsonProperty(PropertyName = "id", Required = Required.DisallowNull, DefaultValueHandling = + // DefaultValueHandling.IgnoreAndPopulate)] public SchemaId SchemaId {get;set;} + private SchemaId SchemaId = new SchemaId(); + + public UdtPropertyType() { + this.setSchemaId(azure.data.cosmos.serialization.hybridrow.SchemaId.Invalid); + } + + public final String getName() { + return Name; + } + + public final void setName(String value) { + Name = value; + } + + public final SchemaId getSchemaId() { + return SchemaId; + } + + public final void setSchemaId(SchemaId value) { + SchemaId = value.clone(); + } +} \ No newline at end of file diff --git a/jre/src/main/java/tangible/Action0Param.java b/jre/src/main/java/tangible/Action0Param.java new file mode 100644 index 0000000..5185ea8 --- /dev/null +++ b/jre/src/main/java/tangible/Action0Param.java @@ -0,0 +1,10 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package tangible; + +@FunctionalInterface +public interface Action0Param { + void invoke(); +} \ No newline at end of file diff --git a/jre/src/main/java/tangible/Func0Param.java b/jre/src/main/java/tangible/Func0Param.java new file mode 100644 index 0000000..f9499eb --- /dev/null +++ b/jre/src/main/java/tangible/Func0Param.java @@ -0,0 +1,10 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package tangible; + +@FunctionalInterface +public interface Func0Param { + TResult invoke(); +} \ No newline at end of file diff --git a/jre/src/main/java/tangible/Func1Param.java b/jre/src/main/java/tangible/Func1Param.java new file mode 100644 index 0000000..5dd795b --- /dev/null +++ b/jre/src/main/java/tangible/Func1Param.java @@ -0,0 +1,10 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package tangible; + +@FunctionalInterface +public interface Func1Param { + TResult invoke(T t); +} \ No newline at end of file diff --git a/jre/src/main/java/tangible/ListHelper.java b/jre/src/main/java/tangible/ListHelper.java new file mode 100644 index 0000000..fb04b4b --- /dev/null +++ b/jre/src/main/java/tangible/ListHelper.java @@ -0,0 +1,142 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package tangible; + +//---------------------------------------------------------------------------------------- +// Copyright © 2007 - 2019 Tangible Software Solutions, Inc. +// This class can be used by anyone provided that the copyright notice remains intact. +// +// This class is used to convert some of the .NET List methods to Java. +//---------------------------------------------------------------------------------------- + +import java.util.ArrayList; +import java.util.function.Predicate; + +public final class ListHelper { + public static boolean exists(ArrayList source, Predicate predicate) { + for (T element : source) { + if (predicate.test(element)) { + return true; + } + } + + return false; + } + + public static T find(ArrayList source, Predicate predicate) { + for (T element : source) { + if (predicate.test(element)) { + return element; + } + } + + return null; + } + + public static ArrayList findAll(ArrayList source, Predicate predicate) { + ArrayList dest = new ArrayList(); + + for (T element : source) { + if (predicate.test(element)) { + dest.add(element); + } + } + + return dest; + } + + public static int findIndex(ArrayList source, Predicate predicate) { + for (int i = 0; i < source.size(); i++) { + if (predicate.test(source.get(i))) { + return i; + } + } + + return -1; + } + + public static int findIndex(ArrayList source, int start, Predicate predicate) { + for (int i = start; i < source.size(); i++) { + if (predicate.test(source.get(i))) { + return i; + } + } + + return -1; + } + + public static int findIndex(ArrayList source, int start, int count, Predicate predicate) { + for (int i = start; i < start + count; i++) { + if (predicate.test(source.get(i))) { + return i; + } + } + + return -1; + } + + public static T findLast(ArrayList source, Predicate predicate) { + for (int i = source.size() - 1; i > -1; i--) { + if (predicate.test(source.get(i))) { + return source.get(i); + } + } + + return null; + } + + public static int findLastIndex(ArrayList source, Predicate predicate) { + for (int i = source.size() - 1; i > -1; i--) { + if (predicate.test(source.get(i))) { + return i; + } + } + + return -1; + } + + public static int findLastIndex(ArrayList source, int start, Predicate predicate) { + for (int i = start; i > -1; i--) { + if (predicate.test(source.get(i))) { + return i; + } + } + + return -1; + } + + public static int findLastIndex(ArrayList source, int start, int count, Predicate predicate) { + for (int i = start; i > start - count; i--) { + if (predicate.test(source.get(i))) { + return i; + } + } + + return -1; + } + + public static int removeAll(ArrayList source, Predicate predicate) { + int removed = 0; + for (int i = 0; i < source.size(); i++) { + if (predicate.test(source.get(i))) { + source.remove(i); + i--; + removed++; + } + } + + return removed; + } + + public static boolean trueForAll(ArrayList source, Predicate predicate) { + for (T element : source) { + if (!predicate.test(element)) { + return false; + } + } + + return true; + } +} \ No newline at end of file diff --git a/jre/src/main/java/tangible/OutObject.java b/jre/src/main/java/tangible/OutObject.java new file mode 100644 index 0000000..6da6196 --- /dev/null +++ b/jre/src/main/java/tangible/OutObject.java @@ -0,0 +1,15 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package tangible; + +//---------------------------------------------------------------------------------------- +// Copyright © 2007 - 2019 Tangible Software Solutions, Inc. +// This class can be used by anyone provided that the copyright notice remains intact. +// +// This class is used to replicate the ability to have 'out' parameters in Java. +//---------------------------------------------------------------------------------------- +public final class OutObject { + public T argValue; +} \ No newline at end of file diff --git a/jre/src/main/java/tangible/RefObject.java b/jre/src/main/java/tangible/RefObject.java new file mode 100644 index 0000000..7086780 --- /dev/null +++ b/jre/src/main/java/tangible/RefObject.java @@ -0,0 +1,19 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package tangible; + +//---------------------------------------------------------------------------------------- +// Copyright © 2007 - 2019 Tangible Software Solutions, Inc. +// This class can be used by anyone provided that the copyright notice remains intact. +// +// This class is used to replicate the ability to pass arguments by reference in Java. +//---------------------------------------------------------------------------------------- +public final class RefObject { + public T argValue; + + public RefObject(T refArg) { + argValue = refArg; + } +} \ No newline at end of file diff --git a/jre/src/main/java/tangible/StringHelper.java b/jre/src/main/java/tangible/StringHelper.java new file mode 100644 index 0000000..ce43a4f --- /dev/null +++ b/jre/src/main/java/tangible/StringHelper.java @@ -0,0 +1,357 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package tangible; + +//---------------------------------------------------------------------------------------- +// Copyright © 2007 - 2019 Tangible Software Solutions, Inc. +// This class can be used by anyone provided that the copyright notice remains intact. +// +// This class is used to replicate some .NET string methods in Java. +//---------------------------------------------------------------------------------------- +public final class StringHelper { + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'IndexOfAny' (1 parameter version). + //------------------------------------------------------------------------------------ + public static int indexOfAny(String string, char[] anyOf) { + int lowestIndex = -1; + for (char c : anyOf) { + int index = string.indexOf(c); + if (index > -1) { + if (lowestIndex == -1 || index < lowestIndex) { + lowestIndex = index; + + if (index == 0) { + break; + } + } + } + } + + return lowestIndex; + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'IndexOfAny' (2 parameter version). + //------------------------------------------------------------------------------------ + public static int indexOfAny(String string, char[] anyOf, int startIndex) { + int indexInSubstring = indexOfAny(string.substring(startIndex), anyOf); + if (indexInSubstring == -1) { + return -1; + } else { + return indexInSubstring + startIndex; + } + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'IndexOfAny' (3 parameter version). + //------------------------------------------------------------------------------------ + public static int indexOfAny(String string, char[] anyOf, int startIndex, int count) { + int endIndex = startIndex + count; + int indexInSubstring = indexOfAny(string.substring(startIndex, endIndex), anyOf); + if (indexInSubstring == -1) { + return -1; + } else { + return indexInSubstring + startIndex; + } + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET static string method 'IsNullOrEmpty'. + //------------------------------------------------------------------------------------ + public static boolean isNullOrEmpty(String string) { + return string == null || string.length() == 0; + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET static string method 'IsNullOrWhiteSpace'. + //------------------------------------------------------------------------------------ + public static boolean isNullOrWhiteSpace(String string) { + if (string == null) { + return true; + } + + for (int index = 0; index < string.length(); index++) { + if (!Character.isWhitespace(string.charAt(index))) { + return false; + } + } + + return true; + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET static string method 'Join' (2 parameter version). + //------------------------------------------------------------------------------------ + public static String join(String separator, String[] stringArray) { + if (stringArray == null) { + return null; + } else { + return join(separator, stringArray, 0, stringArray.length); + } + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET static string method 'Join' (4 parameter version). + //------------------------------------------------------------------------------------ + public static String join(String separator, String[] stringArray, int startIndex, int count) { + String result = ""; + + if (stringArray == null) { + return null; + } + + for (int index = startIndex; index < stringArray.length && index - startIndex < count; index++) { + if (separator != null && index > startIndex) { + result += separator; + } + + if (stringArray[index] != null) { + result += stringArray[index]; + } + } + + return result; + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'LastIndexOf' (char version). + //------------------------------------------------------------------------------------ + public static int lastIndexOf(String string, char value, int startIndex, int count) { + int leftMost = startIndex + 1 - count; + int rightMost = startIndex + 1; + String substring = string.substring(leftMost, rightMost); + int lastIndexInSubstring = substring.lastIndexOf(value); + if (lastIndexInSubstring < 0) { + return -1; + } else { + return lastIndexInSubstring + leftMost; + } + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'LastIndexOf' (string version). + //------------------------------------------------------------------------------------ + public static int lastIndexOf(String string, String value, int startIndex, int count) { + int leftMost = startIndex + 1 - count; + int rightMost = startIndex + 1; + String substring = string.substring(leftMost, rightMost); + int lastIndexInSubstring = substring.lastIndexOf(value); + if (lastIndexInSubstring < 0) { + return -1; + } else { + return lastIndexInSubstring + leftMost; + } + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'LastIndexOfAny' (1 parameter version). + //------------------------------------------------------------------------------------ + public static int lastIndexOfAny(String string, char[] anyOf) { + int highestIndex = -1; + for (char c : anyOf) { + int index = string.lastIndexOf(c); + if (index > highestIndex) { + highestIndex = index; + + if (index == string.length() - 1) { + break; + } + } + } + + return highestIndex; + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'LastIndexOfAny' (2 parameter version). + //------------------------------------------------------------------------------------ + public static int lastIndexOfAny(String string, char[] anyOf, int startIndex) { + String substring = string.substring(0, startIndex + 1); + int lastIndexInSubstring = lastIndexOfAny(substring, anyOf); + if (lastIndexInSubstring < 0) { + return -1; + } else { + return lastIndexInSubstring; + } + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'LastIndexOfAny' (3 parameter version). + //------------------------------------------------------------------------------------ + public static int lastIndexOfAny(String string, char[] anyOf, int startIndex, int count) { + int leftMost = startIndex + 1 - count; + int rightMost = startIndex + 1; + String substring = string.substring(leftMost, rightMost); + int lastIndexInSubstring = lastIndexOfAny(substring, anyOf); + if (lastIndexInSubstring < 0) { + return -1; + } else { + return lastIndexInSubstring + leftMost; + } + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'PadLeft' (1 parameter version). + //------------------------------------------------------------------------------------ + public static String padLeft(String string, int totalWidth) { + return padLeft(string, totalWidth, ' '); + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'PadLeft' (2 parameter version). + //------------------------------------------------------------------------------------ + public static String padLeft(String string, int totalWidth, char paddingChar) { + StringBuilder sb = new StringBuilder(); + + while (sb.length() + string.length() < totalWidth) { + sb.append(paddingChar); + } + + sb.append(string); + return sb.toString(); + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'PadRight' (1 parameter version). + //------------------------------------------------------------------------------------ + public static String padRight(String string, int totalWidth) { + return padRight(string, totalWidth, ' '); + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'PadRight' (2 parameter version). + //------------------------------------------------------------------------------------ + public static String padRight(String string, int totalWidth, char paddingChar) { + StringBuilder sb = new StringBuilder(string); + + while (sb.length() < totalWidth) { + sb.append(paddingChar); + } + + return sb.toString(); + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'Remove' (1 parameter version). + //------------------------------------------------------------------------------------ + public static String remove(String string, int start) { + return string.substring(0, start); + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'Remove' (2 parameter version). + //------------------------------------------------------------------------------------ + public static String remove(String string, int start, int count) { + return string.substring(0, start) + string.substring(start + count); + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string constructor which repeats a character. + //------------------------------------------------------------------------------------ + public static String repeatChar(char charToRepeat, int count) { + String newString = ""; + for (int i = 1; i <= count; i++) { + newString += charToRepeat; + } + return newString; + } + + //------------------------------------------------------------------------------------ + // This method is used for string equality comparisons when the option + // 'Use helper 'stringsEqual' method to handle null strings' is selected + // (The Java String 'equals' method can't be called on a null instance). + //------------------------------------------------------------------------------------ + public static boolean stringsEqual(String s1, String s2) { + if (s1 == null && s2 == null) { + return true; + } else { + return s1 != null && s1.equals(s2); + } + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'Substring' when 'start' is a method + // call or calculated value to ensure that 'start' is obtained just once. + //------------------------------------------------------------------------------------ + public static String substring(String string, int start, int length) { + if (length < 0) { + throw new IndexOutOfBoundsException("Parameter length cannot be negative."); + } + + return string.substring(start, start + length); + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'Trim' when arguments are used. + //------------------------------------------------------------------------------------ + public static String trim(String string, Character... charsToTrim) { + return trimEnd(trimStart(string, charsToTrim), charsToTrim); + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'TrimEnd'. + //------------------------------------------------------------------------------------ + public static String trimEnd(String string, Character... charsToTrim) { + if (string == null || charsToTrim == null) { + return string; + } + + int lengthToKeep = string.length(); + for (int index = string.length() - 1; index >= 0; index--) { + boolean removeChar = false; + if (charsToTrim.length == 0) { + if (Character.isWhitespace(string.charAt(index))) { + lengthToKeep = index; + removeChar = true; + } + } else { + for (int trimCharIndex = 0; trimCharIndex < charsToTrim.length; trimCharIndex++) { + if (string.charAt(index) == charsToTrim[trimCharIndex]) { + lengthToKeep = index; + removeChar = true; + break; + } + } + } + if (!removeChar) { + break; + } + } + return string.substring(0, lengthToKeep); + } + + //------------------------------------------------------------------------------------ + // This method replaces the .NET string method 'TrimStart'. + //------------------------------------------------------------------------------------ + public static String trimStart(String string, Character... charsToTrim) { + if (string == null || charsToTrim == null) { + return string; + } + + int startingIndex = 0; + for (int index = 0; index < string.length(); index++) { + boolean removeChar = false; + if (charsToTrim.length == 0) { + if (Character.isWhitespace(string.charAt(index))) { + startingIndex = index + 1; + removeChar = true; + } + } else { + for (int trimCharIndex = 0; trimCharIndex < charsToTrim.length; trimCharIndex++) { + if (string.charAt(index) == charsToTrim[trimCharIndex]) { + startingIndex = index + 1; + removeChar = true; + break; + } + } + } + if (!removeChar) { + break; + } + } + return string.substring(startingIndex); + } + +} \ No newline at end of file diff --git a/jre/src/main/java/tangible/TryParseHelper.java b/jre/src/main/java/tangible/TryParseHelper.java new file mode 100644 index 0000000..d70cdde --- /dev/null +++ b/jre/src/main/java/tangible/TryParseHelper.java @@ -0,0 +1,76 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package tangible; + +//---------------------------------------------------------------------------------------- +// Copyright © 2007 - 2019 Tangible Software Solutions, Inc. +// This class can be used by anyone provided that the copyright notice remains intact. +// +// This class is used to convert some of the C# TryParse methods to Java. +//---------------------------------------------------------------------------------------- +public final class TryParseHelper { + public static boolean tryParseBoolean(String s, tangible.OutObject result) { + try { + result.argValue = Boolean.parseBoolean(s); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + public static boolean tryParseByte(String s, tangible.OutObject result) { + try { + result.argValue = Byte.parseByte(s); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + public static boolean tryParseDouble(String s, tangible.OutObject result) { + try { + result.argValue = Double.parseDouble(s); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + public static boolean tryParseFloat(String s, tangible.OutObject result) { + try { + result.argValue = Float.parseFloat(s); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + public static boolean tryParseInt(String s, tangible.OutObject result) { + try { + result.argValue = Integer.parseInt(s); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + public static boolean tryParseLong(String s, tangible.OutObject result) { + try { + result.argValue = Long.parseLong(s); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + public static boolean tryParseShort(String s, tangible.OutObject result) { + try { + result.argValue = Short.parseShort(s); + return true; + } catch (NumberFormatException e) { + return false; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BenchmarkSuiteBase.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BenchmarkSuiteBase.java new file mode 100644 index 0000000..1d3075e --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BenchmarkSuiteBase.java @@ -0,0 +1,139 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.MemorySpanResizer; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.io.RowReader; +import azure.data.cosmos.serialization.hybridrow.layouts.Layout; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutResolver; +import azure.data.cosmos.serialization.hybridrow.layouts.LayoutResolverNamespace; +import azure.data.cosmos.serialization.hybridrow.layouts.SystemSchema; +import azure.data.cosmos.serialization.hybridrow.recordio.RecordIOStream; +import azure.data.cosmos.serialization.hybridrow.recordio.Segment; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.stream.Stream; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Fields should be private + + +public class BenchmarkSuiteBase { + //C# TO JAVA CONVERTER WARNING: Java has no equivalent to C# 'private protected' access: + //ORIGINAL LINE: private protected const int InitialCapacity = 2 * 1024 * 1024; + protected static final int InitialCapacity = 2 * 1024 * 1024; + //C# TO JAVA CONVERTER WARNING: Java has no equivalent to C# 'private protected' access: + //ORIGINAL LINE: private protected LayoutResolverNamespace DefaultResolver = (LayoutResolverNamespace) + // SystemSchema.LayoutResolver; + protected LayoutResolverNamespace DefaultResolver = (LayoutResolverNamespace)SystemSchema.LayoutResolver; + + // TODO: C# TO JAVA CONVERTER: Methods returning tuples are not converted by C# to Java Converter: + // private protected async Task<(List>, LayoutResolverNamespace)> + // LoadExpectedAsync(string expectedFile) + // { + // LayoutResolverNamespace resolver = this.DefaultResolver; + // List> expected = new List>(); + // using (Stream stm = new FileStream(expectedFile, FileMode.Open)) + // { + // // Read a RecordIO stream. + // MemorySpanResizer resizer = new MemorySpanResizer(BenchmarkSuiteBase.InitialCapacity); + // Result r = await stm.ReadRecordIOAsync(record => + // { + // r = BenchmarkSuiteBase.LoadOneRow(record, resolver, out Dictionary + // rowValue); + // ResultAssert.IsSuccess(r); + // expected.Add(rowValue); + // return Result.Success; + // } + // , segment => + // { + // r = SegmentSerializer.Read(segment.Span, SystemSchema.LayoutResolver, out Segment s); + // ResultAssert.IsSuccess(r); + // Assert.IsNotNull(s.SDL); + // resolver = new LayoutResolverNamespace(Namespace.Parse(s.SDL), resolver); + // return Result.Success; + // } + // , resizer); + // + // ResultAssert.IsSuccess(r); + // } + // + // return (expected, resolver); + // } + + //C# TO JAVA CONVERTER WARNING: Java has no equivalent to C# 'private protected' access: + //ORIGINAL LINE: private protected static Result LoadOneRow(Memory buffer, LayoutResolver resolver, out + // Dictionary rowValue) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + protected static Result LoadOneRow(Memory buffer, LayoutResolver resolver, + tangible.OutObject> rowValue) { + RowBuffer row = new RowBuffer(buffer.Span, HybridRowVersion.V1, resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row); + row = tempRef_row.argValue; + tangible.RefObject tempRef_reader = + new tangible.RefObject(reader); + Result tempVar = DiagnosticConverter.ReaderToDynamic(tempRef_reader, rowValue); + reader = tempRef_reader.argValue; + return tempVar; + } + + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: private protected static async Task WriteAllRowsAsync(string file, string sdl, LayoutResolver + // resolver, Layout layout, List> rows) + //C# TO JAVA CONVERTER WARNING: Java has no equivalent to C# 'private protected' access: + protected static Task WriteAllRowsAsync(String file, String sdl, LayoutResolver resolver, Layout layout, + ArrayList> rows) { + try (Stream stm = new FileStream(file, FileMode.Truncate)) { + // Create a reusable, resizable buffer. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MemorySpanResizer resizer = new MemorySpanResizer(BenchmarkSuiteBase + // .InitialCapacity); + MemorySpanResizer resizer = new MemorySpanResizer(BenchmarkSuiteBase.InitialCapacity); + + // Write a RecordIO stream. + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'out' keyword - these are + // not converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Result r = await stm.WriteRecordIOAsync(new Segment("HybridRow.Tests.Perf Expected + // Results", sdl), (long index, out ReadOnlyMemory body) => + Result r = await RecordIOStream.WriteRecordIOAsync(stm, + new Segment("HybridRow.Tests.Perf Expected Results", sdl), (long index, out ReadOnlyMemorybody) -> + { + body = null; + if (index >= rows.size()) { + return Result.Success; + } + + StreamingRowGenerator writer = new StreamingRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, + resolver, resizer); + + Result r2 = writer.WriteBuffer(rows.get((int)index)); + if (r2 != Result.Success) { + return r2; + } + + body = resizer.getMemory().Slice(0, writer.getLength()); + return Result.Success; + }); + + ResultAssert.IsSuccess(r); + } + } + + //C# TO JAVA CONVERTER WARNING: Java has no equivalent to C# 'private protected' access: + //ORIGINAL LINE: private protected static class ResultAssert + protected static class ResultAssert { + public static void IsSuccess(Result actual) { + assert actual == Result.Success || Result.Success == actual; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonJsonModelRowGenerator.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonJsonModelRowGenerator.java new file mode 100644 index 0000000..12f10f6 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonJsonModelRowGenerator.java @@ -0,0 +1,131 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import org.bson.BsonWriter; +import org.bson.BsonBinaryWriter +import java.io.Closeable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; + +import static com.google.common.base.Strings.lenientFormat; + +public final class BsonJsonModelRowGenerator implements Closeable { + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.MemoryStream is + // input or output: + private MemoryStream stream; + private BsonWriter writer; + + public BsonJsonModelRowGenerator(int capacity) { + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.MemoryStream + // is input or output: + this.stream = new MemoryStream(capacity); + this.writer = new BsonBinaryWriter(this.stream); + } + + public int getLength() { + return (int)this.stream.Position; + } + + public void Reset() { + this.stream.SetLength(0); + this.stream.Position = 0; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public byte[] ToArray() + public byte[] ToArray() { + return this.stream.ToArray(); + } + + public void WriteBuffer(HashMap dict) { + this.writer.writeStartDocument(); + for ((Utf8String propPath,Object propValue) : dict) + { + this.JsonModelSwitch(propPath, propValue); + } + + this.writer.writeEndDocument(); + } + + public void close() throws IOException { + this.writer.Dispose(); + this.stream.Dispose(); + } + + private void JsonModelSwitch(Utf8String path, Object value) { + if (path != null) { + this.writer.writeName(path.toString()); + } + + switch (value) { + case null: + this.writer.writeNull(); + return; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case bool x: + case + boolean x: + this.writer.writeBoolean(x); + return; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case long x: + case + long x: + this.writer.writeInt64(x); + return; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case double x: + case + double x: + this.writer.writeDouble(x); + return; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case string x: + case String + x: + this.writer.writeString(x); + return; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case Utf8String x: + case Utf8String + x: + this.writer.writeString(x.toString()); + return; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case byte[] x: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + case + byte[] x: + this.writer.writeBytes(x); + return; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case Dictionary x: + case HashMap < Utf8String, Object > x: + this.writer.writeStartDocument(); + for ((Utf8String propPath,Object propValue) :x) + { + this.JsonModelSwitch(propPath, propValue); + } + + this.writer.writeEndDocument(); + return; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case List x: + case ArrayList < Object > x: + this.writer.writeStartArray(); + for (Object item : x) { + this.JsonModelSwitch(null, item); + } + + this.writer.writeEndArray(); + + return; + default: + throw new IllegalStateException(lenientFormat("Unknown type will be ignored: %s", value.getClass().getSimpleName())); + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonReaderExtensions.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonReaderExtensions.java new file mode 100644 index 0000000..3166722 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonReaderExtensions.java @@ -0,0 +1,55 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import MongoDB.Bson.*; +import MongoDB.Bson.IO.*; + +public final class BsonReaderExtensions { + public static void VisitBsonDocument(BsonReader bsonReader) { + bsonReader.ReadStartDocument(); + BsonType type; + while ((type = bsonReader.ReadBsonType()) != BsonType.EndOfDocument) { + String path = bsonReader.ReadName(); + switch (type) { + case BsonType.Array: + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.BsonReaderExtensions.VisitBsonArray(bsonReader); + break; + + case BsonType.Document: + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.BsonReaderExtensions.VisitBsonDocument(bsonReader); + break; + + default: + bsonReader.SkipValue(); + break; + } + } + + bsonReader.ReadEndDocument(); + } + + private static void VisitBsonArray(BsonReader bsonReader) { + bsonReader.ReadStartArray(); + BsonType type; + while ((type = bsonReader.ReadBsonType()) != BsonType.EndOfDocument) { + switch (type) { + case BsonType.Array: + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.BsonReaderExtensions.VisitBsonArray(bsonReader); + break; + + case BsonType.Document: + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.BsonReaderExtensions.VisitBsonDocument(bsonReader); + break; + + default: + bsonReader.SkipValue(); + break; + } + } + + bsonReader.ReadEndArray(); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonRowGenerator.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonRowGenerator.java new file mode 100644 index 0000000..fc24502 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/BsonRowGenerator.java @@ -0,0 +1,306 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import MongoDB.Bson.*; +import MongoDB.Bson.IO.*; +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; + +import java.io.Closeable; +import java.io.IOException; +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.UUID; + +public final class BsonRowGenerator implements Closeable { + private Layout layout; + private LayoutResolver resolver; + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.MemoryStream is + // input or output: + private MemoryStream stream; + private BsonWriter writer; + + public BsonRowGenerator(int capacity, Layout layout, LayoutResolver resolver) { + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.MemoryStream + // is input or output: + this.stream = new MemoryStream(capacity); + this.writer = new BsonBinaryWriter(this.stream); + this.layout = layout; + this.resolver = resolver; + } + + public int getLength() { + return (int)this.stream.Position; + } + + public void Reset() { + this.stream.SetLength(0); + this.stream.Position = 0; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public byte[] ToArray() + public byte[] ToArray() { + return this.stream.ToArray(); + } + + public void WriteBuffer(HashMap dict) { + this.writer.WriteStartDocument(); + for (LayoutColumn c : this.layout.getColumns()) { + this.LayoutCodeSwitch(c.getPath(), c.getTypeArg().clone(), dict.get(c.getPath())); + } + + this.writer.WriteEndDocument(); + } + + public void close() throws IOException { + this.writer.Dispose(); + this.stream.Dispose(); + } + + private void DispatchArray(TypeArgument typeArg, Object value) { + Contract.Requires(typeArg.getTypeArgs().getCount() == 1); + + this.writer.WriteStartArray(); + for (Object item : (ArrayList)value) { + this.LayoutCodeSwitch(null, typeArg.getTypeArgs().get(0).clone(), item); + } + + this.writer.WriteEndArray(); + } + + private void DispatchMap(TypeArgument typeArg, Object value) { + Contract.Requires(typeArg.getTypeArgs().getCount() == 2); + + this.writer.WriteStartArray(); + for (Object item : (ArrayList)value) { + this.DispatchTuple(typeArg.clone(), item); + } + + this.writer.WriteEndArray(); + } + + private void DispatchNullable(TypeArgument typeArg, Object value) { + Contract.Requires(typeArg.getTypeArgs().getCount() == 1); + + if (value != null) { + this.LayoutCodeSwitch(null, typeArg.getTypeArgs().get(0).clone(), value); + } else { + this.writer.WriteNull(); + } + } + + private void DispatchObject(TypeArgument typeArg, Object value) { + this.writer.WriteStartDocument(); + + // TODO: support properties in an object scope. + this.writer.WriteEndDocument(); + } + + private void DispatchSet(TypeArgument typeArg, Object value) { + Contract.Requires(typeArg.getTypeArgs().getCount() == 1); + + this.writer.WriteStartArray(); + for (Object item : (ArrayList)value) { + this.LayoutCodeSwitch(null, typeArg.getTypeArgs().get(0).clone(), item); + } + + this.writer.WriteEndArray(); + } + + private void DispatchTuple(TypeArgument typeArg, Object value) { + Contract.Requires(typeArg.getTypeArgs().getCount() >= 2); + ArrayList items = (ArrayList)value; + Contract.Assert(items.size() == typeArg.getTypeArgs().getCount()); + + this.writer.WriteStartArray(); + for (int i = 0; i < items.size(); i++) { + Object item = items.get(i); + this.LayoutCodeSwitch(null, typeArg.getTypeArgs().get(i).clone(), item); + } + + this.writer.WriteEndArray(); + } + + private void DispatchUDT(TypeArgument typeArg, Object value) { + this.writer.WriteStartDocument(); + + HashMap dict = (HashMap)value; + Layout udt = this.resolver.Resolve(typeArg.getTypeArgs().getSchemaId().clone()); + for (LayoutColumn c : udt.getColumns()) { + this.LayoutCodeSwitch(c.getPath(), c.getTypeArg().clone(), dict.get(c.getPath())); + } + + this.writer.WriteEndDocument(); + } + + private void LayoutCodeSwitch(UtfAnyString path, TypeArgument typeArg, Object value) { + if (!path.IsNull) { + this.writer.WriteName(path); + } + + switch (typeArg.getType().LayoutCode) { + case Null: + this.writer.WriteNull(); + return; + + case Boolean: + this.writer.WriteBoolean(value == null ? false : (Boolean)value); + return; + + case Int8: + this.writer.WriteInt32(value == null ? 0 : (byte)value); + return; + + case Int16: + this.writer.WriteInt32(value == null ? 0 : (Short)value); + return; + + case Int32: + this.writer.WriteInt32(value == null ? 0 : (Integer)value); + return; + + case Int64: + this.writer.WriteInt64(value == null ? 0 : (Long)value); + return; + + case UInt8: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.writer.WriteInt32(value == null ? default(byte) : (byte)value); + this.writer.WriteInt32(value == null ? 0 : (Byte)value); + return; + + case UInt16: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.writer.WriteInt32(value == null ? default(ushort) : (ushort)value); + this.writer.WriteInt32(value == null ? 0 : (short)value); + return; + + case UInt32: + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.writer.WriteInt32(value == null ? default(int) : unchecked((int)(uint)value)); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + this.writer.WriteInt32(value == null ? 0 : (int)(int)value); + return; + + case UInt64: + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.writer.WriteInt64(value == null ? default(long) : unchecked((long)(ulong)value)); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + this.writer.WriteInt64(value == null ? 0 : (long)(long)value); + return; + + case VarInt: + this.writer.WriteInt64(value == null ? 0 : (Long)value); + return; + + case VarUInt: + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.writer.WriteInt64(value == null ? default(long) : unchecked((long)(ulong)value)); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + this.writer.WriteInt64(value == null ? 0 : (long)(long)value); + return; + + case Float32: + this.writer.WriteDouble(value == null ? 0 : (Float)value); + return; + + case Float64: + this.writer.WriteDouble(value == null ? 0 : (Double)value); + return; + + case Float128: + Decimal128 d128 = null; + if (value != null) { + Float128 f128 = (Float128)value; + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: d128 = unchecked(Decimal128.FromIEEEBits((ulong)f128.High, (ulong)f128.Low)); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + d128 = Decimal128.FromIEEEBits((long)f128.High, (long)f128.Low); + } + + this.writer.WriteDecimal128(d128); + return; + + case Decimal: + this.writer.WriteDecimal128(value == null ? null : new Decimal128((BigDecimal)value)); + return; + + case DateTime: + this.writer.WriteDateTime(value == null ? 0 : ((LocalDateTime)value).getTime()); + return; + + case UnixDateTime: + this.writer.WriteDateTime(value == null ? 0 : ((UnixDateTime)value).getMilliseconds()); + return; + + case Guid: + this.writer.WriteString(value == null ? "" : ((UUID)value).toString()); + return; + + case MongoDbObjectId: + this.writer.WriteObjectId(value == null ? null : new ObjectId(((MongoDbObjectId)value).ToByteArray())); + return; + + case Utf8: + this.writer.WriteString(value == null ? "" : ((Utf8String)value).toString()); + return; + + case Binary: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.writer.WriteBytes(value == null ? default(byte[]) : (byte[])value); + this.writer.WriteBytes(value == null ? null : (byte[])value); + return; + + case ObjectScope: + case ImmutableObjectScope: + this.DispatchObject(typeArg.clone(), value); + return; + + case TypedArrayScope: + case ImmutableTypedArrayScope: + this.DispatchArray(typeArg.clone(), value); + return; + + case TypedSetScope: + case ImmutableTypedSetScope: + this.DispatchSet(typeArg.clone(), value); + return; + + case TypedMapScope: + case ImmutableTypedMapScope: + this.DispatchMap(typeArg.clone(), value); + return; + + case TupleScope: + case ImmutableTupleScope: + case TypedTupleScope: + case ImmutableTypedTupleScope: + case TaggedScope: + case ImmutableTaggedScope: + case Tagged2Scope: + case ImmutableTagged2Scope: + this.DispatchTuple(typeArg.clone(), value); + return; + + case NullableScope: + case ImmutableNullableScope: + this.DispatchNullable(typeArg.clone(), value); + return; + + case Schema: + case ImmutableSchema: + this.DispatchUDT(typeArg.clone(), value); + return; + + default: + Contract.Assert(false, String.format("Unknown type will be ignored: %1$s", typeArg.clone())); + return; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Address.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Address.java new file mode 100644 index 0000000..c08c0a3 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Address.java @@ -0,0 +1,317 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf.CassandraHotel.Protobuf; + +import azure.data.cosmos.serialization.hybridrow.Tests.Perf.*; + +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: TestData/CassandraHotelSchema.proto +// + +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pb = Google.Protobuf; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbc = Google.Protobuf.Collections; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbr = Google.Protobuf.Reflection; + +public final class Address implements Google.Protobuf.IMessage
{ + /** + * Field number for the "city" field. + */ + public static final int CityFieldNumber = 2; + /** + * Field number for the "postal_code" field. + */ + public static final int PostalCodeFieldNumber = 4; + /** + * Field number for the "state" field. + */ + public static final int StateFieldNumber = 3; + /** + * Field number for the "street" field. + */ + public static final int StreetFieldNumber = 1; + private static final Google.Protobuf.MessageParser
_parser = + new Google.Protobuf.MessageParser
(() -> new Address()); + private static final Google.Protobuf.FieldCodec _single_city_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(18); + + // TODO: C# TO JAVA CONVERTER: Java does not support 'partial' methods: + // partial void OnConstruction(); + private static final Google.Protobuf.FieldCodec _single_state_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(26); + private static final Google.Protobuf.FieldCodec _single_street_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(10); + private Google.Protobuf.UnknownFieldSet _unknownFields; + private String city_; + private PostalCode postalCode_; + private String state_; + private String street_; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Address() + public Address() { + OnConstruction(); + } + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Address(Address other) + public Address(Address other) { + this(); + setStreet(other.getStreet()); + setCity(other.getCity()); + setState(other.getState()); + setPostalCode(other.postalCode_ != null ? other.getPostalCode().Clone() : null); + _unknownFields = Google.Protobuf.UnknownFieldSet.Clone(other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string City + public String getCity() { + return city_; + } + + public void setCity(String value) { + city_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor + public Google.Protobuf.Reflection getDescriptor() { + return getDescriptor(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public static Google.Protobuf.Reflection + // .MessageDescriptor Descriptor + public static Google.Protobuf.Reflection.MessageDescriptor getDescriptor() { + return Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.CassandraHotelSchemaReflection.getDescriptor().MessageTypes[1]; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public static Google.Protobuf + // .MessageParser
Parser + public static Google.Protobuf.MessageParser
getParser() { + return _parser; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Microsoft.Azure.Cosmos.Serialization + // .HybridRow.Tests.Perf.CassandraHotel.Protobuf.PostalCode PostalCode + public PostalCode getPostalCode() { + return postalCode_; + } + + public void setPostalCode(PostalCode value) { + postalCode_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string State + public String getState() { + return state_; + } + + public void setState(String value) { + state_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string Street + public String getStreet() { + return street_; + } + + public void setStreet(String value) { + street_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() + public int CalculateSize() { + int size = 0; + if (street_ != null) { + size += _single_street_codec.CalculateSizeWithTag(getStreet()); + } + if (city_ != null) { + size += _single_city_codec.CalculateSizeWithTag(getCity()); + } + if (state_ != null) { + size += _single_state_codec.CalculateSizeWithTag(getState()); + } + if (postalCode_ != null) { + size += 1 + Google.Protobuf.CodedOutputStream.ComputeMessageSize(getPostalCode()); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Address Clone() + public Address Clone() { + return new Address(this); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Address other) + public void MergeFrom(Address other) { + if (other == null) { + return; + } + if (other.street_ != null) { + if (street_ == null || !other.getStreet().equals("")) { + setStreet(other.getStreet()); + } + } + if (other.city_ != null) { + if (city_ == null || !other.getCity().equals("")) { + setCity(other.getCity()); + } + } + if (other.state_ != null) { + if (state_ == null || !other.getState().equals("")) { + setState(other.getState()); + } + } + if (other.postalCode_ != null) { + if (postalCode_ == null) { + postalCode_ = new PostalCode(); + } + getPostalCode().MergeFrom(other.getPostalCode()); + } + _unknownFields = Google.Protobuf.UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Google.Protobuf + // .CodedInputStream input) + public void MergeFrom(Google.Protobuf.CodedInputStream input) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint tag; + int tag; + while ((tag = input.ReadTag()) != 0) { + switch (tag) { + default: + _unknownFields = Google.Protobuf.UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + String value = _single_street_codec.Read(input); + if (street_ == null || !value.equals("")) { + setStreet(value); + } + break; + } + case 18: { + String value = _single_city_codec.Read(input); + if (city_ == null || !value.equals("")) { + setCity(value); + } + break; + } + case 26: { + String value = _single_state_codec.Read(input); + if (state_ == null || !value.equals("")) { + setState(value); + } + break; + } + case 34: { + if (postalCode_ == null) { + postalCode_ = new PostalCode(); + } + input.ReadMessage(postalCode_); + break; + } + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(Google.Protobuf + // .CodedOutputStream output) + public void WriteTo(Google.Protobuf.CodedOutputStream output) { + if (street_ != null) { + _single_street_codec.WriteTagAndValue(output, getStreet()); + } + if (city_ != null) { + _single_city_codec.WriteTagAndValue(output, getCity()); + } + if (state_ != null) { + _single_state_codec.WriteTagAndValue(output, getState()); + } + if (postalCode_ != null) { + output.WriteRawTag(34); + output.WriteMessage(getPostalCode()); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) + @Override + public boolean equals(Object other) { + return Equals(other instanceof Address ? (Address)other : null); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Address other) + public boolean equals(Address other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!getStreet().equals(other.getStreet())) { + return false; + } + if (!getCity().equals(other.getCity())) { + return false; + } + if (!getState().equals(other.getState())) { + return false; + } + if (!getPostalCode().equals(other.getPostalCode())) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() + @Override + public int hashCode() { + int hash = 1; + if (street_ != null) { + hash ^= getStreet().hashCode(); + } + if (city_ != null) { + hash ^= getCity().hashCode(); + } + if (state_ != null) { + hash ^= getState().hashCode(); + } + if (postalCode_ != null) { + hash ^= getPostalCode().hashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.hashCode(); + } + return hash; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() + @Override + public String toString() { + return Google.Protobuf.JsonFormatter.ToDiagnosticString(this); + } + +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Available_Rooms_By_Hotel_Date.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Available_Rooms_By_Hotel_Date.java new file mode 100644 index 0000000..e1d9cf9 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Available_Rooms_By_Hotel_Date.java @@ -0,0 +1,321 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf.CassandraHotel.Protobuf; + +import azure.data.cosmos.serialization.hybridrow.Tests.Perf.*; + +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: TestData/CassandraHotelSchema.proto +// + +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pb = Google.Protobuf; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbc = Google.Protobuf.Collections; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbr = Google.Protobuf.Reflection; + +public final class Available_Rooms_By_Hotel_Date implements Google.Protobuf.IMessage { + /** + * Field number for the "date" field. + */ + public static final int DateFieldNumber = 2; + /** + * Field number for the "hotel_id" field. + */ + public static final int HotelIdFieldNumber = 1; + /** + * Field number for the "is_available" field. + */ + public static final int IsAvailableFieldNumber = 4; + /** + * Field number for the "room_number" field. + */ + public static final int RoomNumberFieldNumber = 3; + private static final Google.Protobuf.MessageParser _parser = + new Google.Protobuf.MessageParser(() -> new Available_Rooms_By_Hotel_Date()); + private static final Google.Protobuf.FieldCodec _single_date_codec = + Google.Protobuf.FieldCodec.ForStructWrapper(18); + + // TODO: C# TO JAVA CONVERTER: Java does not support 'partial' methods: + // partial void OnConstruction(); + private static final Google.Protobuf.FieldCodec _single_hotelId_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(10); + private static final Google.Protobuf.FieldCodec _single_isAvailable_codec = + Google.Protobuf.FieldCodec.ForStructWrapper(34); + private static final Google.Protobuf.FieldCodec _single_roomNumber_codec = + Google.Protobuf.FieldCodec.ForStructWrapper(26); + private Google.Protobuf.UnknownFieldSet _unknownFields; + private Long date_; + private String hotelId_; + private Boolean isAvailable_; + private Integer roomNumber_; + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Available_Rooms_By_Hotel_Date() + public Available_Rooms_By_Hotel_Date() { + OnConstruction(); + } + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Available_Rooms_By_Hotel_Date + // (Available_Rooms_By_Hotel_Date other) + public Available_Rooms_By_Hotel_Date(Available_Rooms_By_Hotel_Date other) { + this(); + setHotelId(other.getHotelId()); + setDate(other.getDate()); + setRoomNumber(other.getRoomNumber()); + setIsAvailable(other.getIsAvailable()); + _unknownFields = Google.Protobuf.UnknownFieldSet.Clone(other._unknownFields); + } + + /** + * datetime + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Nullable Date + public Long getDate() { + return date_; + } + + public void setDate(Long value) { + date_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor + public Google.Protobuf.Reflection getDescriptor() { + return getDescriptor(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public static Google.Protobuf.Reflection + // .MessageDescriptor Descriptor + public static Google.Protobuf.Reflection.MessageDescriptor getDescriptor() { + return Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.CassandraHotelSchemaReflection.getDescriptor().MessageTypes[3]; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string HotelId + public String getHotelId() { + return hotelId_; + } + + public void setHotelId(String value) { + hotelId_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Nullable IsAvailable + public Boolean getIsAvailable() { + return isAvailable_; + } + + public void setIsAvailable(Boolean value) { + isAvailable_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public static Google.Protobuf + // .MessageParser Parser + public static Google.Protobuf.MessageParser getParser() { + return _parser; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Nullable RoomNumber + public Integer getRoomNumber() { + return roomNumber_; + } + + public void setRoomNumber(Integer value) { + roomNumber_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() + public int CalculateSize() { + int size = 0; + if (hotelId_ != null) { + size += _single_hotelId_codec.CalculateSizeWithTag(getHotelId()); + } + if (date_ != null) { + size += _single_date_codec.CalculateSizeWithTag(getDate()); + } + if (roomNumber_ != null) { + size += _single_roomNumber_codec.CalculateSizeWithTag(getRoomNumber()); + } + if (isAvailable_ != null) { + size += _single_isAvailable_codec.CalculateSizeWithTag(getIsAvailable()); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Available_Rooms_By_Hotel_Date Clone() + public Available_Rooms_By_Hotel_Date Clone() { + return new Available_Rooms_By_Hotel_Date(this); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom + // (Available_Rooms_By_Hotel_Date other) + public void MergeFrom(Available_Rooms_By_Hotel_Date other) { + if (other == null) { + return; + } + if (other.hotelId_ != null) { + if (hotelId_ == null || !other.getHotelId().equals("")) { + setHotelId(other.getHotelId()); + } + } + if (other.date_ != null) { + if (date_ == null || other.getDate() != 0L) { + setDate(other.getDate()); + } + } + if (other.roomNumber_ != null) { + if (roomNumber_ == null || other.getRoomNumber() != 0) { + setRoomNumber(other.getRoomNumber()); + } + } + if (other.isAvailable_ != null) { + if (isAvailable_ == null || other.getIsAvailable() != false) { + setIsAvailable(other.getIsAvailable()); + } + } + _unknownFields = Google.Protobuf.UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Google.Protobuf + // .CodedInputStream input) + public void MergeFrom(Google.Protobuf.CodedInputStream input) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint tag; + int tag; + while ((tag = input.ReadTag()) != 0) { + switch (tag) { + default: + _unknownFields = Google.Protobuf.UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + String value = _single_hotelId_codec.Read(input); + if (hotelId_ == null || !value.equals("")) { + setHotelId(value); + } + break; + } + case 18: { + Long value = _single_date_codec.Read(input); + if (date_ == null || value != 0L) { + setDate(value); + } + break; + } + case 26: { + Integer value = _single_roomNumber_codec.Read(input); + if (roomNumber_ == null || value != 0) { + setRoomNumber(value); + } + break; + } + case 34: { + Boolean value = _single_isAvailable_codec.Read(input); + if (isAvailable_ == null || value != false) { + setIsAvailable(value); + } + break; + } + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(Google.Protobuf + // .CodedOutputStream output) + public void WriteTo(Google.Protobuf.CodedOutputStream output) { + if (hotelId_ != null) { + _single_hotelId_codec.WriteTagAndValue(output, getHotelId()); + } + if (date_ != null) { + _single_date_codec.WriteTagAndValue(output, getDate()); + } + if (roomNumber_ != null) { + _single_roomNumber_codec.WriteTagAndValue(output, getRoomNumber()); + } + if (isAvailable_ != null) { + _single_isAvailable_codec.WriteTagAndValue(output, getIsAvailable()); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) + @Override + public boolean equals(Object other) { + return Equals(other instanceof Available_Rooms_By_Hotel_Date ? (Available_Rooms_By_Hotel_Date)other : null); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals + // (Available_Rooms_By_Hotel_Date other) + public boolean equals(Available_Rooms_By_Hotel_Date other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!getHotelId().equals(other.getHotelId())) { + return false; + } + if (getDate() != other.getDate()) { + return false; + } + if (getRoomNumber() != other.getRoomNumber()) { + return false; + } + if (getIsAvailable() != other.getIsAvailable()) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() + @Override + public int hashCode() { + int hash = 1; + if (hotelId_ != null) { + hash ^= getHotelId().hashCode(); + } + if (date_ != null) { + hash ^= getDate().hashCode(); + } + if (roomNumber_ != null) { + hash ^= getRoomNumber().hashCode(); + } + if (isAvailable_ != null) { + hash ^= getIsAvailable().hashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.hashCode(); + } + return hash; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() + @Override + public String toString() { + return Google.Protobuf.JsonFormatter.ToDiagnosticString(this); + } + +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/CassandraHotelSchemaReflection.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/CassandraHotelSchemaReflection.java new file mode 100644 index 0000000..2acb93a --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/CassandraHotelSchemaReflection.java @@ -0,0 +1,121 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf.CassandraHotel.Protobuf; + +import azure.data.cosmos.serialization.hybridrow.Tests.Perf.*; + +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: TestData/CassandraHotelSchema.proto +// + +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pb = Google.Protobuf; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbc = Google.Protobuf.Collections; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbr = Google.Protobuf.Reflection; + + +/** + * Holder for reflection information generated from TestData/CassandraHotelSchema.proto + */ +public final class CassandraHotelSchemaReflection { + + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + ///#region Descriptor + + private static Google.Protobuf.Reflection.FileDescriptor descriptor; + + static { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: byte[] descriptorData = System.Convert.FromBase64String(string.Concat + // ("CiNUZXN0RGF0YS9DYXNzYW5kcmFIb3RlbFNjaGVtYS5wcm90bxJITWljcm9z", + // "b2Z0LkF6dXJlLkNvc21vcy5TZXJpYWxpemF0aW9uLkh5YnJpZFJvdy5UZXN0", + // "cy5QZXJmLkNhc3NhbmRyYUhvdGVsGh5nb29nbGUvcHJvdG9idWYvd3JhcHBl", + // "cnMucHJvdG8iYgoKUG9zdGFsQ29kZRIoCgN6aXAYASABKAsyGy5nb29nbGUu", + // "cHJvdG9idWYuSW50MzJWYWx1ZRIqCgVwbHVzNBgCIAEoCzIbLmdvb2dsZS5w", + // "cm90b2J1Zi5JbnQzMlZhbHVlIvsBCgdBZGRyZXNzEiwKBnN0cmVldBgBIAEo", + // "CzIcLmdvb2dsZS5wcm90b2J1Zi5TdHJpbmdWYWx1ZRIqCgRjaXR5GAIgASgL", + // "MhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1ZhbHVlEisKBXN0YXRlGAMgASgL", + // "MhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1ZhbHVlEmkKC3Bvc3RhbF9jb2Rl", + // "GAQgASgLMlQuTWljcm9zb2Z0LkF6dXJlLkNvc21vcy5TZXJpYWxpemF0aW9u", + // "Lkh5YnJpZFJvdy5UZXN0cy5QZXJmLkNhc3NhbmRyYUhvdGVsLlBvc3RhbENv", + // "ZGUi9QEKBkhvdGVscxIuCghob3RlbF9pZBgBIAEoCzIcLmdvb2dsZS5wcm90", + // "b2J1Zi5TdHJpbmdWYWx1ZRIqCgRuYW1lGAIgASgLMhwuZ29vZ2xlLnByb3Rv", + // "YnVmLlN0cmluZ1ZhbHVlEisKBXBob25lGAMgASgLMhwuZ29vZ2xlLnByb3Rv", + // "YnVmLlN0cmluZ1ZhbHVlEmIKB2FkZHJlc3MYBCABKAsyUS5NaWNyb3NvZnQu", + // "QXp1cmUuQ29zbW9zLlNlcmlhbGl6YXRpb24uSHlicmlkUm93LlRlc3RzLlBl", + // "cmYuQ2Fzc2FuZHJhSG90ZWwuQWRkcmVzcyLeAQodQXZhaWxhYmxlX1Jvb21z", + // "X0J5X0hvdGVsX0RhdGUSLgoIaG90ZWxfaWQYASABKAsyHC5nb29nbGUucHJv", + // "dG9idWYuU3RyaW5nVmFsdWUSKQoEZGF0ZRgCIAEoCzIbLmdvb2dsZS5wcm90", + // "b2J1Zi5JbnQ2NFZhbHVlEjAKC3Jvb21fbnVtYmVyGAMgASgLMhsuZ29vZ2xl", + // "LnByb3RvYnVmLkludDMyVmFsdWUSMAoMaXNfYXZhaWxhYmxlGAQgASgLMhou", + // "Z29vZ2xlLnByb3RvYnVmLkJvb2xWYWx1ZSKfBAoGR3Vlc3RzEi4KCGd1ZXN0", + // "X2lkGAEgASgLMhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1ZhbHVlEjAKCmZp", + // "cnN0X25hbWUYAiABKAsyHC5nb29nbGUucHJvdG9idWYuU3RyaW5nVmFsdWUS", + // "LwoJbGFzdF9uYW1lGAMgASgLMhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1Zh", + // "bHVlEisKBXRpdGxlGAQgASgLMhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1Zh", + // "bHVlEg4KBmVtYWlscxgFIAMoCRIVCg1waG9uZV9udW1iZXJzGAYgAygJEnIK", + // "CWFkZHJlc3NlcxgHIAMoCzJfLk1pY3Jvc29mdC5BenVyZS5Db3Ntb3MuU2Vy", + // "aWFsaXphdGlvbi5IeWJyaWRSb3cuVGVzdHMuUGVyZi5DYXNzYW5kcmFIb3Rl", + // "bC5HdWVzdHMuQWRkcmVzc2VzRW50cnkSNAoOY29uZmlybV9udW1iZXIYCCAB", + // "KAsyHC5nb29nbGUucHJvdG9idWYuU3RyaW5nVmFsdWUagwEKDkFkZHJlc3Nl", + // "c0VudHJ5EgsKA2tleRgBIAEoCRJgCgV2YWx1ZRgCIAEoCzJRLk1pY3Jvc29m", + // "dC5BenVyZS5Db3Ntb3MuU2VyaWFsaXphdGlvbi5IeWJyaWRSb3cuVGVzdHMu", + // "UGVyZi5DYXNzYW5kcmFIb3RlbC5BZGRyZXNzOgI4AUJUqgJRTWljcm9zb2Z0", + // "LkF6dXJlLkNvc21vcy5TZXJpYWxpemF0aW9uLkh5YnJpZFJvdy5UZXN0cy5Q", + // "ZXJmLkNhc3NhbmRyYUhvdGVsLlByb3RvYnVmYgZwcm90bzM=")); + byte[] descriptorData = System.Convert.FromBase64String(String.Concat( + "CiNUZXN0RGF0YS9DYXNzYW5kcmFIb3RlbFNjaGVtYS5wcm90bxJITWljcm9z", + "b2Z0LkF6dXJlLkNvc21vcy5TZXJpYWxpemF0aW9uLkh5YnJpZFJvdy5UZXN0", + "cy5QZXJmLkNhc3NhbmRyYUhvdGVsGh5nb29nbGUvcHJvdG9idWYvd3JhcHBl", + "cnMucHJvdG8iYgoKUG9zdGFsQ29kZRIoCgN6aXAYASABKAsyGy5nb29nbGUu", + "cHJvdG9idWYuSW50MzJWYWx1ZRIqCgVwbHVzNBgCIAEoCzIbLmdvb2dsZS5w", + "cm90b2J1Zi5JbnQzMlZhbHVlIvsBCgdBZGRyZXNzEiwKBnN0cmVldBgBIAEo", + "CzIcLmdvb2dsZS5wcm90b2J1Zi5TdHJpbmdWYWx1ZRIqCgRjaXR5GAIgASgL", + "MhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1ZhbHVlEisKBXN0YXRlGAMgASgL", + "MhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1ZhbHVlEmkKC3Bvc3RhbF9jb2Rl", + "GAQgASgLMlQuTWljcm9zb2Z0LkF6dXJlLkNvc21vcy5TZXJpYWxpemF0aW9u", + "Lkh5YnJpZFJvdy5UZXN0cy5QZXJmLkNhc3NhbmRyYUhvdGVsLlBvc3RhbENv", + "ZGUi9QEKBkhvdGVscxIuCghob3RlbF9pZBgBIAEoCzIcLmdvb2dsZS5wcm90", + "b2J1Zi5TdHJpbmdWYWx1ZRIqCgRuYW1lGAIgASgLMhwuZ29vZ2xlLnByb3Rv", + "YnVmLlN0cmluZ1ZhbHVlEisKBXBob25lGAMgASgLMhwuZ29vZ2xlLnByb3Rv", + "YnVmLlN0cmluZ1ZhbHVlEmIKB2FkZHJlc3MYBCABKAsyUS5NaWNyb3NvZnQu", + "QXp1cmUuQ29zbW9zLlNlcmlhbGl6YXRpb24uSHlicmlkUm93LlRlc3RzLlBl", + "cmYuQ2Fzc2FuZHJhSG90ZWwuQWRkcmVzcyLeAQodQXZhaWxhYmxlX1Jvb21z", + "X0J5X0hvdGVsX0RhdGUSLgoIaG90ZWxfaWQYASABKAsyHC5nb29nbGUucHJv", + "dG9idWYuU3RyaW5nVmFsdWUSKQoEZGF0ZRgCIAEoCzIbLmdvb2dsZS5wcm90", + "b2J1Zi5JbnQ2NFZhbHVlEjAKC3Jvb21fbnVtYmVyGAMgASgLMhsuZ29vZ2xl", + "LnByb3RvYnVmLkludDMyVmFsdWUSMAoMaXNfYXZhaWxhYmxlGAQgASgLMhou", + "Z29vZ2xlLnByb3RvYnVmLkJvb2xWYWx1ZSKfBAoGR3Vlc3RzEi4KCGd1ZXN0", + "X2lkGAEgASgLMhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1ZhbHVlEjAKCmZp", + "cnN0X25hbWUYAiABKAsyHC5nb29nbGUucHJvdG9idWYuU3RyaW5nVmFsdWUS", + "LwoJbGFzdF9uYW1lGAMgASgLMhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1Zh", + "bHVlEisKBXRpdGxlGAQgASgLMhwuZ29vZ2xlLnByb3RvYnVmLlN0cmluZ1Zh", + "bHVlEg4KBmVtYWlscxgFIAMoCRIVCg1waG9uZV9udW1iZXJzGAYgAygJEnIK", + "CWFkZHJlc3NlcxgHIAMoCzJfLk1pY3Jvc29mdC5BenVyZS5Db3Ntb3MuU2Vy", + "aWFsaXphdGlvbi5IeWJyaWRSb3cuVGVzdHMuUGVyZi5DYXNzYW5kcmFIb3Rl", + "bC5HdWVzdHMuQWRkcmVzc2VzRW50cnkSNAoOY29uZmlybV9udW1iZXIYCCAB", + "KAsyHC5nb29nbGUucHJvdG9idWYuU3RyaW5nVmFsdWUagwEKDkFkZHJlc3Nl", + "c0VudHJ5EgsKA2tleRgBIAEoCRJgCgV2YWx1ZRgCIAEoCzJRLk1pY3Jvc29m", + "dC5BenVyZS5Db3Ntb3MuU2VyaWFsaXphdGlvbi5IeWJyaWRSb3cuVGVzdHMu", + "UGVyZi5DYXNzYW5kcmFIb3RlbC5BZGRyZXNzOgI4AUJUqgJRTWljcm9zb2Z0", + "LkF6dXJlLkNvc21vcy5TZXJpYWxpemF0aW9uLkh5YnJpZFJvdy5UZXN0cy5Q", + "ZXJmLkNhc3NhbmRyYUhvdGVsLlByb3RvYnVmYgZwcm90bzM=")); + descriptor = Google.Protobuf.Reflection.FileDescriptor.FromGeneratedCode(descriptorData, + new Google.Protobuf.Reflection.FileDescriptor[] { Google.Protobuf.WellKnownTypes.WrappersReflection.Descriptor }, new Google.Protobuf.Reflection.GeneratedClrTypeInfo(null, new Google.Protobuf.Reflection.GeneratedClrTypeInfo[] { new Google.Protobuf.Reflection.GeneratedClrTypeInfo(Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.PostalCode.class, Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.PostalCode.getParser(), new String[] { "Zip", "Plus4" }, null, null, null), new Google.Protobuf.Reflection.GeneratedClrTypeInfo(Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Address.class, Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Address.getParser(), new String[] { "Street", "City", "State", "PostalCode" }, null, null, null), new Google.Protobuf.Reflection.GeneratedClrTypeInfo(Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Hotels.class, Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Hotels.getParser(), new String[] { "HotelId", "Name", "Phone", "Address" }, null, null, null), new Google.Protobuf.Reflection.GeneratedClrTypeInfo(Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Available_Rooms_By_Hotel_Date.class, Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Available_Rooms_By_Hotel_Date.getParser(), new String[] { "HotelId", "Date", "RoomNumber", "IsAvailable" }, null, null, null), new Google.Protobuf.Reflection.GeneratedClrTypeInfo(Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Guests.class, Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Guests.getParser(), new String[] { "GuestId", "FirstName", "LastName", "Title", "Emails", "PhoneNumbers", "Addresses", "ConfirmNumber" }, null, null, new Google.Protobuf.Reflection.GeneratedClrTypeInfo[] { null }) })); + } + + /** + * File descriptor for TestData/CassandraHotelSchema.proto + */ + public static Google.Protobuf.Reflection.FileDescriptor getDescriptor() { + return descriptor; + } + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + ///#endregion + +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Guests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Guests.java new file mode 100644 index 0000000..a638fe9 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Guests.java @@ -0,0 +1,446 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf.CassandraHotel.Protobuf; + +import azure.data.cosmos.serialization.hybridrow.Tests.Perf.*; + +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: TestData/CassandraHotelSchema.proto +// + +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pb = Google.Protobuf; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbc = Google.Protobuf.Collections; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbr = Google.Protobuf.Reflection; + +public final class Guests implements Google.Protobuf.IMessage { + /** + * Field number for the "addresses" field. + */ + public static final int AddressesFieldNumber = 7; + /** + * Field number for the "confirm_number" field. + */ + public static final int ConfirmNumberFieldNumber = 8; + /** + * Field number for the "emails" field. + */ + public static final int EmailsFieldNumber = 5; + /** + * Field number for the "first_name" field. + */ + public static final int FirstNameFieldNumber = 2; + /** + * Field number for the "guest_id" field. + */ + public static final int GuestIdFieldNumber = 1; + /** + * Field number for the "last_name" field. + */ + public static final int LastNameFieldNumber = 3; + + // TODO: C# TO JAVA CONVERTER: Java does not support 'partial' methods: + // partial void OnConstruction(); + /** + * Field number for the "phone_numbers" field. + */ + public static final int PhoneNumbersFieldNumber = 6; + /** + * Field number for the "title" field. + */ + public static final int TitleFieldNumber = 4; + private static final Google.Protobuf.Collections.MapField.Codec _map_addresses_codec = + new Google.Protobuf.Collections.MapField.Codec(Google.Protobuf.FieldCodec.ForString(10), + Google.Protobuf.FieldCodec.ForMessage(18, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Address.getParser()), 58); + private static final Google.Protobuf.MessageParser _parser = + new Google.Protobuf.MessageParser(() -> new Guests()); + private static final Google.Protobuf.FieldCodec _repeated_emails_codec = + Google.Protobuf.FieldCodec.ForString(42); + private static final Google.Protobuf.FieldCodec _repeated_phoneNumbers_codec = + Google.Protobuf.FieldCodec.ForString(50); + private static final Google.Protobuf.FieldCodec _single_confirmNumber_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(66); + private static final Google.Protobuf.FieldCodec _single_firstName_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(18); + private static final Google.Protobuf.FieldCodec _single_guestId_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(10); + private static final Google.Protobuf.FieldCodec _single_lastName_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(26); + private static final Google.Protobuf.FieldCodec _single_title_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(34); + private final Google.Protobuf.Collections.MapField addresses_ = + new Google.Protobuf.Collections.MapField(); + private final Google.Protobuf.Collections.RepeatedField emails_ = + new Google.Protobuf.Collections.RepeatedField(); + private final Google.Protobuf.Collections.RepeatedField phoneNumbers_ = + new Google.Protobuf.Collections.RepeatedField(); + private Google.Protobuf.UnknownFieldSet _unknownFields; + private String confirmNumber_; + private String firstName_; + private String guestId_; + private String lastName_; + private String title_; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Guests() + public Guests() { + OnConstruction(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Guests(Guests other) + public Guests(Guests other) { + this(); + setGuestId(other.getGuestId()); + setFirstName(other.getFirstName()); + setLastName(other.getLastName()); + setTitle(other.getTitle()); + emails_ = other.emails_.Clone(); + phoneNumbers_ = other.phoneNumbers_.Clone(); + addresses_ = other.addresses_.Clone(); + setConfirmNumber(other.getConfirmNumber()); + _unknownFields = Google.Protobuf.UnknownFieldSet.Clone(other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Google.Protobuf.Collections + // .MapField + // Addresses + public Google.Protobuf.Collections.MapField getAddresses() { + return addresses_; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string ConfirmNumber + public String getConfirmNumber() { + return confirmNumber_; + } + + public void setConfirmNumber(String value) { + confirmNumber_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public static Google.Protobuf.Reflection + // .MessageDescriptor Descriptor + public static Google.Protobuf.Reflection.MessageDescriptor getDescriptor() { + return Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.CassandraHotelSchemaReflection.getDescriptor().MessageTypes[4]; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor + public Google.Protobuf.Reflection getDescriptor() { + return getDescriptor(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Google.Protobuf.Collections + // .RepeatedField Emails + public Google.Protobuf.Collections.RepeatedField getEmails() { + return emails_; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string FirstName + public String getFirstName() { + return firstName_; + } + + public void setFirstName(String value) { + firstName_ = value; + } + + /** + * guid + */ + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string GuestId + public String getGuestId() { + return guestId_; + } + + public void setGuestId(String value) { + guestId_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string LastName + public String getLastName() { + return lastName_; + } + + public void setLastName(String value) { + lastName_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public static Google.Protobuf + // .MessageParser Parser + public static Google.Protobuf.MessageParser getParser() { + return _parser; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Google.Protobuf.Collections + // .RepeatedField PhoneNumbers + public Google.Protobuf.Collections.RepeatedField getPhoneNumbers() { + return phoneNumbers_; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string Title + public String getTitle() { + return title_; + } + + public void setTitle(String value) { + title_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() + public int CalculateSize() { + int size = 0; + if (guestId_ != null) { + size += _single_guestId_codec.CalculateSizeWithTag(getGuestId()); + } + if (firstName_ != null) { + size += _single_firstName_codec.CalculateSizeWithTag(getFirstName()); + } + if (lastName_ != null) { + size += _single_lastName_codec.CalculateSizeWithTag(getLastName()); + } + if (title_ != null) { + size += _single_title_codec.CalculateSizeWithTag(getTitle()); + } + size += emails_.CalculateSize(_repeated_emails_codec); + size += phoneNumbers_.CalculateSize(_repeated_phoneNumbers_codec); + size += addresses_.CalculateSize(_map_addresses_codec); + if (confirmNumber_ != null) { + size += _single_confirmNumber_codec.CalculateSizeWithTag(getConfirmNumber()); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Guests Clone() + public Guests Clone() { + return new Guests(this); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Guests other) + public void MergeFrom(Guests other) { + if (other == null) { + return; + } + if (other.guestId_ != null) { + if (guestId_ == null || !other.getGuestId().equals("")) { + setGuestId(other.getGuestId()); + } + } + if (other.firstName_ != null) { + if (firstName_ == null || !other.getFirstName().equals("")) { + setFirstName(other.getFirstName()); + } + } + if (other.lastName_ != null) { + if (lastName_ == null || !other.getLastName().equals("")) { + setLastName(other.getLastName()); + } + } + if (other.title_ != null) { + if (title_ == null || !other.getTitle().equals("")) { + setTitle(other.getTitle()); + } + } + emails_.Add(other.emails_); + phoneNumbers_.Add(other.phoneNumbers_); + addresses_.Add(other.addresses_); + if (other.confirmNumber_ != null) { + if (confirmNumber_ == null || !other.getConfirmNumber().equals("")) { + setConfirmNumber(other.getConfirmNumber()); + } + } + _unknownFields = Google.Protobuf.UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Google.Protobuf + // .CodedInputStream input) + public void MergeFrom(Google.Protobuf.CodedInputStream input) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint tag; + int tag; + while ((tag = input.ReadTag()) != 0) { + switch (tag) { + default: + _unknownFields = Google.Protobuf.UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + String value = _single_guestId_codec.Read(input); + if (guestId_ == null || !value.equals("")) { + setGuestId(value); + } + break; + } + case 18: { + String value = _single_firstName_codec.Read(input); + if (firstName_ == null || !value.equals("")) { + setFirstName(value); + } + break; + } + case 26: { + String value = _single_lastName_codec.Read(input); + if (lastName_ == null || !value.equals("")) { + setLastName(value); + } + break; + } + case 34: { + String value = _single_title_codec.Read(input); + if (title_ == null || !value.equals("")) { + setTitle(value); + } + break; + } + case 42: { + emails_.AddEntriesFrom(input, _repeated_emails_codec); + break; + } + case 50: { + phoneNumbers_.AddEntriesFrom(input, _repeated_phoneNumbers_codec); + break; + } + case 58: { + addresses_.AddEntriesFrom(input, _map_addresses_codec); + break; + } + case 66: { + String value = _single_confirmNumber_codec.Read(input); + if (confirmNumber_ == null || !value.equals("")) { + setConfirmNumber(value); + } + break; + } + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(Google.Protobuf + // .CodedOutputStream output) + public void WriteTo(Google.Protobuf.CodedOutputStream output) { + if (guestId_ != null) { + _single_guestId_codec.WriteTagAndValue(output, getGuestId()); + } + if (firstName_ != null) { + _single_firstName_codec.WriteTagAndValue(output, getFirstName()); + } + if (lastName_ != null) { + _single_lastName_codec.WriteTagAndValue(output, getLastName()); + } + if (title_ != null) { + _single_title_codec.WriteTagAndValue(output, getTitle()); + } + emails_.WriteTo(output, _repeated_emails_codec); + phoneNumbers_.WriteTo(output, _repeated_phoneNumbers_codec); + addresses_.WriteTo(output, _map_addresses_codec); + if (confirmNumber_ != null) { + _single_confirmNumber_codec.WriteTagAndValue(output, getConfirmNumber()); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) + @Override + public boolean equals(Object other) { + return Equals(other instanceof Guests ? (Guests)other : null); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Guests other) + public boolean equals(Guests other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!getGuestId().equals(other.getGuestId())) { + return false; + } + if (!getFirstName().equals(other.getFirstName())) { + return false; + } + if (!getLastName().equals(other.getLastName())) { + return false; + } + if (!getTitle().equals(other.getTitle())) { + return false; + } + if (!emails_.equals(other.emails_)) { + return false; + } + if (!phoneNumbers_.equals(other.phoneNumbers_)) { + return false; + } + if (!getAddresses().equals(other.getAddresses())) { + return false; + } + if (!getConfirmNumber().equals(other.getConfirmNumber())) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() + @Override + public int hashCode() { + int hash = 1; + if (guestId_ != null) { + hash ^= getGuestId().hashCode(); + } + if (firstName_ != null) { + hash ^= getFirstName().hashCode(); + } + if (lastName_ != null) { + hash ^= getLastName().hashCode(); + } + if (title_ != null) { + hash ^= getTitle().hashCode(); + } + hash ^= emails_.hashCode(); + hash ^= phoneNumbers_.hashCode(); + hash ^= getAddresses().hashCode(); + if (confirmNumber_ != null) { + hash ^= getConfirmNumber().hashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.hashCode(); + } + return hash; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() + @Override + public String toString() { + return Google.Protobuf.JsonFormatter.ToDiagnosticString(this); + } + +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Hotels.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Hotels.java new file mode 100644 index 0000000..56687ff --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/Hotels.java @@ -0,0 +1,317 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf.CassandraHotel.Protobuf; + +import azure.data.cosmos.serialization.hybridrow.Tests.Perf.*; + +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: TestData/CassandraHotelSchema.proto +// + +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pb = Google.Protobuf; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbc = Google.Protobuf.Collections; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbr = Google.Protobuf.Reflection; + +public final class Hotels implements Google.Protobuf.IMessage { + /** + * Field number for the "address" field. + */ + public static final int AddressFieldNumber = 4; + /** + * Field number for the "hotel_id" field. + */ + public static final int HotelIdFieldNumber = 1; + /** + * Field number for the "name" field. + */ + public static final int NameFieldNumber = 2; + /** + * Field number for the "phone" field. + */ + public static final int PhoneFieldNumber = 3; + private static final Google.Protobuf.MessageParser _parser = + new Google.Protobuf.MessageParser(() -> new Hotels()); + private static final Google.Protobuf.FieldCodec _single_hotelId_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(10); + + // TODO: C# TO JAVA CONVERTER: Java does not support 'partial' methods: + // partial void OnConstruction(); + private static final Google.Protobuf.FieldCodec _single_name_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(18); + private static final Google.Protobuf.FieldCodec _single_phone_codec = + Google.Protobuf.FieldCodec.ForClassWrapper(26); + private Google.Protobuf.UnknownFieldSet _unknownFields; + private Address address_; + private String hotelId_; + private String name_; + private String phone_; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Hotels() + public Hotels() { + OnConstruction(); + } + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Hotels(Hotels other) + public Hotels(Hotels other) { + this(); + setHotelId(other.getHotelId()); + setName(other.getName()); + setPhone(other.getPhone()); + setAddress(other.address_ != null ? other.getAddress().Clone() : null); + _unknownFields = Google.Protobuf.UnknownFieldSet.Clone(other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Microsoft.Azure.Cosmos.Serialization + // .HybridRow.Tests.Perf.CassandraHotel.Protobuf.Address Address + public Address getAddress() { + return address_; + } + + public void setAddress(Address value) { + address_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor + public Google.Protobuf.Reflection getDescriptor() { + return getDescriptor(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public static Google.Protobuf.Reflection + // .MessageDescriptor Descriptor + public static Google.Protobuf.Reflection.MessageDescriptor getDescriptor() { + return Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.CassandraHotelSchemaReflection.getDescriptor().MessageTypes[2]; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string HotelId + public String getHotelId() { + return hotelId_; + } + + public void setHotelId(String value) { + hotelId_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name + public String getName() { + return name_; + } + + public void setName(String value) { + name_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public static Google.Protobuf + // .MessageParser Parser + public static Google.Protobuf.MessageParser getParser() { + return _parser; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public string Phone + public String getPhone() { + return phone_; + } + + public void setPhone(String value) { + phone_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() + public int CalculateSize() { + int size = 0; + if (hotelId_ != null) { + size += _single_hotelId_codec.CalculateSizeWithTag(getHotelId()); + } + if (name_ != null) { + size += _single_name_codec.CalculateSizeWithTag(getName()); + } + if (phone_ != null) { + size += _single_phone_codec.CalculateSizeWithTag(getPhone()); + } + if (address_ != null) { + size += 1 + Google.Protobuf.CodedOutputStream.ComputeMessageSize(getAddress()); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Hotels Clone() + public Hotels Clone() { + return new Hotels(this); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Hotels other) + public void MergeFrom(Hotels other) { + if (other == null) { + return; + } + if (other.hotelId_ != null) { + if (hotelId_ == null || !other.getHotelId().equals("")) { + setHotelId(other.getHotelId()); + } + } + if (other.name_ != null) { + if (name_ == null || !other.getName().equals("")) { + setName(other.getName()); + } + } + if (other.phone_ != null) { + if (phone_ == null || !other.getPhone().equals("")) { + setPhone(other.getPhone()); + } + } + if (other.address_ != null) { + if (address_ == null) { + address_ = new Address(); + } + getAddress().MergeFrom(other.getAddress()); + } + _unknownFields = Google.Protobuf.UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Google.Protobuf + // .CodedInputStream input) + public void MergeFrom(Google.Protobuf.CodedInputStream input) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint tag; + int tag; + while ((tag = input.ReadTag()) != 0) { + switch (tag) { + default: + _unknownFields = Google.Protobuf.UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + String value = _single_hotelId_codec.Read(input); + if (hotelId_ == null || !value.equals("")) { + setHotelId(value); + } + break; + } + case 18: { + String value = _single_name_codec.Read(input); + if (name_ == null || !value.equals("")) { + setName(value); + } + break; + } + case 26: { + String value = _single_phone_codec.Read(input); + if (phone_ == null || !value.equals("")) { + setPhone(value); + } + break; + } + case 34: { + if (address_ == null) { + address_ = new Address(); + } + input.ReadMessage(address_); + break; + } + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(Google.Protobuf + // .CodedOutputStream output) + public void WriteTo(Google.Protobuf.CodedOutputStream output) { + if (hotelId_ != null) { + _single_hotelId_codec.WriteTagAndValue(output, getHotelId()); + } + if (name_ != null) { + _single_name_codec.WriteTagAndValue(output, getName()); + } + if (phone_ != null) { + _single_phone_codec.WriteTagAndValue(output, getPhone()); + } + if (address_ != null) { + output.WriteRawTag(34); + output.WriteMessage(getAddress()); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) + @Override + public boolean equals(Object other) { + return Equals(other instanceof Hotels ? (Hotels)other : null); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Hotels other) + public boolean equals(Hotels other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!getHotelId().equals(other.getHotelId())) { + return false; + } + if (!getName().equals(other.getName())) { + return false; + } + if (!getPhone().equals(other.getPhone())) { + return false; + } + if (!getAddress().equals(other.getAddress())) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() + @Override + public int hashCode() { + int hash = 1; + if (hotelId_ != null) { + hash ^= getHotelId().hashCode(); + } + if (name_ != null) { + hash ^= getName().hashCode(); + } + if (phone_ != null) { + hash ^= getPhone().hashCode(); + } + if (address_ != null) { + hash ^= getAddress().hashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.hashCode(); + } + return hash; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() + @Override + public String toString() { + return Google.Protobuf.JsonFormatter.ToDiagnosticString(this); + } + +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/PostalCode.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/PostalCode.java new file mode 100644 index 0000000..58148f3 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CassandraHotel/Protobuf/PostalCode.java @@ -0,0 +1,232 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf.CassandraHotel.Protobuf; + +import azure.data.cosmos.serialization.hybridrow.Tests.Perf.*; + +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: TestData/CassandraHotelSchema.proto +// + +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pb = Google.Protobuf; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbc = Google.Protobuf.Collections; +//C# TO JAVA CONVERTER NOTE: There is no Java equivalent to C# namespace aliases: +//using pbr = Google.Protobuf.Reflection; + +public final class PostalCode implements Google.Protobuf.IMessage { + /** + * Field number for the "plus4" field. + */ + public static final int Plus4FieldNumber = 2; + /** + * Field number for the "zip" field. + */ + public static final int ZipFieldNumber = 1; + private static final Google.Protobuf.MessageParser _parser = + new Google.Protobuf.MessageParser(() -> new PostalCode()); + private static final Google.Protobuf.FieldCodec _single_plus4_codec = + Google.Protobuf.FieldCodec.ForStructWrapper(18); + private static final Google.Protobuf.FieldCodec _single_zip_codec = + Google.Protobuf.FieldCodec.ForStructWrapper(10); + private Google.Protobuf.UnknownFieldSet _unknownFields; + + // TODO: C# TO JAVA CONVERTER: Java does not support 'partial' methods: + // partial void OnConstruction(); + private Integer plus4_; + private Integer zip_; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public PostalCode() + public PostalCode() { + OnConstruction(); + } + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public PostalCode(PostalCode other) + public PostalCode(PostalCode other) { + this(); + setZip(other.getZip()); + setPlus4(other.getPlus4()); + _unknownFields = Google.Protobuf.UnknownFieldSet.Clone(other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public static Google.Protobuf.Reflection + // .MessageDescriptor Descriptor + public static Google.Protobuf.Reflection.MessageDescriptor getDescriptor() { + return Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.CassandraHotelSchemaReflection.getDescriptor().MessageTypes[0]; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor + public Google.Protobuf.Reflection getDescriptor() { + return getDescriptor(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public static Google.Protobuf + // .MessageParser Parser + public static Google.Protobuf.MessageParser getParser() { + return _parser; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Nullable Plus4 + public Integer getPlus4() { + return plus4_; + } + + public void setPlus4(Integer value) { + plus4_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public Nullable Zip + public Integer getZip() { + return zip_; + } + + public void setZip(Integer value) { + zip_ = value; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() + public int CalculateSize() { + int size = 0; + if (zip_ != null) { + size += _single_zip_codec.CalculateSizeWithTag(getZip()); + } + if (plus4_ != null) { + size += _single_plus4_codec.CalculateSizeWithTag(getPlus4()); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public PostalCode Clone() + public PostalCode Clone() { + return new PostalCode(this); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PostalCode other) + public void MergeFrom(PostalCode other) { + if (other == null) { + return; + } + if (other.zip_ != null) { + if (zip_ == null || other.getZip() != 0) { + setZip(other.getZip()); + } + } + if (other.plus4_ != null) { + if (plus4_ == null || other.getPlus4() != 0) { + setPlus4(other.getPlus4()); + } + } + _unknownFields = Google.Protobuf.UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Google.Protobuf + // .CodedInputStream input) + public void MergeFrom(Google.Protobuf.CodedInputStream input) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint tag; + int tag; + while ((tag = input.ReadTag()) != 0) { + switch (tag) { + default: + _unknownFields = Google.Protobuf.UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Integer value = _single_zip_codec.Read(input); + if (zip_ == null || value != 0) { + setZip(value); + } + break; + } + case 18: { + Integer value = _single_plus4_codec.Read(input); + if (plus4_ == null || value != 0) { + setPlus4(value); + } + break; + } + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(Google.Protobuf + // .CodedOutputStream output) + public void WriteTo(Google.Protobuf.CodedOutputStream output) { + if (zip_ != null) { + _single_zip_codec.WriteTagAndValue(output, getZip()); + } + if (plus4_ != null) { + _single_plus4_codec.WriteTagAndValue(output, getPlus4()); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) + @Override + public boolean equals(Object other) { + return Equals(other instanceof PostalCode ? (PostalCode)other : null); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PostalCode other) + public boolean equals(PostalCode other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (getZip() != other.getZip()) { + return false; + } + if (getPlus4() != other.getPlus4()) { + return false; + } + return Equals(_unknownFields, other._unknownFields); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() + @Override + public int hashCode() { + int hash = 1; + if (zip_ != null) { + hash ^= getZip().hashCode(); + } + if (plus4_ != null) { + hash ^= getPlus4().hashCode(); + } + if (_unknownFields != null) { + hash ^= _unknownFields.hashCode(); + } + return hash; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() + @Override + public String toString() { + return Google.Protobuf.JsonFormatter.ToDiagnosticString(this); + } + +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CodeGenMicroBenchmarkSuite.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CodeGenMicroBenchmarkSuite.java new file mode 100644 index 0000000..de42a6f --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CodeGenMicroBenchmarkSuite.java @@ -0,0 +1,311 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import azure.data.cosmos.serialization.hybridrow.Result; + +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.HashMap; +import java.util.List; + +/** + * Tests involving generated (early bound) code compiled from schema based on a partial implementation + * of Cassandra Hotel Schema described here: https: //www.oreilly.com/ideas/cassandra-data-modeling . + *

+ * The tests here differ from in that they rely on + * the schema being known at compile time instead of runtime. This allows code to be generated that + * directly addresses the schema structure instead of dynamically discovering schema structure at + * runtime. + *

+ */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass] public sealed class CodeGenMicroBenchmarkSuite : MicroBenchmarkSuiteBase +public final class CodeGenMicroBenchmarkSuite extends MicroBenchmarkSuiteBase { + private static final int GuestCount = 1000; + private static final int HotelCount = 10000; + private static final int RoomsCount = 10000; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task CodeGenGuestsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task CodeGenGuestsReadBenchmarkAsync() + public Task CodeGenGuestsReadBenchmarkAsync() { + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.CodeGenReadBenchmark(resolver, "Guests", "Guests", + CodeGenMicroBenchmarkSuite.GuestCount, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task CodeGenGuestsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task CodeGenGuestsWriteBenchmarkAsync() + public Task CodeGenGuestsWriteBenchmarkAsync() { + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.CodeGenWriteBenchmark(resolver, "Guests", "Guests", + CodeGenMicroBenchmarkSuite.GuestCount, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task CodeGenHotelReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task CodeGenHotelReadBenchmarkAsync() + public Task CodeGenHotelReadBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.CodeGenReadBenchmark(resolver, "Hotels", "Hotels", + CodeGenMicroBenchmarkSuite.HotelCount, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task CodeGenHotelWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task CodeGenHotelWriteBenchmarkAsync() + public Task CodeGenHotelWriteBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.CodeGenWriteBenchmark(resolver, "Hotels", "Hotels", + CodeGenMicroBenchmarkSuite.HotelCount, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task CodeGenRoomsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task CodeGenRoomsReadBenchmarkAsync() + public Task CodeGenRoomsReadBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.CodeGenReadBenchmark(resolver, "Available_Rooms_By_Hotel_Date", "Rooms", + CodeGenMicroBenchmarkSuite.RoomsCount, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task CodeGenRoomsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task CodeGenRoomsWriteBenchmarkAsync() + public Task CodeGenRoomsWriteBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.CodeGenWriteBenchmark(resolver, "Available_Rooms_By_Hotel_Date", "Rooms", + CodeGenMicroBenchmarkSuite.RoomsCount, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task ProtobufGuestsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task ProtobufGuestsReadBenchmarkAsync() + public Task ProtobufGuestsReadBenchmarkAsync() { + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.ProtobufReadBenchmark("Guests", "Guests", CodeGenMicroBenchmarkSuite.GuestCount, + expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task ProtobufGuestsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task ProtobufGuestsWriteBenchmarkAsync() + public Task ProtobufGuestsWriteBenchmarkAsync() { + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.ProtobufWriteBenchmark("Guests", "Guests", CodeGenMicroBenchmarkSuite.GuestCount, + expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task ProtobufHotelReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task ProtobufHotelReadBenchmarkAsync() + public Task ProtobufHotelReadBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.ProtobufReadBenchmark("Hotels", "Hotels", CodeGenMicroBenchmarkSuite.HotelCount, + expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task ProtobufHotelWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task ProtobufHotelWriteBenchmarkAsync() + public Task ProtobufHotelWriteBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.ProtobufWriteBenchmark("Hotels", "Hotels", CodeGenMicroBenchmarkSuite.HotelCount, + expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task ProtobufRoomsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task ProtobufRoomsReadBenchmarkAsync() + public Task ProtobufRoomsReadBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.ProtobufReadBenchmark("Available_Rooms_By_Hotel_Date", "Rooms", + CodeGenMicroBenchmarkSuite.RoomsCount, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task ProtobufRoomsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task ProtobufRoomsWriteBenchmarkAsync() + public Task ProtobufRoomsWriteBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + CodeGenMicroBenchmarkSuite.ProtobufWriteBenchmark("Available_Rooms_By_Hotel_Date", "Rooms", + CodeGenMicroBenchmarkSuite.RoomsCount, expected); + } + + private static void CodeGenReadBenchmark(LayoutResolverNamespace resolver, String schemaName, String dataSetName, + int innerLoopIterations, ArrayList> expected) { + // Serialize input data to sequence of byte buffers. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: List expectedSerialized = new List(expected.Count); + ArrayList expectedSerialized = new ArrayList(expected.size()); + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = + schemaName.equals( > x.Name)).SchemaId) + BenchmarkContext context = new BenchmarkContext(); + context.CodeGenWriter = new CodeGenRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, resolver); + + for (HashMap tableValue : expected) { + context.CodeGenWriter.Reset(); + + Result r = context.CodeGenWriter.WriteBuffer(tableValue); + ResultAssert.IsSuccess(r); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: expectedSerialized.Add(context.CodeGenWriter.ToArray()); + expectedSerialized.add(context.CodeGenWriter.ToArray()); + } + + tangible.RefObject tempRef_context = new tangible.RefObject(context); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MicroBenchmarkSuiteBase.Benchmark("CodeGen", "Read", dataSetName, "HybridRowGen", innerLoopIterations, ref context, (ref BenchmarkContext ctx, byte[] tableValue) => + MicroBenchmarkSuiteBase.Benchmark("CodeGen", "Read", dataSetName, "HybridRowGen", innerLoopIterations, tempRef_context, (ref BenchmarkContext ctx, byte[] tableValue) -> + { + Result r = ctx.CodeGenWriter.ReadBuffer(tableValue); + ResultAssert.IsSuccess(r); + }, (ref BenchmarkContext ctx, byte[] tableValue) -> tableValue.length, expectedSerialized); + context = tempRef_context.argValue; + } + + private static void CodeGenWriteBenchmark(LayoutResolverNamespace resolver, String schemaName, String dataSetName + , int innerLoopIterations, ArrayList> expected) { + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = + schemaName.equals( > x.Name)).SchemaId) + BenchmarkContext context = new BenchmarkContext(); + context.CodeGenWriter = new CodeGenRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, resolver); + + tangible.RefObject tempRef_context = new tangible.RefObject(context); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + MicroBenchmarkSuiteBase.Benchmark("CodeGen", "Write", dataSetName, "HybridRowGen", innerLoopIterations, + tempRef_context, (ref BenchmarkContext ctx, HashMap tableValue) -> + { + ctx.CodeGenWriter.Reset(); + + Result r = ctx.CodeGenWriter.WriteBuffer(tableValue); + ResultAssert.IsSuccess(r); + }, (ref BenchmarkContext ctx, HashMap tableValue) -> ctx.CodeGenWriter.Length, expected); + context = tempRef_context.argValue; + } + + private static void ProtobufReadBenchmark(String schemaName, String dataSetName, int innerLoopIterations, + ArrayList> expected) { + // Serialize input data to sequence of byte buffers. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: List expectedSerialized = new List(expected.Count); + ArrayList expectedSerialized = new ArrayList(expected.size()); + BenchmarkContext context = new BenchmarkContext(); + context.ProtobufWriter = new ProtobufRowGenerator(schemaName, BenchmarkSuiteBase.InitialCapacity); + + for (HashMap tableValue : expected) { + context.ProtobufWriter.WriteBuffer(tableValue); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: expectedSerialized.Add(context.ProtobufWriter.ToArray()); + expectedSerialized.add(context.ProtobufWriter.ToArray()); + } + + tangible.RefObject tempRef_context = new tangible.RefObject(context); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MicroBenchmarkSuiteBase.Benchmark("CodeGen", "Read", dataSetName, "Protobuf", + // innerLoopIterations, ref context, (ref BenchmarkContext ctx, byte[] tableValue) => ctx.ProtobufWriter + // .ReadBuffer(tableValue), (ref BenchmarkContext ctx, byte[] tableValue) => tableValue.Length, + // expectedSerialized); + MicroBenchmarkSuiteBase.Benchmark("CodeGen", "Read", dataSetName, "Protobuf", innerLoopIterations, + tempRef_context, + (ref BenchmarkContext ctx, byte[] tableValue) -> ctx.ProtobufWriter.ReadBuffer(tableValue), + (ref BenchmarkContext ctx, byte[] tableValue) -> tableValue.length, expectedSerialized); + context = tempRef_context.argValue; + } + + private static void ProtobufWriteBenchmark(String schemaName, String dataSetName, int innerLoopIterations, + ArrayList> expected) { + BenchmarkContext context = new BenchmarkContext(); + context.ProtobufWriter = new ProtobufRowGenerator(schemaName, BenchmarkSuiteBase.InitialCapacity); + + tangible.RefObject tempRef_context = new tangible.RefObject(context); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + MicroBenchmarkSuiteBase.Benchmark("CodeGen", "Write", dataSetName, "Protobuf", innerLoopIterations, + tempRef_context, (ref BenchmarkContext ctx, HashMap tableValue) -> + { + ctx.ProtobufWriter.WriteBuffer(tableValue); + }, (ref BenchmarkContext ctx, HashMap tableValue) -> ctx.ProtobufWriter.Length, expected); + context = tempRef_context.argValue; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CodeGenRowGenerator.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CodeGenRowGenerator.java new file mode 100644 index 0000000..1a855ca --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/CodeGenRowGenerator.java @@ -0,0 +1,1157 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.ISpanResizer; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; +import azure.data.cosmos.serialization.hybridrow.perf.CodeGenRowGenerator.GuestsHybridRowSerializer; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.UUID; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: internal ref struct CodeGenRowGenerator +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# ref struct: +public final class CodeGenRowGenerator { + private HybridRowSerializer dispatcher; + private RowBuffer row = new RowBuffer(); + + + public CodeGenRowGenerator(int capacity, Layout layout, LayoutResolver resolver) { + this(capacity, layout, resolver, null); + } + + public CodeGenRowGenerator() { + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public CodeGenRowGenerator(int capacity, Layout layout, LayoutResolver resolver, + // ISpanResizer resizer = default) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public CodeGenRowGenerator(int capacity, Layout layout, LayoutResolver resolver, ISpanResizer resizer) { + this.row = new RowBuffer(capacity, resizer); + this.row.InitLayout(HybridRowVersion.V1, layout, resolver); + + switch (layout.getName()) { + case "Hotels": + this.dispatcher = new HotelsHybridRowSerializer(layout, resolver); + break; + + case "Guests": + this.dispatcher = new GuestsHybridRowSerializer(layout, resolver); + break; + + case "Available_Rooms_By_Hotel_Date": + this.dispatcher = new RoomsHybridRowSerializer(layout, resolver); + break; + + default: + Contract.Fail(String.format("Unknown schema will be ignored: %1$s", layout.getName())); + this.dispatcher = null; + break; + } + } + + public int getLength() { + return this.row.getLength(); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Result ReadBuffer(byte[] buffer) + public Result ReadBuffer(byte[] buffer) { + this.row = new RowBuffer(buffer.AsSpan(), HybridRowVersion.V1, this.row.getResolver()); + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + RowCursor root = RowCursor.Create(tempRef_row); + this.row = tempRef_row.argValue; + tangible.RefObject tempRef_row2 = + new tangible.RefObject(this.row); + tangible.RefObject tempRef_root = + new tangible.RefObject(root); + Result tempVar = this.dispatcher.ReadBuffer(tempRef_row2, tempRef_root); + root = tempRef_root.argValue; + this.row = tempRef_row2.argValue; + return tempVar; + } + + public void Reset() { + Layout layout = this.row.getResolver().Resolve(this.row.getHeader().getSchemaId().clone()); + this.row.InitLayout(HybridRowVersion.V1, layout, this.row.getResolver()); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public byte[] ToArray() + public byte[] ToArray() { + return this.row.ToArray(); + } + + public Result WriteBuffer(HashMap tableValue) { + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + RowCursor root = RowCursor.Create(tempRef_row); + this.row = tempRef_row.argValue; + tangible.RefObject tempRef_row2 = + new tangible.RefObject(this.row); + tangible.RefObject tempRef_root = + new tangible.RefObject(root); + Result tempVar = this.dispatcher.WriteBuffer(tempRef_row2, tempRef_root, tableValue); + root = tempRef_root.argValue; + this.row = tempRef_row2.argValue; + return tempVar; + } + + public CodeGenRowGenerator clone() { + CodeGenRowGenerator varCopy = new CodeGenRowGenerator(); + + varCopy.row = this.row.clone(); + varCopy.dispatcher = this.dispatcher; + + return varCopy; + } + + private final static class AddressHybridRowSerializer extends HybridRowSerializer { + private static final Utf8String CityName = Utf8String.TranscodeUtf16("city"); + private static final Utf8String PostalCodeName = Utf8String.TranscodeUtf16("postal_code"); + private static final Utf8String StateName = Utf8String.TranscodeUtf16("state"); + private static final Utf8String StreetName = Utf8String.TranscodeUtf16("street"); + private LayoutColumn city; + private LayoutColumn postalCode; + private PostalCodeHybridRowSerializer postalCodeSerializer; + private StringToken postalCodeToken = new StringToken(); + private LayoutColumn state; + private LayoutColumn street; + + public AddressHybridRowSerializer(Layout layout, LayoutResolver resolver) { + tangible.OutObject tempOut_street = new tangible.OutObject(); + layout.TryFind(AddressHybridRowSerializer.StreetName, tempOut_street); + this.street = tempOut_street.argValue; + tangible.OutObject tempOut_city = new tangible.OutObject(); + layout.TryFind(AddressHybridRowSerializer.CityName, tempOut_city); + this.city = tempOut_city.argValue; + tangible.OutObject tempOut_state = new tangible.OutObject(); + layout.TryFind(AddressHybridRowSerializer.StateName, tempOut_state); + this.state = tempOut_state.argValue; + tangible.OutObject tempOut_postalCode = new tangible.OutObject(); + layout.TryFind(AddressHybridRowSerializer.PostalCodeName, tempOut_postalCode); + this.postalCode = tempOut_postalCode.argValue; + tangible.OutObject tempOut_postalCodeToken = new tangible.OutObject(); + layout.getTokenizer().TryFindToken(this.postalCode.getPath(), tempOut_postalCodeToken); + this.postalCodeToken = tempOut_postalCodeToken.argValue; + this.postalCodeSerializer = new PostalCodeHybridRowSerializer(resolver.Resolve(this.postalCode.getTypeArgs().getSchemaId().clone()), resolver); + } + + @Override + public Result ReadBuffer(tangible.RefObject row, tangible.RefObject root) { + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = LayoutType.Utf8.ReadVariable(row, root, this.street, out _); + if (r != Result.Success) { + return r; + } + + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + r = LayoutType.Utf8.ReadVariable(row, root, this.city, out _); + if (r != Result.Success) { + return r; + } + + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + r = LayoutType.Utf8.ReadFixed(row, root, this.state, out _); + if (r != Result.Success) { + return r; + } + + root.argValue.Find(row, this.postalCodeToken.clone()); + RowCursor childScope; + tangible.OutObject tempOut_childScope = new tangible.OutObject(); + r = LayoutType.UDT.ReadScope(row, root, tempOut_childScope); + childScope = tempOut_childScope.argValue; + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_childScope = new tangible.RefObject(childScope); + r = this.postalCodeSerializer.ReadBuffer(row, tempRef_childScope); + childScope = tempRef_childScope.argValue; + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_childScope2 = new tangible.RefObject(childScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, tempRef_childScope2); + childScope = tempRef_childScope2.argValue; + return Result.Success; + } + + @Override + public Result WriteBuffer(tangible.RefObject row, tangible.RefObject root, HashMap tableValue) { + for ((Utf8String key,Object value) :tableValue) + { + Result r; + switch (0) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' statements: + //ORIGINAL LINE: case 0 when key.Equals(AddressHybridRowSerializer.StreetName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteVariable(row, root, this.street, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' statements: + //ORIGINAL LINE: case 0 when key.Equals(AddressHybridRowSerializer.CityName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteVariable(row, root, this.city, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' statements: + //ORIGINAL LINE: case 0 when key.Equals(AddressHybridRowSerializer.StateName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteFixed(row, root, this.state, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' statements: + //ORIGINAL LINE: case 0 when key.Equals(AddressHybridRowSerializer.PostalCodeName): + case 0 + if (value != null) { + root.argValue.Find(row, this.postalCodeToken.clone()); + RowCursor childScope; + tangible.OutObject tempOut_childScope = new tangible.OutObject(); + r = LayoutType.UDT.WriteScope(row, root, this.postalCode.getTypeArgs().clone(), tempOut_childScope); + childScope = tempOut_childScope.argValue; + + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_childScope = new tangible.RefObject(childScope); + r = this.postalCodeSerializer.WriteBuffer(row, tempRef_childScope, (HashMap)value); + childScope = tempRef_childScope.argValue; + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_childScope2 = new tangible.RefObject(childScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, tempRef_childScope2); + childScope = tempRef_childScope2.argValue; + } + + break; + + default: + Contract.Fail(String.format("Unknown property name: %1$s", key)); + break; + } + } + + return Result.Success; + } + } + + private final static class GuestsHybridRowSerializer extends HybridRowSerializer { + private static final Utf8String AddressesName = Utf8String.TranscodeUtf16("addresses"); + private static final Utf8String ConfirmNumberName = Utf8String.TranscodeUtf16("confirm_number"); + private static final Utf8String EmailsName = Utf8String.TranscodeUtf16("emails"); + private static final Utf8String FirstNameName = Utf8String.TranscodeUtf16("first_name"); + private static final Utf8String GuestIdName = Utf8String.TranscodeUtf16("guest_id"); + private static final Utf8String LastNameName = Utf8String.TranscodeUtf16("last_name"); + private static final Utf8String PhoneNumbersName = Utf8String.TranscodeUtf16("phone_numbers"); + private static final Utf8String TitleName = Utf8String.TranscodeUtf16("title"); + private AddressHybridRowSerializer addressSerializer; + private LayoutScope.WriterFunc> addressSerializerWriter; + private LayoutColumn addresses; + private TypeArgumentList addressesFieldType = new TypeArgumentList(); + private StringToken addressesToken = new StringToken(); + private LayoutColumn confirmNumber; + private LayoutColumn emails; + private StringToken emailsToken = new StringToken(); + private LayoutColumn firstName; + private LayoutColumn guestId; + private LayoutColumn lastName; + private LayoutColumn phoneNumbers; + private StringToken phoneNumbersToken = new StringToken(); + private LayoutColumn title; + + public GuestsHybridRowSerializer(Layout layout, LayoutResolver resolver) { + tangible.OutObject tempOut_guestId = + new tangible.OutObject(); + layout.TryFind(GuestsHybridRowSerializer.GuestIdName, tempOut_guestId); + this.guestId = tempOut_guestId.argValue; + tangible.OutObject tempOut_firstName = new tangible.OutObject(); + layout.TryFind(GuestsHybridRowSerializer.FirstNameName, tempOut_firstName); + this.firstName = tempOut_firstName.argValue; + tangible.OutObject tempOut_lastName + = new tangible.OutObject(); + layout.TryFind(GuestsHybridRowSerializer.LastNameName, tempOut_lastName); + this.lastName = tempOut_lastName.argValue; + tangible.OutObject tempOut_title = + new tangible.OutObject(); + layout.TryFind(GuestsHybridRowSerializer.TitleName, tempOut_title); + this.title = tempOut_title.argValue; + tangible.OutObject tempOut_emails = + new tangible.OutObject(); + layout.TryFind(GuestsHybridRowSerializer.EmailsName, tempOut_emails); + this.emails = tempOut_emails.argValue; + tangible.OutObject tempOut_phoneNumbers = new tangible.OutObject(); + layout.TryFind(GuestsHybridRowSerializer.PhoneNumbersName, tempOut_phoneNumbers); + this.phoneNumbers = tempOut_phoneNumbers.argValue; + tangible.OutObject tempOut_addresses = new tangible.OutObject(); + layout.TryFind(GuestsHybridRowSerializer.AddressesName, tempOut_addresses); + this.addresses = tempOut_addresses.argValue; + tangible.OutObject tempOut_confirmNumber = new tangible.OutObject(); + layout.TryFind(GuestsHybridRowSerializer.ConfirmNumberName, tempOut_confirmNumber); + this.confirmNumber = tempOut_confirmNumber.argValue; + tangible.OutObject tempOut_emailsToken = new tangible.OutObject(); + layout.getTokenizer().TryFindToken(this.emails.getPath(), tempOut_emailsToken); + this.emailsToken = tempOut_emailsToken.argValue; + tangible.OutObject tempOut_phoneNumbersToken = new tangible.OutObject(); + layout.getTokenizer().TryFindToken(this.phoneNumbers.getPath(), tempOut_phoneNumbersToken); + this.phoneNumbersToken = tempOut_phoneNumbersToken.argValue; + tangible.OutObject tempOut_addressesToken = new tangible.OutObject(); + layout.getTokenizer().TryFindToken(this.addresses.getPath(), tempOut_addressesToken); + this.addressesToken = tempOut_addressesToken.argValue; + + this.addressesFieldType = + new TypeArgumentList(new TypeArgument[] { new TypeArgument(LayoutType.TypedTuple, + this.addresses.getTypeArgs().clone()) }); + + this.addressSerializer = + new AddressHybridRowSerializer(resolver.Resolve(this.addresses.getTypeArgs().get(1).getTypeArgs().getSchemaId().clone()), resolver); + this.addressSerializerWriter = (tangible.RefObject b, tangible.RefObject scope, + HashMap context) -> addressSerializer.WriteBuffer(b, + scope, context); + } + + @Override + public Result ReadBuffer(tangible.RefObject row, tangible.RefObject root) { + java.util.UUID _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + Result r = LayoutType.Guid.ReadFixed(row, root, this.guestId, tempOut__); + _ = tempOut__.argValue; + if (r != Result.Success) { + return r; + } + + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + r = LayoutType.Utf8.ReadVariable(row, root, this.firstName, out _); + if (r != Result.Success) { + return r; + } + + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + r = LayoutType.Utf8.ReadVariable(row, root, this.lastName, out _); + if (r != Result.Success) { + return r; + } + + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + r = LayoutType.Utf8.ReadVariable(row, root, this.title, out _); + if (r != Result.Success) { + return r; + } + + root.argValue.Find(row, this.emailsToken.clone()); + RowCursor childScope; + tangible.OutObject tempOut_childScope = + new tangible.OutObject(); + r = LayoutType.TypedArray.ReadScope(row, root, tempOut_childScope); + childScope = tempOut_childScope.argValue; + if (r != Result.Success) { + return r; + } + + while (childScope.MoveNext(row)) { + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + r = LayoutType.Utf8.ReadSparse(row, ref childScope, out _); + if (r != Result.Success) { + return r; + } + } + + tangible.RefObject tempRef_childScope = + new tangible.RefObject(childScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, + tempRef_childScope); + childScope = tempRef_childScope.argValue; + root.argValue.Find(row, this.phoneNumbersToken.clone()); + tangible.OutObject tempOut_childScope2 = + new tangible.OutObject(); + r = LayoutType.TypedArray.ReadScope(row, root, tempOut_childScope2); + childScope = tempOut_childScope2.argValue; + if (r != Result.Success) { + return r; + } + + while (childScope.MoveNext(row)) { + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + r = LayoutType.Utf8.ReadSparse(row, ref childScope, out _); + if (r != Result.Success) { + return r; + } + } + + tangible.RefObject tempRef_childScope2 = + new tangible.RefObject(childScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, + tempRef_childScope2); + childScope = tempRef_childScope2.argValue; + root.argValue.Find(row, this.addressesToken.clone()); + tangible.OutObject tempOut_childScope3 = + new tangible.OutObject(); + r = LayoutType.TypedMap.ReadScope(row, root, tempOut_childScope3); + childScope = tempOut_childScope3.argValue; + if (r != Result.Success) { + return r; + } + + while (childScope.MoveNext(row)) { + tangible.RefObject tempRef_childScope3 = + new tangible.RefObject(childScope); + RowCursor tupleScope; + tangible.OutObject tempOut_tupleScope = + new tangible.OutObject(); + r = LayoutType.TypedTuple.ReadScope(row, tempRef_childScope3, tempOut_tupleScope); + tupleScope = tempOut_tupleScope.argValue; + childScope = tempRef_childScope3.argValue; + if (r != Result.Success) { + return r; + } + + if (!tupleScope.MoveNext(row)) { + return Result.InvalidRow; + } + + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + r = LayoutType.Utf8.ReadSparse(row, ref tupleScope, out _); + if (r != Result.Success) { + return r; + } + + if (!tupleScope.MoveNext(row)) { + return Result.InvalidRow; + } + + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + RowCursor valueScope; + tangible.OutObject tempOut_valueScope = + new tangible.OutObject(); + r = LayoutType.ImmutableUDT.ReadScope(row, tempRef_tupleScope, tempOut_valueScope); + valueScope = tempOut_valueScope.argValue; + tupleScope = tempRef_tupleScope.argValue; + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_valueScope = + new tangible.RefObject(valueScope); + r = this.addressSerializer.ReadBuffer(row, tempRef_valueScope); + valueScope = tempRef_valueScope.argValue; + if (r != Result.Success) { + return r; + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + tupleScope.Skip(row, ref valueScope); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + childScope.Skip(row, ref tupleScope); + } + + tangible.RefObject tempRef_childScope4 = + new tangible.RefObject(childScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, + tempRef_childScope4); + childScope = tempRef_childScope4.argValue; + + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + return LayoutType.Utf8.ReadVariable(row, root, this.confirmNumber, out _); + } + + @Override + public Result WriteBuffer(tangible.RefObject row, tangible.RefObject root, + HashMap tableValue) { + for ((Utf8String key,Object value) :tableValue) + { + Result r; + switch (0) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(GuestsHybridRowSerializer.GuestIdName): + case 0 + if (value != null) { + r = LayoutType.Guid.WriteFixed(row, root, this.guestId, (UUID)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(GuestsHybridRowSerializer.FirstNameName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteVariable(row, root, this.firstName, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(GuestsHybridRowSerializer.LastNameName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteVariable(row, root, this.lastName, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(GuestsHybridRowSerializer.TitleName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteVariable(row, root, this.title, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(GuestsHybridRowSerializer.EmailsName): + case 0 + if (value != null) { + root.argValue.Find(row, this.emailsToken.clone()); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' + // keyword - these are not converted by C# to Java Converter: + r = LayoutType.TypedArray.WriteScope(row, root, this.emails.getTypeArgs().clone(), + (ArrayList)value, (ref RowBuffer row2, ref RowCursor childScope, + ArrayList context) -> + { + for (Object item : context) { + tangible.RefObjecttempRef_row2 = new tangible.RefObject (row2); + tangible.RefObjecttempRef_childScope = new tangible.RefObject (childScope); + Result r2 = LayoutType.Utf8.WriteSparse(tempRef_row2, tempRef_childScope, + (Utf8String)item); + childScope = tempRef_childScope.argValue; + row2 = tempRef_row2.argValue; + if (r2 != Result.Success) { + return r2; + } + + tangible.RefObjecttempRef_row22 = new tangible.RefObject (row2); + childScope.MoveNext(tempRef_row22); + row2 = tempRef_row22.argValue; + } + + return Result.Success; + }); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(GuestsHybridRowSerializer.PhoneNumbersName): + case 0 + if (value != null) { + root.argValue.Find(row, this.phoneNumbersToken.clone()); + RowCursor childScope; + tangible.OutObject tempOut_childScope = new tangible.OutObject(); + r = LayoutType.TypedArray.WriteScope(row, root, this.phoneNumbers.getTypeArgs().clone(), + tempOut_childScope); + childScope = tempOut_childScope.argValue; + if (r != Result.Success) { + return r; + } + + for (Object item : (ArrayList)value) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved + // 'ref' keyword - these cannot be converted using the 'RefObject' helper class + // unless the method is within the code being modified: + r = LayoutType.Utf8.WriteSparse(row, ref childScope, (Utf8String)item); + if (r != Result.Success) { + return r; + } + + childScope.MoveNext(row); + } + + tangible.RefObject tempRef_childScope = new tangible.RefObject(childScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, tempRef_childScope); + childScope = tempRef_childScope.argValue; + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(GuestsHybridRowSerializer.AddressesName): + case 0 + if (value != null) { + root.argValue.Find(row, this.addressesToken.clone()); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' + // keyword - these are not converted by C# to Java Converter: + r = LayoutType.TypedMap.WriteScope(row, root, this.addresses.getTypeArgs().clone(), (this + , (ArrayList)value), (ref + RowBuffer row2, ref RowCursor childScope, (GuestsHybridRowSerializer + _this, ArrayList < Object > value)ctx) -> + { + for (Object item : ctx.value) { + tangible.RefObject tempRef_row2 = new tangible.RefObject(row2); + tangible.RefObject tempRef_childScope = new tangible.RefObject(childScope); + Result r2 = LayoutType.TypedTuple.WriteScope(tempRef_row2, tempRef_childScope, + ctx._this.addresses.TypeArgs, (ctx._this, (ArrayList)item), + (ref RowBuffer row3, ref RowCursor tupleScope, (GuestsHybridRowSerializer + _this, ArrayList < Object > value)ctx2) -> + { + tangible.RefObjecttempRef_row3 = new tangible.RefObject (row3); + tangible.RefObjecttempRef_tupleScope = new tangible.RefObject (tupleScope); + Result r3 = LayoutType.Utf8.WriteSparse(tempRef_row3, tempRef_tupleScope, + (Utf8String)ctx2.value[0]); + tupleScope = tempRef_tupleScope.argValue; + row3 = tempRef_row3.argValue; + if (r3 != Result.Success) { + return r3; + } + + tangible.RefObjecttempRef_row32 = new tangible.RefObject (row3); + tupleScope.MoveNext(tempRef_row32); + row3 = tempRef_row32.argValue; + tangible.RefObject tempRef_row33 = new tangible.RefObject(row3); + tangible.RefObject tempRef_tupleScope2 = new tangible.RefObject(tupleScope); + Result tempVar = LayoutType.ImmutableUDT.WriteScope(tempRef_row33, + tempRef_tupleScope2, ctx2._this.addresses.TypeArgs[1].TypeArgs, + (HashMap)ctx2.value[1], + ctx2._this.addressSerializerWriter); + tupleScope = tempRef_tupleScope2.argValue; + row3 = tempRef_row33.argValue; + return tempVar; + }) + childScope = tempRef_childScope.argValue; + row2 = tempRef_row2.argValue; + if (r2 != Result.Success) { + return r2; + } + + tangible.RefObjecttempRef_row22 = new tangible.RefObject (row2); + childScope.MoveNext(tempRef_row22); + row2 = tempRef_row22.argValue; + } + + return Result.Success; + }) + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(GuestsHybridRowSerializer.ConfirmNumberName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteVariable(row, root, this.confirmNumber, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + default: + Contract.Fail(String.format("Unknown property name: %1$s", key)); + break; + } + } + + return Result.Success; + } + } + + private final static class HotelsHybridRowSerializer extends HybridRowSerializer { + private static final Utf8String AddressName = Utf8String.TranscodeUtf16("address"); + private static final Utf8String HotelIdName = Utf8String.TranscodeUtf16("hotel_id"); + private static final Utf8String NameName = Utf8String.TranscodeUtf16("name"); + private static final Utf8String PhoneName = Utf8String.TranscodeUtf16("phone"); + private LayoutColumn address; + private AddressHybridRowSerializer addressSerializer; + private StringToken addressToken = new StringToken(); + private LayoutColumn hotelId; + private LayoutColumn name; + private LayoutColumn phone; + + public HotelsHybridRowSerializer(Layout layout, LayoutResolver resolver) { + tangible.OutObject tempOut_hotelId = + new tangible.OutObject(); + layout.TryFind(HotelsHybridRowSerializer.HotelIdName, tempOut_hotelId); + this.hotelId = tempOut_hotelId.argValue; + tangible.OutObject tempOut_name = + new tangible.OutObject(); + layout.TryFind(HotelsHybridRowSerializer.NameName, tempOut_name); + this.name = tempOut_name.argValue; + tangible.OutObject tempOut_phone = + new tangible.OutObject(); + layout.TryFind(HotelsHybridRowSerializer.PhoneName, tempOut_phone); + this.phone = tempOut_phone.argValue; + tangible.OutObject tempOut_address = + new tangible.OutObject(); + layout.TryFind(HotelsHybridRowSerializer.AddressName, tempOut_address); + this.address = tempOut_address.argValue; + tangible.OutObject tempOut_addressToken = new tangible.OutObject(); + layout.getTokenizer().TryFindToken(this.address.getPath(), tempOut_addressToken); + this.addressToken = tempOut_addressToken.argValue; + this.addressSerializer = + new AddressHybridRowSerializer(resolver.Resolve(this.address.getTypeArgs().getSchemaId().clone()), + resolver); + } + + @Override + public Result ReadBuffer(tangible.RefObject row, tangible.RefObject root) { + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + Result r = LayoutType.Utf8.ReadFixed(row, root, this.hotelId, out _); + if (r != Result.Success) { + return r; + } + + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + r = LayoutType.Utf8.ReadVariable(row, root, this.name, out _); + if (r != Result.Success) { + return r; + } + + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + r = LayoutType.Utf8.ReadVariable(row, root, this.phone, out _); + if (r != Result.Success) { + return r; + } + + root.argValue.Find(row, this.addressToken.clone()); + RowCursor childScope; + tangible.OutObject tempOut_childScope = + new tangible.OutObject(); + r = LayoutType.UDT.ReadScope(row, root, tempOut_childScope); + childScope = tempOut_childScope.argValue; + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_childScope = + new tangible.RefObject(childScope); + r = this.addressSerializer.ReadBuffer(row, tempRef_childScope); + childScope = tempRef_childScope.argValue; + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_childScope2 = + new tangible.RefObject(childScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, + tempRef_childScope2); + childScope = tempRef_childScope2.argValue; + return Result.Success; + } + + @Override + public Result WriteBuffer(tangible.RefObject row, tangible.RefObject root, + HashMap tableValue) { + for ((Utf8String key,Object value) :tableValue) + { + Result r; + switch (0) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(HotelsHybridRowSerializer.HotelIdName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteFixed(row, root, this.hotelId, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(HotelsHybridRowSerializer.NameName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteVariable(row, root, this.name, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(HotelsHybridRowSerializer.PhoneName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteVariable(row, root, this.phone, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(HotelsHybridRowSerializer.AddressName): + case 0 + if (value != null) { + root.argValue.Find(row, this.addressToken.clone()); + RowCursor childScope; + tangible.OutObject tempOut_childScope = new tangible.OutObject(); + r = LayoutType.UDT.WriteScope(row, root, this.address.getTypeArgs().clone(), + tempOut_childScope); + childScope = tempOut_childScope.argValue; + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_childScope = new tangible.RefObject(childScope); + r = this.addressSerializer.WriteBuffer(row, tempRef_childScope, (HashMap)value); + childScope = tempRef_childScope.argValue; + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_childScope2 = new tangible.RefObject(childScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, tempRef_childScope2); + childScope = tempRef_childScope2.argValue; + } + + break; + + default: + Contract.Fail(String.format("Unknown property name: %1$s", key)); + break; + } + } + + return Result.Success; + } + } + + private abstract static class HybridRowSerializer { + public abstract Result ReadBuffer(tangible.RefObject row, tangible.RefObject root); + + public abstract Result WriteBuffer(tangible.RefObject row, tangible.RefObject root, + HashMap tableValue); + } + + private final static class PostalCodeHybridRowSerializer extends HybridRowSerializer { + private static final Utf8String Plus4Name = Utf8String.TranscodeUtf16("plus4"); + private static final Utf8String ZipName = Utf8String.TranscodeUtf16("zip"); + private LayoutColumn plus4; + private StringToken plus4Token = new StringToken(); + private LayoutColumn zip; + + // ReSharper disable once UnusedParameter.Local + public PostalCodeHybridRowSerializer(Layout layout, LayoutResolver resolver) { + tangible.OutObject tempOut_zip = + new tangible.OutObject(); + layout.TryFind(PostalCodeHybridRowSerializer.ZipName, tempOut_zip); + this.zip = tempOut_zip.argValue; + tangible.OutObject tempOut_plus4 = + new tangible.OutObject(); + layout.TryFind(PostalCodeHybridRowSerializer.Plus4Name, tempOut_plus4); + this.plus4 = tempOut_plus4.argValue; + tangible.OutObject tempOut_plus4Token = new tangible.OutObject(); + layout.getTokenizer().TryFindToken(this.plus4.getPath(), tempOut_plus4Token); + this.plus4Token = tempOut_plus4Token.argValue; + } + + @Override + public Result ReadBuffer(tangible.RefObject row, tangible.RefObject root) { + int _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + Result r = LayoutType.Int32.ReadFixed(row, root, this.zip, tempOut__); + _ = tempOut__.argValue; + if (r != Result.Success) { + return r; + } + + root.argValue.Find(row, this.plus4Token.clone()); + short _; + tangible.OutObject tempOut__2 = new tangible.OutObject(); + Result tempVar = LayoutType.Int16.ReadSparse(row, root, tempOut__2); + _ = tempOut__2.argValue; + return tempVar; + } + + @Override + public Result WriteBuffer(tangible.RefObject row, tangible.RefObject root, + HashMap tableValue) { + for ((Utf8String key,Object value) :tableValue) + { + Result r; + switch (0) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(PostalCodeHybridRowSerializer.ZipName): + case 0 + if (value != null) { + r = LayoutType.Int32.WriteFixed(row, root, this.zip, (int)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(PostalCodeHybridRowSerializer.Plus4Name): + case 0 + if (value != null) { + root.argValue.Find(row, this.plus4Token.clone()); + r = LayoutType.Int16.WriteSparse(row, root, (short)value); + if (r != Result.Success) { + return r; + } + } + + break; + + default: + Contract.Fail(String.format("Unknown property name: %1$s", key)); + break; + } + } + + return Result.Success; + } + } + + private final static class RoomsHybridRowSerializer extends HybridRowSerializer { + private static final Utf8String DateName = Utf8String.TranscodeUtf16("date"); + private static final Utf8String HotelIdName = Utf8String.TranscodeUtf16("hotel_id"); + private static final Utf8String IsAvailableName = Utf8String.TranscodeUtf16("is_available"); + private static final Utf8String RoomNumberName = Utf8String.TranscodeUtf16("room_number"); + private LayoutColumn date; + private LayoutColumn hotelId; + private LayoutColumn isAvailable; + private LayoutColumn roomNumber; + + // ReSharper disable once UnusedParameter.Local + public RoomsHybridRowSerializer(Layout layout, LayoutResolver resolver) { + tangible.OutObject tempOut_hotelId = + new tangible.OutObject(); + layout.TryFind(RoomsHybridRowSerializer.HotelIdName, tempOut_hotelId); + this.hotelId = tempOut_hotelId.argValue; + tangible.OutObject tempOut_date = + new tangible.OutObject(); + layout.TryFind(RoomsHybridRowSerializer.DateName, tempOut_date); + this.date = tempOut_date.argValue; + tangible.OutObject tempOut_roomNumber = new tangible.OutObject(); + layout.TryFind(RoomsHybridRowSerializer.RoomNumberName, tempOut_roomNumber); + this.roomNumber = tempOut_roomNumber.argValue; + tangible.OutObject tempOut_isAvailable = new tangible.OutObject(); + layout.TryFind(RoomsHybridRowSerializer.IsAvailableName, tempOut_isAvailable); + this.isAvailable = tempOut_isAvailable.argValue; + } + + @Override + public Result ReadBuffer(tangible.RefObject row, tangible.RefObject root) { + Utf8Span _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + Result r = LayoutType.Utf8.ReadFixed(row, root, this.hotelId, out _); + if (r != Result.Success) { + return r; + } + + java.time.LocalDateTime _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + r = LayoutType.DateTime.ReadFixed(row, root, this.date, tempOut__); + _ = tempOut__.argValue; + if (r != Result.Success) { + return r; + } + + byte _; + tangible.OutObject tempOut__2 = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = LayoutType.UInt8.ReadFixed(ref row, ref root, this.roomNumber, out byte _); + r = LayoutType.UInt8.ReadFixed(row, root, this.roomNumber, tempOut__2); + _ = tempOut__2.argValue; + if (r != Result.Success) { + return r; + } + + boolean _; + tangible.OutObject tempOut__3 = new tangible.OutObject(); + Result tempVar = LayoutType.Boolean.ReadFixed(row, root, this.isAvailable, tempOut__3); + _ = tempOut__3.argValue; + return tempVar; + } + + @Override + public Result WriteBuffer(tangible.RefObject row, tangible.RefObject root, + HashMap tableValue) { + for ((Utf8String key,Object value) :tableValue) + { + Result r; + switch (0) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(RoomsHybridRowSerializer.HotelIdName): + case 0 + if (value != null) { + r = LayoutType.Utf8.WriteFixed(row, root, this.hotelId, (Utf8String)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(RoomsHybridRowSerializer.DateName): + case 0 + if (value != null) { + r = LayoutType.DateTime.WriteFixed(row, root, this.date, (LocalDateTime)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(RoomsHybridRowSerializer.RoomNumberName): + case 0 + if (value != null) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = LayoutType.UInt8.WriteFixed(ref row, ref root, this.roomNumber, + // (byte)value); + r = LayoutType.UInt8.WriteFixed(row, root, this.roomNumber, (byte)value); + if (r != Result.Success) { + return r; + } + } + + break; + + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to the C# 'when' clause in 'case' + // statements: + //ORIGINAL LINE: case 0 when key.Equals(RoomsHybridRowSerializer.IsAvailableName): + case 0 + if (value != null) { + r = LayoutType.Boolean.WriteFixed(row, root, this.isAvailable, (boolean)value); + if (r != Result.Success) { + return r; + } + } + + break; + + default: + Contract.Fail(String.format("Unknown property name: %1$s", key)); + break; + } + } + + return Result.Success; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/GenerateBenchmarkSuite.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/GenerateBenchmarkSuite.java new file mode 100644 index 0000000..ee45d60 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/GenerateBenchmarkSuite.java @@ -0,0 +1,111 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import java.io.File; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.HashMap; +import java.util.List; +import java.util.Random; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][DeploymentItem(TestData.SchemaFile, TestData.Target)] public sealed class +// GenerateBenchmarkSuite : BenchmarkSuiteBase +public final class GenerateBenchmarkSuite extends BenchmarkSuiteBase { + private String sdl; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task GenerateGuestsBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task GenerateGuestsBenchmarkAsync() + public Task GenerateGuestsBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await this.GenerateBenchmarkAsync("Guests", 50, TestData.GuestsExpected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task GenerateHotelBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task GenerateHotelBenchmarkAsync() + public Task GenerateHotelBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await this.GenerateBenchmarkAsync("Hotels", 100, TestData.HotelExpected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task GenerateRoomsBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task GenerateRoomsBenchmarkAsync() + public Task GenerateRoomsBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await this.GenerateBenchmarkAsync("Available_Rooms_By_Hotel_Date", 100, TestData.RoomsExpected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public void ParseNamespaceExample() { + this.sdl = Files.readString(TestData.SchemaFile); + Namespace schema = Namespace.Parse(this.sdl); + this.DefaultResolver = new LayoutResolverNamespace(schema, SystemSchema.LayoutResolver); + } + + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: private async Task GenerateBenchmarkAsync(string schemaName, int outerLoopIterations, string + // expectedFile) + private Task GenerateBenchmarkAsync(String schemaName, int outerLoopIterations, String expectedFile) { + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + ArrayList> rows = GenerateBenchmarkSuite.GenerateBenchmarkInputs(resolver, + schemaName, outerLoopIterations); + + Schema tableSchema = resolver.Namespace.Schemas.Find(x = schemaName.equals( > x.Name)) + TypeArgument typeArg = new TypeArgument(LayoutType.UDT, + new TypeArgumentList(tableSchema.getSchemaId().clone())); + + boolean allMatch = rows.size() == expected.Count; + for (int i = 0; allMatch && i < rows.size(); i++) { + allMatch |= HybridRowValueGenerator.DynamicTypeArgumentEquals(resolver, expected[i], rows.get(i), + typeArg.clone()); + } + + if (!allMatch) { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await BenchmarkSuiteBase. + WriteAllRowsAsync(expectedFile, this.sdl, resolver, resolver.Resolve(tableSchema.getSchemaId().clone()), rows); + System.out.printf("Updated expected file at: %1$s" + "\r\n", (new File(expectedFile)).getAbsolutePath()); + Assert.IsTrue(allMatch, "Expected output does not match expected file."); + } + } + + private static ArrayList> GenerateBenchmarkInputs(LayoutResolverNamespace resolver, + String schemaName, + int outerLoopIterations) { + HybridRowGeneratorConfig generatorConfig = new HybridRowGeneratorConfig(); + final int seed = 42; + RandomGenerator rand = new RandomGenerator(new Random(seed)); + HybridRowValueGenerator valueGenerator = new HybridRowValueGenerator(rand, generatorConfig); + + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = + schemaName.equals( > x.Name)).SchemaId) + ArrayList> rows = new ArrayList>(outerLoopIterations); + for (int iteration = 0; iteration != outerLoopIterations; iteration += outerLoopIterations < 0 ? 0 : 1) { + TypeArgument typeArg = new TypeArgument(LayoutType.UDT, new TypeArgumentList(layout.getSchemaId().clone())); + HashMap rowValue = + (HashMap)valueGenerator.GenerateLayoutType(resolver, typeArg.clone()); + rows.add(rowValue); + } + + return rows; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/JsonModelRowGenerator.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/JsonModelRowGenerator.java new file mode 100644 index 0000000..ee199a5 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/JsonModelRowGenerator.java @@ -0,0 +1,186 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.ISpanResizer; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; + +import java.util.ArrayList; +import java.util.HashMap; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: public ref struct JsonModelRowGenerator +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# ref struct: +public final class JsonModelRowGenerator { + private RowBuffer row = new RowBuffer(); + + + public JsonModelRowGenerator(int capacity, Layout layout, LayoutResolver resolver) { + this(capacity, layout, resolver, null); + } + + public JsonModelRowGenerator() { + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public JsonModelRowGenerator(int capacity, Layout layout, LayoutResolver resolver, + // ISpanResizer resizer = default) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + public JsonModelRowGenerator(int capacity, Layout layout, LayoutResolver resolver, ISpanResizer resizer) { + this.row = new RowBuffer(capacity, resizer); + this.row.InitLayout(HybridRowVersion.V1, layout, resolver); + } + + public int getLength() { + return this.row.getLength(); + } + + public RowReader GetReader() { + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + return new RowReader(ref this.row) + this.row = tempRef_row.argValue; + return tempVar; + } + + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.Stream is input or + // output: + public boolean ReadFrom(Stream stream, int length) { + return this.row.ReadFrom(stream, length, HybridRowVersion.V1, this.row.getResolver()); + } + + public void Reset() { + Layout layout = this.row.getResolver().Resolve(this.row.getHeader().getSchemaId().clone()); + this.row.InitLayout(HybridRowVersion.V1, layout, this.row.getResolver()); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public byte[] ToArray() + public byte[] ToArray() { + return this.row.ToArray(); + } + + public Result WriteBuffer(HashMap value) { + tangible.RefObject tempRef_row = + new tangible.RefObject(this.row); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + Result tempVar = RowWriter.WriteBuffer(tempRef_row, value, (ref RowWriter writer, TypeArgument typeArg, + HashMap dict) -> + { + for ((Utf8String propPath,Object propValue) :dict) + { + tangible.RefObject tempRef_writer = + new tangible.RefObject(writer); + Result result = JsonModelRowGenerator.JsonModelSwitch(tempRef_writer, propPath, propValue); + writer = tempRef_writer.argValue; + return result; + } + + return Result.Success; + }); + this.row = tempRef_row.argValue; + return tempVar; + } + + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.Stream is input or + // output: + public void WriteTo(Stream stream) { + this.row.WriteTo(stream); + } + + public JsonModelRowGenerator clone() { + JsonModelRowGenerator varCopy = new JsonModelRowGenerator(); + + varCopy.row = this.row.clone(); + + return varCopy; + } + + private static Result JsonModelSwitch(tangible.RefObject writer, Utf8String path, Object value) { + switch (value) { + case null: + return writer.argValue.WriteNull(path); + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case bool x: + case + boolean x: + return writer.argValue.WriteBool(path, x); + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case long x: + case + long x: + return writer.argValue.WriteInt64(path, x); + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case double x: + case + double x: + return writer.argValue.WriteFloat64(path, x); + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case string x: + case String + x: + return writer.argValue.WriteString(path, x); + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case Utf8String x: + case Utf8String + x: + return writer.argValue.WriteString(path, x.Span); + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case byte[] x: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + case + byte[] x: + return writer.argValue.WriteBinary(path, x); + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case ReadOnlyMemory x: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + case ReadOnlyMemory < Byte > x: + return writer.argValue.WriteBinary(path, x.Span); + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case Dictionary x: + case HashMap < Utf8String, Object > x: + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these + // are not converted by C# to Java Converter: + return writer.argValue.WriteScope(path, new TypeArgument(LayoutType.Object), x, + (ref RowWriter writer2, TypeArgument typeArg, HashMap dict) -> + { + for ((Utf8String propPath,Object propValue) :dict) + { + tangible.RefObject tempRef_writer2 = new tangible.RefObject(writer2); + Result result = JsonModelRowGenerator.JsonModelSwitch(tempRef_writer2, propPath, propValue); + writer2 = tempRef_writer2.argValue; + return result; + } + + return Result.Success; + }); + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# pattern variables in 'case' statements: + //ORIGINAL LINE: case List x: + case ArrayList < Object > x: + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not converted by C# to Java Converter: + return writer.argValue.WriteScope(path, new TypeArgument(LayoutType.Array), x, (ref RowWriter writer2, TypeArgument typeArg, ArrayList list) -> + { + for (Object elm : list) { + tangible.RefObject tempRef_writer2 = new tangible.RefObject(writer2); + Result result = JsonModelRowGenerator.JsonModelSwitch(tempRef_writer2, null, elm); + writer2 = tempRef_writer2.argValue; + if (result != Result.Success) { + return result; + } + } + + return Result.Success; + }); + default: + Contract.Assert(false, String.format("Unknown type will be ignored: %1$s", value.getClass().getSimpleName())); + return Result.Failure; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/Measurements.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/Measurements.java new file mode 100644 index 0000000..1503cce --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/Measurements.java @@ -0,0 +1,63 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import java.io.Closeable; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.time.LocalDateTime; + +public class Measurements implements Closeable { + private static final long RunId = LocalDateTime.UtcNow.getTime(); + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.FileStream is + // input or output: + private FileStream file; + private TextWriter writer; + + public Measurements(String path) { + File info = new File(path); + if (info.exists()) { + this.file = new FileOutputStream(path, true); + this.writer = new OutputStreamWriter(this.file, java.nio.charset.StandardCharsets.US_ASCII); + } else { + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.FileStream + // is input or output: + this.file = new FileStream(path, FileMode.CreateNew); + this.writer = new OutputStreamWriter(this.file, java.nio.charset.StandardCharsets.US_ASCII); + this.writer.WriteLine("RunId,Model,Operation,Schema,API,Iterations,Size (bytes),Total (ms),Duration (ms)," + + "Allocated (bytes),ThreadId,Gen0,Gen1,Gen2,Total Allocated (bytes)"); + } + } + + public final void WriteMeasurement(String model, String operation, String schema, String api, + int outerLoopIterations, int innerLoopIterations, long totalSize, + double totalDurationMs, int threadId, int gen0, int gen1, int gen2, + long totalAllocatedBytes) { + System.out.printf("RunId: %1$s, \nModel: %2$s \nOperation: %3$s \nSchema: %4$s \nAPI: %5$s" + "\r\n", + Measurements.RunId, model, operation, schema, api); + + System.out.printf("\n\nIterations: %1$s \nSize (bytes): %1.0f \nTotal (ms): %2.4f \nDuration (ms): %3.4f " + + "\nAllocated (bytes): %4.4f" + "\r\n", outerLoopIterations, totalSize / outerLoopIterations, + totalDurationMs, totalDurationMs / (outerLoopIterations * innerLoopIterations), + totalAllocatedBytes / (outerLoopIterations * innerLoopIterations)); + + // TODO: C# TO JAVA CONVERTER: The '4:n0' format specifier is not converted to Java: + System.out.printf("\n\nThread: %1$s \nCollections: %2$s, %3$s, %4$s \nTotal Allocated: {4:n0} (bytes)" + "\r" + + "\n", threadId, gen0, gen1, gen2, totalAllocatedBytes); + + + this.writer.WriteLine("{0},{1},{2},{3},{4},{5},{6:F0},{7:F8},{8:F8},{9:F8},{10},{11},{12},{13},{14:0}", + Measurements.RunId, model, operation, schema, api, outerLoopIterations, totalSize / outerLoopIterations, + totalDurationMs, totalDurationMs / (outerLoopIterations * innerLoopIterations), totalAllocatedBytes / (outerLoopIterations * innerLoopIterations), threadId, gen0, gen1, gen2, totalAllocatedBytes); + } + + public final void close() throws IOException { + this.writer.Flush(); + this.writer.Dispose(); + this.file.Dispose(); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/MicroBenchmarkSuiteBase.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/MicroBenchmarkSuiteBase.java new file mode 100644 index 0000000..2792e4e --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/MicroBenchmarkSuiteBase.java @@ -0,0 +1,126 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import JetBrains.Profiler.Api.*; + +import java.util.ArrayList; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [SuppressMessage("Microsoft.Reliability", "CA2001:Avoid calling problematic methods", Justification +// = "Perf Benchmark")] public class MicroBenchmarkSuiteBase : BenchmarkSuiteBase +public class MicroBenchmarkSuiteBase extends BenchmarkSuiteBase { + private static final String MetricsResultFile = "HybridRowPerf.csv"; + private static final int WarmCount = 5; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Reliability", "CA2001:Avoid calling problematic methods", + // Justification = "Perf Benchmark")] private protected static void Benchmark(string model, string + // operation, string schema, string api, int innerLoopIterations, ref BenchmarkContext context, + // BenchmarkBody loopBody, BenchmarkMeasure measure, List expected) + //C# TO JAVA CONVERTER WARNING: Java has no equivalent to C# 'private protected' access: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Reliability", "CA2001:Avoid calling problematic methods", + // Justification = "Perf Benchmark")] private protected static void Benchmark(string model, string + // operation, string schema, string api, int innerLoopIterations, ref BenchmarkContext context, + // BenchmarkBody loopBody, BenchmarkMeasure measure, List expected) + protected static void Benchmark(String model, String operation, String schema, String api, + int innerLoopIterations, tangible.RefObject context, + BenchmarkBody loopBody, BenchmarkMeasure measure, + ArrayList expected) { + Stopwatch sw = new Stopwatch(); + double durationMs = 0; + long rowSize = 0; + + // Warm + int warm = Math.min(MicroBenchmarkSuiteBase.WarmCount, expected.size()); + for (int i = 0; i < warm; i++) { + for (int innerLoop = 0; innerLoop < innerLoopIterations; innerLoop++) { + loopBody.invoke(context, expected.get(i)); + } + } + + // Execute + System.gc(); + System.runFinalization(); + Thread.sleep(1000); + int gen0 = GC.CollectionCount(0); + int gen1 = GC.CollectionCount(1); + int gen2 = GC.CollectionCount(2); + long allocated = GC.GetAllocatedBytesForCurrentThread(); + int threadId = Thread.currentThread().ManagedThreadId; + ThreadPriority currentPriority = Thread.currentThread().Priority; + Thread.currentThread().Priority = ThreadPriority.Highest; + MemoryProfiler.CollectAllocations(true); + MemoryProfiler.GetSnapshot(); + try { + for (TValue tableValue : expected) { + sw.Restart(); + MicroBenchmarkSuiteBase.BenchmarkInnerLoop(innerLoopIterations, tableValue, context, loopBody); + sw.Stop(); + durationMs += sw.Elapsed.TotalMilliseconds; + rowSize += measure.invoke(context, tableValue); + } + } finally { + Thread.currentThread().Priority = currentPriority; + gen0 = GC.CollectionCount(0) - gen0; + gen1 = GC.CollectionCount(1) - gen1; + gen2 = GC.CollectionCount(2) - gen2; + allocated = GC.GetAllocatedBytesForCurrentThread() - allocated; + MemoryProfiler.GetSnapshot(); + MemoryProfiler.CollectAllocations(false); + } + + try (Measurements m = new Measurements(MicroBenchmarkSuiteBase.MetricsResultFile)) { + m.WriteMeasurement(model, operation, schema, api, expected.size(), innerLoopIterations, rowSize, + durationMs, threadId, gen0, gen1, gen2, allocated); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.NoInlining)] private static void BenchmarkInnerLoop(int + // innerLoopIterations, TValue tableValue, ref BenchmarkContext context, BenchmarkBody loopBody) + private static void BenchmarkInnerLoop(int innerLoopIterations, TValue tableValue, + tangible.RefObject context, + BenchmarkBody loopBody) { + for (int innerLoop = 0; innerLoop < innerLoopIterations; innerLoop++) { + loopBody.invoke(context, tableValue); + } + } + + @FunctionalInterface + public interface BenchmarkBody { + void invoke(tangible.RefObject context, TValue value); + } + + @FunctionalInterface + public interface BenchmarkMeasure { + long invoke(tangible.RefObject context, TValue value); + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: private protected ref struct BenchmarkContext + //C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# ref struct: + //C# TO JAVA CONVERTER WARNING: Java has no equivalent to C# 'private protected' access: + protected final static class BenchmarkContext { + public CodeGenRowGenerator CodeGenWriter = new CodeGenRowGenerator(); + public JsonModelRowGenerator JsonModelWriter = new JsonModelRowGenerator(); + public WriteRowGenerator PatchWriter = new WriteRowGenerator(); + public ProtobufRowGenerator ProtobufWriter = new ProtobufRowGenerator(); + public StreamingRowGenerator StreamingWriter = new StreamingRowGenerator(); + + public BenchmarkContext clone() { + BenchmarkContext varCopy = new BenchmarkContext(); + + varCopy.CodeGenWriter = this.CodeGenWriter.clone(); + varCopy.ProtobufWriter = this.ProtobufWriter.clone(); + varCopy.PatchWriter = this.PatchWriter.clone(); + varCopy.StreamingWriter = this.StreamingWriter.clone(); + varCopy.JsonModelWriter = this.JsonModelWriter.clone(); + + return varCopy; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/ProtobufRowGenerator.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/ProtobufRowGenerator.java new file mode 100644 index 0000000..4581a92 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/ProtobufRowGenerator.java @@ -0,0 +1,332 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import Google.Protobuf.*; +import Google.Protobuf.Collections.*; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.UUID; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable DontUseNamespaceAliases // Namespace Aliases should be avoided + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning restore DontUseNamespaceAliases // Namespace Aliases should be avoided + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: internal ref struct ProtobufRowGenerator +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# ref struct: +public final class ProtobufRowGenerator { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private ReadOnlySpan active; + private ReadOnlySpan active; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private readonly byte[] buffer; + private byte[] buffer; + private String schemaName; + + public ProtobufRowGenerator() { + } + + public ProtobufRowGenerator(String schemaName, int capacity) { + this.schemaName = schemaName; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.buffer = new byte[capacity]; + this.buffer = new byte[capacity]; + this.active = this.buffer; + } + + public int getLength() { + return this.active.Length; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public void ReadBuffer(byte[] buffer) + public void ReadBuffer(byte[] buffer) { + switch (this.schemaName) { + case "Hotels": + ProtobufRowGenerator.ReadBufferHotel(buffer); + break; + + case "Guests": + ProtobufRowGenerator.ReadBufferGuest(buffer); + break; + + case "Available_Rooms_By_Hotel_Date": + ProtobufRowGenerator.ReadBufferRoom(buffer); + break; + + default: + Contract.Fail(String.format("Unknown schema will be ignored: %1$s", this.schemaName)); + break; + } + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public byte[] ToArray() + public byte[] ToArray() { + return this.active.ToArray(); + } + + public void WriteBuffer(HashMap tableValue) { + switch (this.schemaName) { + case "Hotels": + this.WriteBufferHotel(tableValue); + break; + + case "Guests": + this.WriteBufferGuest(tableValue); + break; + + case "Available_Rooms_By_Hotel_Date": + this.WriteBufferRoom(tableValue); + break; + + default: + Contract.Fail(String.format("Unknown schema will be ignored: %1$s", this.schemaName)); + break; + } + } + + public ProtobufRowGenerator clone() { + ProtobufRowGenerator varCopy = new ProtobufRowGenerator(); + + varCopy.schemaName = this.schemaName; + varCopy.buffer = this.buffer; + varCopy.active = this.active; + + return varCopy; + } + + private static Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Address MakeAddress(HashMap tableValue) { + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Address address = new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Address(); + for ((Utf8String key,Object value) :tableValue) + { + switch (key.toString()) { + case "street": + address.setStreet(value == null ? null : ((Utf8String)value).toString()); + break; + + case "city": + address.setCity(value == null ? null : ((Utf8String)value).toString()); + break; + + case "state": + address.setState(value == null ? null : ((Utf8String)value).toString()); + break; + + case "postal_code": + address.setPostalCode(value == null ? null : ProtobufRowGenerator.MakePostalCode((HashMap)value)); + break; + + default: + Assert.Fail("should never happen"); + break; + } + } + + return address; + } + + private static Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.PostalCode MakePostalCode(HashMap tableValue) { + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.PostalCode postalCode = new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.PostalCode(); + for ((Utf8String key,Object value) :tableValue) + { + switch (key.toString()) { + case "zip": + postalCode.setZip((Integer)value); + break; + + case "plus4": + postalCode.setPlus4((Short)value); + break; + + default: + Assert.Fail("should never happen"); + break; + } + } + + return postalCode; + } + + private static void PopulateStringAddressMap(MapField field, + ArrayList list) { + for (Object item : list) { + ArrayList tuple = (ArrayList)item; + String key = ((Utf8String)tuple.get(0)).toString(); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Address value = + ProtobufRowGenerator.MakeAddress((HashMap)tuple.get(1)); + field.Add(key, value); + } + } + + private static void PopulateStringList(RepeatedField field, ArrayList list) { + for (Object item : list) { + field.Add(((Utf8String)item).toString()); + } + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private static void ReadBufferGuest(byte[] buffer) + private static void ReadBufferGuest(byte[] buffer) { + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Guests item = + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Guests(); + item.MergeFrom(buffer); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private static void ReadBufferHotel(byte[] buffer) + private static void ReadBufferHotel(byte[] buffer) { + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Hotels item = + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Hotels(); + item.MergeFrom(buffer); + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private static void ReadBufferRoom(byte[] buffer) + private static void ReadBufferRoom(byte[] buffer) { + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Available_Rooms_By_Hotel_Date item = new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Available_Rooms_By_Hotel_Date(); + item.MergeFrom(buffer); + } + + private void WriteBufferGuest(HashMap tableValue) { + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Guests room = + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Guests(); + try (CodedOutputStream stm = new CodedOutputStream(this.buffer)) { + for ((Utf8String key,Object value) :tableValue) + { + switch (key.toString()) { + case "guest_id": + room.setGuestId(value == null ? null : ((UUID)value).toString()); + break; + + case "first_name": + room.setFirstName(value == null ? null : ((Utf8String)value).toString()); + break; + + case "last_name": + room.setLastName(value == null ? null : ((Utf8String)value).toString()); + break; + + case "title": + room.setTitle(value == null ? null : ((Utf8String)value).toString()); + break; + + case "emails": + if (value != null) { + ProtobufRowGenerator.PopulateStringList(room.getEmails(), (ArrayList)value); + } + + break; + + case "phone_numbers": + if (value != null) { + ProtobufRowGenerator.PopulateStringList(room.getPhoneNumbers(), (ArrayList)value); + } + + break; + + case "addresses": + if (value != null) { + ProtobufRowGenerator.PopulateStringAddressMap(room.getAddresses(), + (ArrayList)value); + } + + break; + + case "confirm_number": + room.setConfirmNumber(value == null ? null : ((Utf8String)value).toString()); + break; + + default: + Assert.Fail("should never happen"); + break; + } + } + + room.WriteTo(stm); + stm.Flush(); + this.active = this.buffer.AsSpan(0, (int)stm.Position); + } + } + + private void WriteBufferHotel(HashMap tableValue) { + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Hotels room = + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Hotels(); + try (CodedOutputStream stm = new CodedOutputStream(this.buffer)) { + for ((Utf8String key,Object value) :tableValue) + { + switch (key.toString()) { + case "hotel_id": + room.setHotelId(value == null ? null : ((Utf8String)value).toString()); + break; + + case "name": + room.setName(value == null ? null : ((Utf8String)value).toString()); + break; + + case "phone": + room.setPhone(value == null ? null : ((Utf8String)value).toString()); + break; + + case "address": + room.setAddress(value == null ? null : ProtobufRowGenerator.MakeAddress((HashMap)value)); + break; + + default: + Assert.Fail("should never happen"); + break; + } + } + + room.WriteTo(stm); + stm.Flush(); + this.active = this.buffer.AsSpan(0, (int)stm.Position); + } + } + + private void WriteBufferRoom(HashMap tableValue) { + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Available_Rooms_By_Hotel_Date room = new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.CassandraHotel.Protobuf.Available_Rooms_By_Hotel_Date(); + try (CodedOutputStream stm = new CodedOutputStream(this.buffer)) { + for ((Utf8String key,Object value) :tableValue) + { + switch (key.toString()) { + case "hotel_id": + room.setHotelId(value == null ? null : ((Utf8String)value).toString()); + break; + + case "date": + room.setDate(value == null ? null : ((LocalDateTime)value).getTime()); + break; + + case "room_number": + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: room.RoomNumber = (Nullable)value; + room.setRoomNumber((Byte)value); + break; + + case "is_available": + room.setIsAvailable((Boolean)value); + break; + + default: + Assert.Fail("should never happen"); + break; + } + } + + room.WriteTo(stm); + stm.Flush(); + this.active = this.buffer.AsSpan(0, (int)stm.Position); + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/ReaderBenchmark.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/ReaderBenchmark.java new file mode 100644 index 0000000..52faf99 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/ReaderBenchmark.java @@ -0,0 +1,314 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.MemorySpanResizer; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; + +import java.io.Closeable; +import java.io.File; +import java.io.IOException; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][SuppressMessage("Microsoft.Reliability", "CA2001:Avoid calling problematic methods", +// Justification = "Perf Benchmark")][DeploymentItem("TestData\\*.hr", "TestData")] public sealed class ReaderBenchmark +public final class ReaderBenchmark { + private static final String CombinedScriptsData = "TestData\\CombinedScriptsData.hr"; + private static final int InitialCapacity = 2 * 1024 * 1024; + private static final int MeasureCount = 10; + private static final int WarmCount = 5; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][Ignore] public async Task AllAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][Ignore] public async Task AllAsync() + public Task AllAsync() { + final String dir = "E:\\TestData\\HybridRow"; + for (File childFile : (new File(dir)).EnumerateFiles("*.hr")) { + try (BenchmarkContext context = new BenchmarkContext(childFile.getPath(), false, false)) { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await ReaderBenchmark. + BenchmarkAsync(context, (object arg) -> ReaderBenchmark.RowReaderBenchmarkAsync(arg)); + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(ReaderBenchmark.CombinedScriptsData, "TestData")] + // public async Task RowReaderAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(ReaderBenchmark.CombinedScriptsData, "TestData")] + // public async Task RowReaderAsync() + public Task RowReaderAsync() { + try (BenchmarkContext context = new BenchmarkContext(ReaderBenchmark.CombinedScriptsData, true, true)) { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await ReaderBenchmark.BenchmarkAsync(context, (object arg) -> ReaderBenchmark.RowReaderBenchmarkAsync(arg)); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][Ignore] public async Task SpecificFileAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][Ignore] public async Task SpecificFileAsync() + public Task SpecificFileAsync() { + final String filename = "E:\\TestData\\HybridRow\\Lastfm.hr"; + try (BenchmarkContext context = new BenchmarkContext(filename, true, true)) { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await ReaderBenchmark.BenchmarkAsync(context, (object arg) -> ReaderBenchmark.RowReaderBenchmarkAsync(arg)); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Reliability", "CA2001:Avoid calling problematic methods", + // Justification = "Perf Benchmark")] private static async Task BenchmarkAsync(BenchmarkContext context, + // Func body) + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Reliability", "CA2001:Avoid calling problematic methods", + // Justification = "Perf Benchmark")] private static async Task BenchmarkAsync(BenchmarkContext context, + // Func body) + private static Task BenchmarkAsync(BenchmarkContext context, tangible.Func1Param body) { + try (SingleThreadedTaskScheduler scheduler = new SingleThreadedTaskScheduler()) { + // Warm + System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + for (int i = 0; i < ReaderBenchmark.WarmCount; i++) { + context.Reset(); + sw.Restart(); + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await Task. + Factory.StartNew(body, context, CancellationToken.None, TaskCreationOptions.None, scheduler).Unwrap(); + sw.Stop(); + if (context.getShowWarmSummary()) { + context.Summarize(sw.Elapsed); + } + } + + // Execute + double[] timing = new double[ReaderBenchmark.MeasureCount]; + for (int i = 0; i < ReaderBenchmark.MeasureCount; i++) { + System.gc(); + System.runFinalization(); + context.Reset(); + sw.Restart(); + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + await Task. + Factory.StartNew(body, context, CancellationToken.None, TaskCreationOptions.None, scheduler).Unwrap(); + sw.Stop(); + if (context.getShowSummary()) { + context.Summarize(sw.Elapsed); + } + + timing[i] = sw.Elapsed.TotalMilliseconds; + } + + Arrays.sort(timing); + System.out.println(String.format("File: %1$s, Mean: %1.4f", + Path.GetFileNameWithoutExtension(context.getInputFile()), timing[ReaderBenchmark.MeasureCount / 2])); + } + } + + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: private static async Task RowReaderBenchmarkAsync(object ctx) + private static Task RowReaderBenchmarkAsync(Object ctx) { + BenchmarkContext context = (BenchmarkContext)ctx; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MemorySpanResizer resizer = new MemorySpanResizer(ReaderBenchmark.InitialCapacity); + MemorySpanResizer resizer = new MemorySpanResizer(ReaderBenchmark.InitialCapacity); + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + Result r = await + Microsoft.Azure.Cosmos.Serialization.HybridRow.RecordIO.RecordIOStream.ReadRecordIOAsync(context.getInput(), + record -> + { + context.IncrementRecordCount(); + r = ReaderBenchmark.VisitOneRow(record, context.getResolver()); + assert Result.Success == r; + return Result.Success; + }, segment -> + { + Segment _; + tangible.OutObject tempOut__ = + new tangible.OutObject(); + r = SegmentSerializer.Read(segment.Span, context.getResolver(), tempOut__); + _ = tempOut__.argValue; + assert Result.Success == r; + + // TODO: do something with embedded schema. + return Result.Success; + }, resizer); + + assert Result.Success == r; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private static Result VisitOneRow(Memory buffer, LayoutResolver resolver) + private static Result VisitOneRow(Memory buffer, LayoutResolver resolver) { + RowBuffer row = new RowBuffer(buffer.Span, HybridRowVersion.V1, resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row); + row = tempRef_row.argValue; + return Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.RowReaderExtensions.VisitReader(reader.clone()); + } + + private final static class BenchmarkContext implements Closeable { + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.Stream is + // input or output: + private Stream input; + private String inputFile; + private long recordCount; + private LayoutResolver resolver; + private boolean showSummary; + private boolean showWarmSummary; + + + public BenchmarkContext(String inputFile, boolean showSummary) { + this(inputFile, showSummary, false); + } + + public BenchmarkContext(String inputFile) { + this(inputFile, true, false); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public BenchmarkContext(string inputFile, bool showSummary = true, bool showWarmSummary = + // false) + public BenchmarkContext(String inputFile, boolean showSummary, boolean showWarmSummary) { + this.inputFile = inputFile; + this.showSummary = showSummary; + this.showWarmSummary = showWarmSummary; + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.FileStream + // is input or output: + this.input = new FileStream(inputFile, FileMode.Open); + this.resolver = SystemSchema.LayoutResolver; + } + + // TODO: C# TO JAVA CONVERTER: C# to Java Converter cannot determine whether this System.IO.Stream is + // input or output: + public Stream getInput() { + return this.input; + } + + public String getInputFile() { + return this.inputFile; + } + + public LayoutResolver getResolver() { + return this.resolver; + } + + public boolean getShowSummary() { + return this.showSummary; + } + + public boolean getShowWarmSummary() { + return this.showWarmSummary; + } + + public void IncrementRecordCount() { + this.recordCount++; + } + + public void Reset() { + this.recordCount = 0; + this.input.Seek(0, SeekOrigin.Begin); + } + + public void Summarize(TimeSpan duration) { + System.out.print(String.format("Total Time: %0.4f, ", duration.TotalMilliseconds)); + System.out.println(String.format("Record Count: %1$s", this.recordCount)); + } + + public void close() throws IOException { + this.input.Dispose(); + } + } + + private final static class SingleThreadedTaskScheduler extends TaskScheduler implements Closeable { + private CancellationTokenSource cancel; + private EventWaitHandle ready; + private ConcurrentQueue tasks; + private Thread worker; + + // Creates a new instance with the specified degree of parallelism. + public SingleThreadedTaskScheduler() { + this.tasks = new ConcurrentQueue(); + this.ready = new ManualResetEvent(false); + this.worker = new Thread() { + void run() { + this.DoWork(); + } + }; + this.cancel = new CancellationTokenSource(); + this.worker.start(); + } + + // Gets the maximum concurrency level supported by this scheduler. + @Override + public int getMaximumConcurrencyLevel() { + return 1; + } + + public void close() throws IOException { + if (!this.cancel.IsCancellationRequested) { + this.cancel.Cancel(); + this.worker.join(); + this.ready == null ? null : this.ready.Dispose(); + this.cancel == null ? null : this.cancel.Dispose(); + } + } + + @Override + protected java.lang.Iterable GetScheduledTasks() { + return null; + } + + // Queues a task to the scheduler. + @Override + protected void QueueTask(Task task) { + synchronized (this.tasks) { + this.tasks.Enqueue(task); + if (Thread.currentThread() != this.worker) { + this.ready.Set(); + } + } + } + + @Override + protected boolean TryDequeue(Task task) { + return false; + } + + // Attempts to execute the specified task on the current thread. + @Override + protected boolean TryExecuteTaskInline(Task task, boolean taskWasPreviouslyQueued) { + // If this thread isn't already processing a task, we don't support inlining + if (Thread.currentThread() != this.worker) { + return false; + } + + // If the task was previously queued, then skip it. + if (taskWasPreviouslyQueued) { + return false; + } + + return this.TryExecuteTask(task); + } + + private void DoWork() { + while (!this.cancel.IsCancellationRequested) { + Task item; + tangible.OutObject tempOut_item = new tangible.OutObject(); + if (this.tasks.TryDequeue(tempOut_item)) { + item = tempOut_item.argValue; + this.TryExecuteTask(item); + } else { + item = tempOut_item.argValue; + this.ready.WaitOne(TimeSpan.FromSeconds(1)); + } + } + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/RowReaderExtensions.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/RowReaderExtensions.java new file mode 100644 index 0000000..f8df4ce --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/RowReaderExtensions.java @@ -0,0 +1,88 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; + +public final class RowReaderExtensions { + public static Result VisitReader(tangible.RefObject reader) { + while (reader.argValue.Read()) { + Utf8Span path = reader.argValue.getPathSpan(); + switch (reader.argValue.getType().LayoutCode) { + case Null: + case Boolean: + case Int8: + case Int16: + case Int32: + case Int64: + case UInt8: + case UInt16: + case UInt32: + case UInt64: + case VarInt: + case VarUInt: + case Float32: + case Float64: + case Float128: + case Decimal: + case DateTime: + case UnixDateTime: + case Guid: + case MongoDbObjectId: + case Utf8: + case Binary: + break; + + case NullableScope: + case ImmutableNullableScope: { + if (!reader.argValue.getHasValue()) { + break; + } + + // TODO: C# TO JAVA CONVERTER: There is no 'goto' in Java: + goto case LayoutCode.TypedTupleScope + } + + case ObjectScope: + case ImmutableObjectScope: + case Schema: + case ImmutableSchema: + case ArrayScope: + case ImmutableArrayScope: + case TypedArrayScope: + case ImmutableTypedArrayScope: + case TypedSetScope: + case ImmutableTypedSetScope: + case TypedMapScope: + case ImmutableTypedMapScope: + case TupleScope: + case ImmutableTupleScope: + case TypedTupleScope: + case ImmutableTypedTupleScope: + case TaggedScope: + case ImmutableTaggedScope: + case Tagged2Scope: + case ImmutableTagged2Scope: { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not converted by C# to Java Converter: + Result r = reader.argValue.ReadScope(null, (ref RowReader child, Object _) -> child.VisitReader()); + if (r != Result.Success) { + return r; + } + + break; + } + + default: { + Contract.Assert(false, String.format("Unknown type will be ignored: %1$s", reader.argValue.getType().LayoutCode)); + break; + } + } + } + + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/SchematizedMicroBenchmarkSuite.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/SchematizedMicroBenchmarkSuite.java new file mode 100644 index 0000000..1b495d0 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/SchematizedMicroBenchmarkSuite.java @@ -0,0 +1,639 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import MongoDB.Bson.IO.*; +import Newtonsoft.Json.*; +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; + +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.HashMap; +import java.util.List; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][DeploymentItem(TestData.SchemaFile, TestData.Target)] public sealed class +// SchematizedMicroBenchmarkSuite : MicroBenchmarkSuiteBase +public final class SchematizedMicroBenchmarkSuite extends MicroBenchmarkSuiteBase { + private static final JsonSerializerSettings JsonSettings = new JsonSerializerSettings + private String sdl; + + { + NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task BsonGuestsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task BsonGuestsReadBenchmarkAsync() + public Task BsonGuestsReadBenchmarkAsync() { + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.BsonReadBenchmark(resolver, "Guests", "Guests", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task BsonGuestsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task BsonGuestsWriteBenchmarkAsync() + public Task BsonGuestsWriteBenchmarkAsync() { + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.BsonWriteBenchmark(resolver, "Guests", "Guests", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task BsonHotelReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task BsonHotelReadBenchmarkAsync() + public Task BsonHotelReadBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.BsonReadBenchmark(resolver, "Hotels", "Hotels", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task BsonHotelWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task BsonHotelWriteBenchmarkAsync() + public Task BsonHotelWriteBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.BsonWriteBenchmark(resolver, "Hotels", "Hotels", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task BsonRoomsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task BsonRoomsReadBenchmarkAsync() + public Task BsonRoomsReadBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.BsonReadBenchmark(resolver, "Available_Rooms_By_Hotel_Date", "Rooms", 10000, + expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task BsonRoomsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task BsonRoomsWriteBenchmarkAsync() + public Task BsonRoomsWriteBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.BsonWriteBenchmark(resolver, "Available_Rooms_By_Hotel_Date", "Rooms", 10000, + expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task JsonGuestsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task JsonGuestsReadBenchmarkAsync() + public Task JsonGuestsReadBenchmarkAsync() { + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.JsonReadBenchmark("Guests", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task JsonGuestsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task JsonGuestsWriteBenchmarkAsync() + public Task JsonGuestsWriteBenchmarkAsync() { + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.JsonWriteBenchmark("Guests", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task JsonHotelReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task JsonHotelReadBenchmarkAsync() + public Task JsonHotelReadBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.JsonReadBenchmark("Hotels", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task JsonHotelWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task JsonHotelWriteBenchmarkAsync() + public Task JsonHotelWriteBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.JsonWriteBenchmark("Hotels", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task JsonRoomsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task JsonRoomsReadBenchmarkAsync() + public Task JsonRoomsReadBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.JsonReadBenchmark("Rooms", 10000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task JsonRoomsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task JsonRoomsWriteBenchmarkAsync() + public Task JsonRoomsWriteBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace _) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.JsonWriteBenchmark("Rooms", 10000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task LayoutGuestsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task LayoutGuestsReadBenchmarkAsync() + public Task LayoutGuestsReadBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + final int innerLoopIterations = 1; + //#else + final int innerLoopIterations = 1000; + //#endif + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.LayoutReadBenchmark(resolver, "Guests", "Guests", innerLoopIterations, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task LayoutGuestsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task LayoutGuestsWriteBenchmarkAsync() + public Task LayoutGuestsWriteBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + final int innerLoopIterations = 1; + //#else + final int innerLoopIterations = 1000; + //#endif + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.LayoutWriteBenchmark(resolver, "Guests", "Guests", innerLoopIterations, + expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task LayoutHotelReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task LayoutHotelReadBenchmarkAsync() + public Task LayoutHotelReadBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.LayoutReadBenchmark(resolver, "Hotels", "Hotels", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task LayoutHotelWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task LayoutHotelWriteBenchmarkAsync() + public Task LayoutHotelWriteBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.LayoutWriteBenchmark(resolver, "Hotels", "Hotels", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task LayoutRoomsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task LayoutRoomsReadBenchmarkAsync() + public Task LayoutRoomsReadBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.LayoutReadBenchmark(resolver, "Available_Rooms_By_Hotel_Date", "Rooms", 1000, + expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task LayoutRoomsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task LayoutRoomsWriteBenchmarkAsync() + public Task LayoutRoomsWriteBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.LayoutWriteBenchmark(resolver, "Available_Rooms_By_Hotel_Date", "Rooms", 1000, + expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public void ParseNamespaceExample() { + this.sdl = Files.readString(TestData.SchemaFile); + Namespace schema = Namespace.Parse(this.sdl); + this.DefaultResolver = new LayoutResolverNamespace(schema, SystemSchema.LayoutResolver); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task StreamingGuestsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task StreamingGuestsReadBenchmarkAsync() + public Task StreamingGuestsReadBenchmarkAsync() { + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.StreamingReadBenchmark(resolver, "Guests", "Guests", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task StreamingGuestsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.GuestsExpected, TestData.Target)] public + // async Task StreamingGuestsWriteBenchmarkAsync() + public Task StreamingGuestsWriteBenchmarkAsync() { + String expectedFile = TestData.GuestsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.StreamingWriteBenchmark(resolver, "Guests", "Guests", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task StreamingHotelReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task StreamingHotelReadBenchmarkAsync() + public Task StreamingHotelReadBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.StreamingReadBenchmark(resolver, "Hotels", "Hotels", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task StreamingHotelWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.HotelExpected, TestData.Target)] public + // async Task StreamingHotelWriteBenchmarkAsync() + public Task StreamingHotelWriteBenchmarkAsync() { + String expectedFile = TestData.HotelExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.StreamingWriteBenchmark(resolver, "Hotels", "Hotels", 1000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task StreamingRoomsReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task StreamingRoomsReadBenchmarkAsync() + public Task StreamingRoomsReadBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.StreamingReadBenchmark(resolver, "Available_Rooms_By_Hotel_Date", "Rooms", + 10000, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task StreamingRoomsWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.RoomsExpected, TestData.Target)] public + // async Task StreamingRoomsWriteBenchmarkAsync() + public Task StreamingRoomsWriteBenchmarkAsync() { + String expectedFile = TestData.RoomsExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + SchematizedMicroBenchmarkSuite.StreamingWriteBenchmark(resolver, "Available_Rooms_By_Hotel_Date", "Rooms", + 10000, expected); + } + + private static void BsonReadBenchmark(LayoutResolverNamespace resolver, String schemaName, String dataSetName, + int innerLoopIterations, ArrayList> expected) { + // Serialize input data to sequence of byte buffers. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: List expectedSerialized = new List(expected.Count); + ArrayList expectedSerialized = new ArrayList(expected.size()); + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = + schemaName.equals( > x.Name)).SchemaId) + try (BsonRowGenerator writer = new BsonRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, resolver)) { + for (HashMap tableValue : expected) { + writer.Reset(); + writer.WriteBuffer(tableValue); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: expectedSerialized.Add(writer.ToArray()); + expectedSerialized.add(writer.ToArray()); + } + } + + BenchmarkContext ignoredContext = null; + tangible.RefObject tempRef_ignoredContext = new tangible.RefObject(ignoredContext); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MicroBenchmarkSuiteBase.Benchmark("Schematized", "Read", dataSetName, "BSON", + // innerLoopIterations, ref ignoredContext, (ref BenchmarkContext _, byte[] tableValue) => + MicroBenchmarkSuiteBase.Benchmark("Schematized", "Read", dataSetName, "BSON", innerLoopIterations, + tempRef_ignoredContext, (ref BenchmarkContext _, byte[] tableValue) -> + { + try (MemoryStream stm = new MemoryStream(tableValue)) { + try (BsonBinaryReader bsonReader = new BsonBinaryReader(stm)) { + bsonReader.VisitBsonDocument(); + } + } + }, (ref BenchmarkContext _, byte[] tableValue) -> tableValue.length, expectedSerialized); + ignoredContext = tempRef_ignoredContext.argValue; + } + + private static void BsonWriteBenchmark(LayoutResolverNamespace resolver, String schemaName, String dataSetName, + int innerLoopIterations, ArrayList> expected) { + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = + schemaName.equals( > x.Name)).SchemaId) + try (BsonRowGenerator writer = new BsonRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, resolver)) { + BenchmarkContext ignoredContext = null; + + tangible.RefObject tempRef_ignoredContext = new tangible.RefObject(ignoredContext); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are + // not converted by C# to Java Converter: + MicroBenchmarkSuiteBase.Benchmark("Schematized", "Write", dataSetName, "BSON", innerLoopIterations, + tempRef_ignoredContext, (ref BenchmarkContext _, HashMap tableValue) -> + { + writer.Reset(); + writer.WriteBuffer(tableValue); + }, (ref BenchmarkContext _, HashMap tableValue) -> writer.getLength(), expected); + ignoredContext = tempRef_ignoredContext.argValue; + } + } + + private static void JsonReadBenchmark(String dataSetName, int innerLoopIterations, ArrayList> expected) { + // Serialize input data to sequence of byte buffers. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: List expectedSerialized = new List(expected.Count); + ArrayList expectedSerialized = new ArrayList(expected.size()); + Encoding utf8Encoding = new UTF8Encoding(); + JsonSerializer jsonSerializer = JsonSerializer.Create(SchematizedMicroBenchmarkSuite.JsonSettings); + try (MemoryStream jsonStream = new MemoryStream(BenchmarkSuiteBase.InitialCapacity)) { + try (OutputStreamWriter textWriter = new OutputStreamWriter(jsonStream)) { + try (JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)) { + jsonSerializer.Converters.Add(new Utf8StringJsonConverter()); + + for (HashMap tableValue : expected) { + jsonSerializer.Serialize(jsonWriter, tableValue); + jsonWriter.Flush(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: expectedSerialized.Add(jsonStream.ToArray()); + expectedSerialized.add((Byte)jsonStream.ToArray()); + jsonStream.SetLength(0); + } + } + } + } + + BenchmarkContext ignoredContext = null; + jsonSerializer.Converters.Add(new Utf8StringJsonConverter()); + + tangible.RefObject tempRef_ignoredContext = new tangible.RefObject(ignoredContext); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MicroBenchmarkSuiteBase.Benchmark("Schematized", "Read", dataSetName, "JSON", + // innerLoopIterations, ref ignoredContext, (ref BenchmarkContext _, byte[] tableValue) => + MicroBenchmarkSuiteBase.Benchmark("Schematized", "Read", dataSetName, "JSON", innerLoopIterations, + tempRef_ignoredContext, (ref BenchmarkContext _, byte[] tableValue) -> + { + try (MemoryStream jsonStream = new MemoryStream(tableValue)) { + try (InputStreamReader textReader = new InputStreamReader(jsonStream)) { + try (JsonTextReader jsonReader = new JsonTextReader(textReader)) { + while (jsonReader.Read()) { + // Just visit the entire structure without materializing any of the values. + } + } + } + } + }, (ref BenchmarkContext _, byte[] tableValue) -> tableValue.length, expectedSerialized); + ignoredContext = tempRef_ignoredContext.argValue; + } + + private static void JsonWriteBenchmark(String dataSetName, int innerLoopIterations, ArrayList> expected) { + Encoding utf8Encoding = new UTF8Encoding(); + JsonSerializer jsonSerializer = JsonSerializer.Create(SchematizedMicroBenchmarkSuite.JsonSettings); + try (MemoryStream jsonStream = new MemoryStream(BenchmarkSuiteBase.InitialCapacity)) { + try (OutputStreamWriter textWriter = new OutputStreamWriter(jsonStream)) { + try (JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)) { + BenchmarkContext ignoredContext = null; + jsonSerializer.Converters.Add(new Utf8StringJsonConverter()); + + tangible.RefObject tempRef_ignoredContext = new tangible.RefObject(ignoredContext); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - + // these are not converted by C# to Java Converter: + MicroBenchmarkSuiteBase.Benchmark("Schematized", "Write", dataSetName, "JSON", + innerLoopIterations, tempRef_ignoredContext, (ref BenchmarkContext _, HashMap tableValue) -> + { + jsonStream.SetLength(0); + jsonSerializer.Serialize(jsonWriter, tableValue); + jsonWriter.Flush(); + }, (ref BenchmarkContext _, HashMap value) -> jsonStream.Length, expected); + ignoredContext = tempRef_ignoredContext.argValue; + } + } + } + } + + private static void LayoutReadBenchmark(LayoutResolverNamespace resolver, String schemaName, String dataSetName, + int innerLoopIterations, ArrayList> expected) { + // Serialize input data to sequence of byte buffers. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: List expectedSerialized = new List(expected.Count); + ArrayList expectedSerialized = new ArrayList(expected.size()); + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = + schemaName.equals( > x.Name)).SchemaId) + BenchmarkContext context = new BenchmarkContext(); + context.StreamingWriter = new StreamingRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, resolver); + + for (HashMap tableValue : expected) { + context.StreamingWriter.Reset(); + + Result r = context.StreamingWriter.WriteBuffer(tableValue); + ResultAssert.IsSuccess(r); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: expectedSerialized.Add(context.StreamingWriter.ToArray()); + expectedSerialized.add((Byte)context.StreamingWriter.ToArray()); + } + + tangible.RefObject tempRef_context = new tangible.RefObject(context); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MicroBenchmarkSuiteBase.Benchmark("Schematized", "Read", dataSetName, "Layout", + // innerLoopIterations, ref context, (ref BenchmarkContext ctx, byte[] tableValue) => + MicroBenchmarkSuiteBase.Benchmark("Schematized", "Read", dataSetName, "Layout", innerLoopIterations, + tempRef_context, (ref BenchmarkContext ctx, byte[] tableValue) -> + { + VisitRowGenerator visitor = new VisitRowGenerator(tableValue.AsSpan(), resolver); + Result r = visitor.DispatchLayout(layout); + ResultAssert.IsSuccess(r); + }, (ref BenchmarkContext ctx, byte[] tableValue) -> tableValue.length, expectedSerialized); + context = tempRef_context.argValue; + } + + private static void LayoutWriteBenchmark(LayoutResolverNamespace resolver, String schemaName, String dataSetName, + int innerLoopIterations, ArrayList> expected) { + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = + schemaName.equals( > x.Name)).SchemaId) + BenchmarkContext context = new BenchmarkContext(); + context.PatchWriter = new WriteRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, resolver); + + tangible.RefObject tempRef_context = new tangible.RefObject(context); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + MicroBenchmarkSuiteBase.Benchmark("Schematized", "Write", dataSetName, "Layout", innerLoopIterations, + tempRef_context, (ref BenchmarkContext ctx, HashMap dict) -> + { + ctx.PatchWriter.Reset(); + Result r = ctx.PatchWriter.DispatchLayout(layout, dict); + ResultAssert.IsSuccess(r); + }, (ref BenchmarkContext ctx, HashMap _) -> ctx.PatchWriter.Length, expected); + context = tempRef_context.argValue; + } + + private static void StreamingReadBenchmark(LayoutResolverNamespace resolver, String schemaName, String dataSetName, int innerLoopIterations, ArrayList> expected) { + // Serialize input data to sequence of byte buffers. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: List expectedSerialized = new List(expected.Count); + ArrayList expectedSerialized = new ArrayList(expected.size()); + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = schemaName.equals( > x.Name)).SchemaId) + BenchmarkContext context = new BenchmarkContext(); + context.StreamingWriter = new StreamingRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, resolver); + + for (HashMap tableValue : expected) { + context.StreamingWriter.Reset(); + + Result r = context.StreamingWriter.WriteBuffer(tableValue); + ResultAssert.IsSuccess(r); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: expectedSerialized.Add(context.StreamingWriter.ToArray()); + expectedSerialized.add((Byte)context.StreamingWriter.ToArray()); + } + + tangible.RefObject tempRef_context = new tangible.RefObject(context); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MicroBenchmarkSuiteBase.Benchmark("Schematized", "Read", dataSetName, "HybridRow", innerLoopIterations, ref context, (ref BenchmarkContext ctx, byte[] tableValue) => + MicroBenchmarkSuiteBase.Benchmark("Schematized", "Read", dataSetName, "HybridRow", innerLoopIterations, tempRef_context, (ref BenchmarkContext ctx, byte[] tableValue) -> + { + RowBuffer row = new RowBuffer(tableValue.AsSpan(), HybridRowVersion.V1, resolver); + tangible.RefObject tempRef_row = new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row); + row = tempRef_row.argValue; + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.RowReaderExtensions.VisitReader(reader.clone()); + }, (ref BenchmarkContext ctx, byte[] tableValue) -> tableValue.length, expectedSerialized); + context = tempRef_context.argValue; + } + + private static void StreamingWriteBenchmark(LayoutResolverNamespace resolver, String schemaName, + String dataSetName, int innerLoopIterations, + ArrayList> expected) { + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = + schemaName.equals( > x.Name)).SchemaId) + BenchmarkContext context = new BenchmarkContext(); + context.StreamingWriter = new StreamingRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, resolver); + + tangible.RefObject tempRef_context = new tangible.RefObject(context); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + MicroBenchmarkSuiteBase.Benchmark("Schematized", "Write", dataSetName, "HybridRow", innerLoopIterations, + tempRef_context, (ref BenchmarkContext ctx, HashMap tableValue) -> + { + ctx.StreamingWriter.Reset(); + + Result r = ctx.StreamingWriter.WriteBuffer(tableValue); + ResultAssert.IsSuccess(r); + }, (ref BenchmarkContext ctx, HashMap _) -> ctx.StreamingWriter.Length, expected); + context = tempRef_context.argValue; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/TestData.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/TestData.java new file mode 100644 index 0000000..79ff704 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/TestData.java @@ -0,0 +1,20 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +/** + * Names of assets in the TestData folder. + */ +public class TestData { + public static final String GuestsExpected = "TestData\\GuestsSchemaExpected.hr"; + public static final String HotelExpected = "TestData\\HotelSchemaExpected.hr"; + public static final String Messages1KExpected = "TestData\\Messages1KExpected.hr"; + public static final String RoomsExpected = "TestData\\RoomsSchemaExpected.hr"; + public static final String SchemaFile = "TestData\\CassandraHotelSchema.json"; + /** + * The folder to which TestData assets should be copied during deployment. + */ + public static final String Target = "TestData"; +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/UnschematizedMicroBenchmarkSuite.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/UnschematizedMicroBenchmarkSuite.java new file mode 100644 index 0000000..4365fb4 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/perf/UnschematizedMicroBenchmarkSuite.java @@ -0,0 +1,341 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.perf; + +import MongoDB.Bson.IO.*; +import Newtonsoft.Json.*; +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; + +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.HashMap; +import java.util.List; + +/** + * Tests involving fully (or mostly) unschematized test data. + */ +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass] public sealed class UnschematizedMicroBenchmarkSuite : MicroBenchmarkSuiteBase +public final class UnschematizedMicroBenchmarkSuite extends MicroBenchmarkSuiteBase { + private static final JsonSerializerSettings JsonSettings = new JsonSerializerSettings + + { + NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task BsonMessages1KReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task BsonMessages1KReadBenchmarkAsync() + public Task BsonMessages1KReadBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + final int innerLoopIterations = 1; + //#else + final int innerLoopIterations = 10; + //#endif + String expectedFile = TestData.Messages1KExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + UnschematizedMicroBenchmarkSuite.BsonReadBenchmark("Messages1K", innerLoopIterations, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task BsonMessages1KWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task BsonMessages1KWriteBenchmarkAsync() + public Task BsonMessages1KWriteBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + final int innerLoopIterations = 1; + //#else + final int innerLoopIterations = 10; + //#endif + String expectedFile = TestData.Messages1KExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + UnschematizedMicroBenchmarkSuite.BsonWriteBenchmark("Messages1K", innerLoopIterations, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task JsonMessages1KReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task JsonMessages1KReadBenchmarkAsync() + public Task JsonMessages1KReadBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + final int innerLoopIterations = 1; + //#else + final int innerLoopIterations = 10; + //#endif + String expectedFile = TestData.Messages1KExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + UnschematizedMicroBenchmarkSuite.JsonReadBenchmark("Messages1K", innerLoopIterations, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task JsonMessages1KWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task JsonMessages1KWriteBenchmarkAsync() + public Task JsonMessages1KWriteBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + final int innerLoopIterations = 1; + //#else + final int innerLoopIterations = 10; + //#endif + String expectedFile = TestData.Messages1KExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + UnschematizedMicroBenchmarkSuite.JsonWriteBenchmark("Messages1K", innerLoopIterations, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task Messages1KReadBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task Messages1KReadBenchmarkAsync() + public Task Messages1KReadBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + final int innerLoopIterations = 1; + //#else + final int innerLoopIterations = 10; + //#endif + String expectedFile = TestData.Messages1KExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + UnschematizedMicroBenchmarkSuite.JsonModelReadBenchmark(resolver, "TypedJsonHybridRowSchema", "Messages1K", + innerLoopIterations, expected); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task Messages1KWriteBenchmarkAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem(TestData.Messages1KExpected, TestData.Target)] + // public async Task Messages1KWriteBenchmarkAsync() + public Task Messages1KWriteBenchmarkAsync() { + // TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: + //#if DEBUG + final int innerLoopIterations = 1; + //#else + final int innerLoopIterations = 10; + //#endif + String expectedFile = TestData.Messages1KExpected; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + (List < Dictionary < Utf8String, object >> expected, LayoutResolverNamespace resolver) =await + this.LoadExpectedAsync(expectedFile); + UnschematizedMicroBenchmarkSuite.JsonModelWriteBenchmark(resolver, "TypedJsonHybridRowSchema", "Messages1K", + innerLoopIterations, expected); + } + + private static void BsonReadBenchmark(String dataSetName, int innerLoopIterations, ArrayList> expected) { + // Serialize input data to sequence of byte buffers. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: List expectedSerialized = new List(expected.Count); + ArrayList expectedSerialized = new ArrayList(expected.size()); + try (BsonJsonModelRowGenerator writer = new BsonJsonModelRowGenerator(BenchmarkSuiteBase.InitialCapacity)) { + for (HashMap tableValue : expected) { + writer.Reset(); + writer.WriteBuffer(tableValue); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: expectedSerialized.Add(writer.ToArray()); + expectedSerialized.add(writer.ToArray()); + } + } + + BenchmarkContext ignoredContext = null; + tangible.RefObject tempRef_ignoredContext = new tangible.RefObject(ignoredContext); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MicroBenchmarkSuiteBase.Benchmark("Unschematized", "Read", dataSetName, "BSON", innerLoopIterations, ref ignoredContext, (ref BenchmarkContext _, byte[] tableValue) => + MicroBenchmarkSuiteBase.Benchmark("Unschematized", "Read", dataSetName, "BSON", innerLoopIterations, tempRef_ignoredContext, (ref BenchmarkContext _, byte[] tableValue) -> + { + try (MemoryStream stm = new MemoryStream(tableValue)) { + try (BsonBinaryReader bsonReader = new BsonBinaryReader(stm)) { + bsonReader.VisitBsonDocument(); + } + } + }, (ref BenchmarkContext _, byte[] tableValue) -> tableValue.length, expectedSerialized); + ignoredContext = tempRef_ignoredContext.argValue; + } + + private static void BsonWriteBenchmark(String dataSetName, int innerLoopIterations, ArrayList> expected) { + try (BsonJsonModelRowGenerator writer = new BsonJsonModelRowGenerator(BenchmarkSuiteBase.InitialCapacity)) { + BenchmarkContext ignoredContext = null; + + tangible.RefObject tempRef_ignoredContext = new tangible.RefObject(ignoredContext); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are + // not converted by C# to Java Converter: + MicroBenchmarkSuiteBase.Benchmark("Unschematized", "Write", dataSetName, "BSON", innerLoopIterations, + tempRef_ignoredContext, (ref BenchmarkContext _, HashMap tableValue) -> + { + writer.Reset(); + writer.WriteBuffer(tableValue); + }, (ref BenchmarkContext _, HashMap tableValue) -> writer.getLength(), expected); + ignoredContext = tempRef_ignoredContext.argValue; + } + } + + private static void JsonModelReadBenchmark(LayoutResolverNamespace resolver, String schemaName, + String dataSetName, int innerLoopIterations, + ArrayList> expected) { + // Serialize input data to sequence of byte buffers. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: List expectedSerialized = new List(expected.Count); + ArrayList expectedSerialized = new ArrayList(expected.size()); + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = + schemaName.equals( > x.Name)).SchemaId) + BenchmarkContext context = new BenchmarkContext(); + context.JsonModelWriter = new JsonModelRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, resolver); + + for (HashMap tableValue : expected) { + context.JsonModelWriter.Reset(); + + Result r = context.JsonModelWriter.WriteBuffer(tableValue); + ResultAssert.IsSuccess(r); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: expectedSerialized.Add(context.JsonModelWriter.ToArray()); + expectedSerialized.add(context.JsonModelWriter.ToArray()); + } + + tangible.RefObject tempRef_context = new tangible.RefObject(context); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MicroBenchmarkSuiteBase.Benchmark("Unschematized", "Read", dataSetName, "HybridRowSparse", + // innerLoopIterations, ref context, (ref BenchmarkContext ctx, byte[] tableValue) => + MicroBenchmarkSuiteBase.Benchmark("Unschematized", "Read", dataSetName, "HybridRowSparse", + innerLoopIterations, tempRef_context, (ref BenchmarkContext ctx, byte[] tableValue) -> + { + RowBuffer row = new RowBuffer(tableValue.AsSpan(), HybridRowVersion.V1, resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row); + row = tempRef_row.argValue; + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Perf.RowReaderExtensions.VisitReader(reader.clone()); + }, (ref BenchmarkContext ctx, byte[] tableValue) -> tableValue.length, expectedSerialized); + context = tempRef_context.argValue; + } + + private static void JsonModelWriteBenchmark(LayoutResolverNamespace resolver, String schemaName, + String dataSetName, int innerLoopIterations, + ArrayList> expected) { + Layout layout = resolver.Resolve(tangible.ListHelper.find(resolver.getNamespace().getSchemas(), x = + schemaName.equals( > x.Name)).SchemaId) + BenchmarkContext context = new BenchmarkContext(); + context.JsonModelWriter = new JsonModelRowGenerator(BenchmarkSuiteBase.InitialCapacity, layout, resolver); + + tangible.RefObject tempRef_context = new tangible.RefObject(context); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + MicroBenchmarkSuiteBase.Benchmark("Unschematized", "Write", dataSetName, "HybridRowSparse", + innerLoopIterations, tempRef_context, (ref BenchmarkContext ctx, HashMap tableValue) -> + { + ctx.JsonModelWriter.Reset(); + + Result r = ctx.JsonModelWriter.WriteBuffer(tableValue); + ResultAssert.IsSuccess(r); + }, (ref BenchmarkContext ctx, HashMap tableValue) -> ctx.JsonModelWriter.Length, expected); + context = tempRef_context.argValue; + } + + private static void JsonReadBenchmark(String dataSetName, int innerLoopIterations, ArrayList> expected) { + // Serialize input data to sequence of byte buffers. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: List expectedSerialized = new List(expected.Count); + ArrayList expectedSerialized = new ArrayList(expected.size()); + Encoding utf8Encoding = new UTF8Encoding(); + JsonSerializer jsonSerializer = JsonSerializer.Create(UnschematizedMicroBenchmarkSuite.JsonSettings); + try (MemoryStream jsonStream = new MemoryStream(BenchmarkSuiteBase.InitialCapacity)) { + try (OutputStreamWriter textWriter = new OutputStreamWriter(jsonStream)) { + try (JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)) { + jsonSerializer.Converters.Add(new Utf8StringJsonConverter()); + + for (HashMap tableValue : expected) { + jsonSerializer.Serialize(jsonWriter, tableValue); + jsonWriter.Flush(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: expectedSerialized.Add(jsonStream.ToArray()); + expectedSerialized.add((Byte)jsonStream.ToArray()); + jsonStream.SetLength(0); + } + } + } + } + + BenchmarkContext ignoredContext = null; + jsonSerializer.Converters.Add(new Utf8StringJsonConverter()); + + tangible.RefObject tempRef_ignoredContext = new tangible.RefObject(ignoredContext); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MicroBenchmarkSuiteBase.Benchmark("Unschematized", "Read", dataSetName, "JSON", + // innerLoopIterations, ref ignoredContext, (ref BenchmarkContext _, byte[] tableValue) => + MicroBenchmarkSuiteBase.Benchmark("Unschematized", "Read", dataSetName, "JSON", innerLoopIterations, + tempRef_ignoredContext, (ref BenchmarkContext _, byte[] tableValue) -> + { + try (MemoryStream jsonStream = new MemoryStream(tableValue)) { + try (InputStreamReader textReader = new InputStreamReader(jsonStream)) { + try (JsonTextReader jsonReader = new JsonTextReader(textReader)) { + while (jsonReader.Read()) { + // Just visit the entire structure without materializing any of the values. + } + } + } + } + }, (ref BenchmarkContext _, byte[] tableValue) -> tableValue.length, expectedSerialized); + ignoredContext = tempRef_ignoredContext.argValue; + } + + private static void JsonWriteBenchmark(String dataSetName, int innerLoopIterations, ArrayList> expected) { + Encoding utf8Encoding = new UTF8Encoding(); + JsonSerializer jsonSerializer = JsonSerializer.Create(UnschematizedMicroBenchmarkSuite.JsonSettings); + try (MemoryStream jsonStream = new MemoryStream(BenchmarkSuiteBase.InitialCapacity)) { + try (OutputStreamWriter textWriter = new OutputStreamWriter(jsonStream)) { + try (JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)) { + BenchmarkContext ignoredContext = null; + jsonSerializer.Converters.Add(new Utf8StringJsonConverter()); + + tangible.RefObject tempRef_ignoredContext = new tangible.RefObject(ignoredContext); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - + // these are not converted by C# to Java Converter: + MicroBenchmarkSuiteBase.Benchmark("Unschematized", "Write", dataSetName, "JSON", + innerLoopIterations, tempRef_ignoredContext, (ref BenchmarkContext _, HashMap tableValue) -> + { + jsonStream.SetLength(0); + jsonSerializer.Serialize(jsonWriter, tableValue); + jsonWriter.Flush(); + }, (ref BenchmarkContext _, HashMap value) -> jsonStream.Length, expected); + ignoredContext = tempRef_ignoredContext.argValue; + } + } + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ArrayAssert.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ArrayAssert.java new file mode 100644 index 0000000..d20711e --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ArrayAssert.java @@ -0,0 +1,46 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +public final class ArrayAssert { + public static void AreEqual(T[] expected, T[] actual) { + if (expected == null) { + assert actual == null; + return; + } + + assert actual != null; + assert expected.length == actual.length; + for (int i = 0; i < expected.length; i++) { + assert expected[i] == actual[i]; + } + } + + public static void AreEqual(T[] expected, T[] actual, String message) { + if (expected == null) { + Assert.IsNull(actual, message); + return; + } + + Assert.IsNotNull(actual, message); + Assert.AreEqual(expected.length, actual.length, message); + for (int i = 0; i < expected.length; i++) { + Assert.AreEqual(expected[i], actual[i], message); + } + } + + public static void AreEqual(T[] expected, T[] actual, String message, Object... parameters) { + if (expected == null) { + Assert.IsNull(actual, message, parameters); + return; + } + + Assert.IsNotNull(actual, message, parameters); + Assert.AreEqual(expected.length, actual.length, message, parameters); + for (int i = 0; i < expected.length; i++) { + Assert.AreEqual(expected[i], actual[i], message, parameters); + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/AssertThrowsException.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/AssertThrowsException.java new file mode 100644 index 0000000..536f687 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/AssertThrowsException.java @@ -0,0 +1,111 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +public final class AssertThrowsException { + /** + * Safely converts an object to a string, handling null values and null characters. Null + * values are converted to "(null)". Null characters are converted to "\\0". + * + * @param input The object to convert to a string. + * @return The converted string. + */ + public static String ReplaceNulls(Object input) { + String input1 = input == null ? null : input.toString(); + if (input1 == null) { + return "(null)"; + } + + return Assert.ReplaceNullChars(input1); + } + + /** + * Tests whether the code specified by delegate throws exact given + * exception of type (and not of derived type) and throws + * AssertFailedException + * if code does not throws exception or throws exception of type other than + * . + * + * @param action Delegate to code to be tested and which is expected to throw exception. + * @param message The message to include in the exception when does + * not throws exception of type . + * + * Type of exception expected to be thrown. + * @return The exception that was thrown. + * @throws T:Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException Thrown if + * does + * not throws exception of type + * . + */ + public static T ThrowsException(tangible.Action0Param action, String message) { + return AssertThrowsException.ThrowsException(action, message, null); + } + + /** + * Tests whether the code specified by delegate throws exact given + * exception of type (and not of derived type) and throws + * AssertFailedException + * if code does not throws exception or throws exception of type other than + * . + * + * @param action Delegate to code to be tested and which is expected to throw exception. + * @param message The message to include in the exception when does + * not throws exception of type . + * @param parameters An array of parameters to use when formatting . + * Type of exception expected to be thrown. + * @return The exception that was thrown. + * @throws T:Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException Thrown if + * does + * not throws exception of type + * . + */ + public static T ThrowsException(tangible.Action0Param action, String message, + Object... parameters) { + if (action == null) { + throw new NullPointerException("action"); + } + + if (message == null) { + throw new NullPointerException("message"); + } + + try { + action.invoke(); + } catch (RuntimeException ex) { + if (T.class != ex.getClass()) { + Assert.Fail(String.format("Threw exception %3$s, but exception %2$s was expected. %1$s\nException " + + "Message: %4$s\nStack Trace: %5$s", AssertThrowsException.ReplaceNulls(message), + (Object)T.class.Name, ex.getClass().getSimpleName(), ex.getMessage(), + (Object)ex.StackTrace), parameters); + } + + return (T)ex; + } + + Assert.Fail(String.format("No exception thrown. %2$s exception was expected. %1$s", + AssertThrowsException.ReplaceNulls(message), T.class.Name), parameters); + + return null; + } + + /** + * Tests whether the code specified by delegate throws exact given + * exception of type (and not of derived type) and throws + * AssertFailedException + * if code does not throws exception or throws exception of type other than + * . + * + * @param action Delegate to code to be tested and which is expected to throw exception. + * Type of exception expected to be thrown. + * @return The exception that was thrown. + * @throws T:Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException Thrown if + * does + * not throws exception of type + * . + */ + public static T ThrowsException(tangible.Action0Param action) { + return AssertThrowsException.ThrowsException(action, "", null); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/CrossVersioningUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/CrossVersioningUnitTests.java new file mode 100644 index 0000000..6d4adcd --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/CrossVersioningUnitTests.java @@ -0,0 +1,614 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import Newtonsoft.Json.*; +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.NullValue; +import azure.data.cosmos.serialization.hybridrow.RowCursor; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; + +import java.nio.file.Files; +import java.time.LocalDateTime; +import java.util.UUID; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Public Fields + + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][SuppressMessage("Naming", "DontUseVarForVariableTypes", Justification = "The types here +// are anonymous.")][DeploymentItem(CrossVersioningUnitTests.SchemaFile, "TestData")][DeploymentItem +// (CrossVersioningUnitTests.ExpectedFile, "TestData")] public sealed class CrossVersioningUnitTests +public final class CrossVersioningUnitTests { + private static final String ExpectedFile = "TestData\\CrossVersioningExpected.json"; + private static final LocalDateTime SampleDateTime = LocalDateTime.parse("2018-08-14 02:05:00.0000000"); + private static final Float128 SampleFloat128 = new Float128(0, 42); + private static final UUID SampleGuid = UUID.fromString("{2A9C25B9-922E-4611-BB0A-244A9496503C}"); + private static final MongoDbObjectId SampleMongoDbObjectId = new MongoDbObjectId(704643072, 0); // 42 in big-endian + private static final UnixDateTime SampleUnixDateTime = new UnixDateTime(42); + private static final String SchemaFile = "TestData\\CrossVersioningSchema.json"; + private Expected expected; + private LayoutResolver resolver; + private Namespace schema; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][SuppressMessage("StyleCop.CSharp.ReadabilityRules", + // "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Test code.")] public void CrossVersionDeleteSparse() + public void CrossVersionDeleteSparse() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Sparse")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.ReadFrom(this.resolver, + this.expected.getCrossVersionSparse()); + d.LayoutCodeSwitch("null"); + d.LayoutCodeSwitch("bool", value:true) + d.LayoutCodeSwitch("int8", value:(byte)-86) + d.LayoutCodeSwitch("int16", value:(short)-21846) + d.LayoutCodeSwitch("int32", value:-1431655766) + d.LayoutCodeSwitch("int64", value:-6148914691236517206L) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint8", value: (byte)0xAA); + d.LayoutCodeSwitch("uint8", value:(byte)0xAA) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint16", value: (ushort)0xAAAA); + d.LayoutCodeSwitch("uint16", value:(short)0xAAAA) + d.LayoutCodeSwitch("uint32", value:0xAAAAAAAA) + d.LayoutCodeSwitch("uint64", value:0xAAAAAAAAAAAAAAAAL) + d.LayoutCodeSwitch("float32", value:1.0F / 3.0F) + d.LayoutCodeSwitch("float64", value:1.0 / 3.0) + d.LayoutCodeSwitch("float128", value:CrossVersioningUnitTests.SampleFloat128) + d.LayoutCodeSwitch("decimal", value:java.math.BigDecimal.ONE / 3.0) + d.LayoutCodeSwitch("datetime", value:CrossVersioningUnitTests.SampleDateTime) + d.LayoutCodeSwitch("unixdatetime", value:CrossVersioningUnitTests.SampleUnixDateTime) + d.LayoutCodeSwitch("guid", value:CrossVersioningUnitTests.SampleGuid) + d.LayoutCodeSwitch("mongodbobjectid", value:CrossVersioningUnitTests.SampleMongoDbObjectId) + d.LayoutCodeSwitch("utf8", value:"abc") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("binary", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("binary", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + d.LayoutCodeSwitch("array_t", value:new byte[] { -86, -86, -86 }) + d.LayoutCodeSwitch("array_t>", value:new float[][] + { + new float[] { 1, 2, 3 }, + new float[] { 1, 2, 3 } + }) + d.LayoutCodeSwitch("array_t", value:new String[] { "abc", "def", "hij" }) + d.LayoutCodeSwitch("tuple", value:Tuple.Create(-6148914691236517206L, -6148914691236517206L)) + d.LayoutCodeSwitch("tuple>", value: + Tuple.Create(NullValue.Default, Tuple.Create((byte)-86, (byte)-86))) + d.LayoutCodeSwitch("tuple", value:Tuple.Create(false, new Point(1, 2))) + d.LayoutCodeSwitch("set_t", value:new String[] { "abc", "efg", "xzy" }) + d.LayoutCodeSwitch("set_t>", value:new byte[][] + { + new byte[] { 1, 2, 3 }, + new byte[] { 4, 5, 6 }, + new byte[] { 7, 8, 9 } + }) + d.LayoutCodeSwitch("set_t>", value:new int[][] + { + new int[] { 1, 2, 3 }, + new int[] { 4, 5, 6 }, + new int[] { 7, 8, 9 } + }) + d.LayoutCodeSwitch("set_t", value:new Point[] + { + new Point(1, 2), + new Point(3, 4), + new Point(5, 6) + }) + d.LayoutCodeSwitch("map_t", value: + new System.Tuple[] { Tuple.Create("Mark", "Luke"), Tuple.Create("Harrison", "Han") }) + d.LayoutCodeSwitch("map_t>", value: + new System.Tuple[] { Tuple.Create((byte)1, new byte[] { 1, 2, 3 }), Tuple.Create((byte)2, + new byte[] { 4, 5, 6 }) }) + + d.LayoutCodeSwitch("map_t>", value: + new System.Tuple[] { Tuple.Create((short)1, new System.Tuple[] { Tuple.Create(1, 2), + Tuple.Create(3, 4) }), Tuple.Create((short)2, new System.Tuple[] { Tuple.Create(5, 6), + Tuple.Create(7, 8) }) }) + + d.LayoutCodeSwitch("map_t", value: + new System.Tuple[] { Tuple.Create(1.0, new Point(1, 2)), Tuple.Create(2.0, new Point(3, 4)), + Tuple.Create(3.0, new Point(5, 6)) }) + + assert this.expected.getCrossVersionNullSparse() == d.RowToHex(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CrossVersionReadFixed() + public void CrossVersionReadFixed() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Fixed")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.ReadFrom(this.resolver, + this.expected.getCrossVersionFixed()); + d.LayoutCodeSwitch("null"); + d.LayoutCodeSwitch("bool", value:true) + d.LayoutCodeSwitch("int8", value:(byte)-86) + d.LayoutCodeSwitch("int16", value:(short)-21846) + d.LayoutCodeSwitch("int32", value:-1431655766) + d.LayoutCodeSwitch("int64", value:-6148914691236517206L) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint8", value: (byte)0xAA); + d.LayoutCodeSwitch("uint8", value:(byte)0xAA) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint16", value: (ushort)0xAAAA); + d.LayoutCodeSwitch("uint16", value:(short)0xAAAA) + d.LayoutCodeSwitch("uint32", value:0xAAAAAAAA) + d.LayoutCodeSwitch("uint64", value:0xAAAAAAAAAAAAAAAAL) + d.LayoutCodeSwitch("float32", value:1.0F / 3.0F) + d.LayoutCodeSwitch("float64", value:1.0 / 3.0) + d.LayoutCodeSwitch("float128", value:CrossVersioningUnitTests.SampleFloat128) + d.LayoutCodeSwitch("decimal", value:java.math.BigDecimal.ONE / 3.0) + d.LayoutCodeSwitch("datetime", value:CrossVersioningUnitTests.SampleDateTime) + d.LayoutCodeSwitch("unixdatetime", value:CrossVersioningUnitTests.SampleUnixDateTime) + d.LayoutCodeSwitch("guid", value:CrossVersioningUnitTests.SampleGuid) + d.LayoutCodeSwitch("mongodbobjectid", value:CrossVersioningUnitTests.SampleMongoDbObjectId) + d.LayoutCodeSwitch("utf8", value:"abc") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("binary", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("binary", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CrossVersionReadNullFixed() + public void CrossVersionReadNullFixed() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Fixed")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.Create(layout, this.resolver); + d.LayoutCodeSwitch("null"); + d.LayoutCodeSwitch("bool"); + d.LayoutCodeSwitch("int8"); + d.LayoutCodeSwitch("int16"); + d.LayoutCodeSwitch("int32"); + d.LayoutCodeSwitch("int64"); + d.LayoutCodeSwitch("uint8"); + d.LayoutCodeSwitch("uint16"); + d.LayoutCodeSwitch("uint32"); + d.LayoutCodeSwitch("uint64"); + d.LayoutCodeSwitch("float32"); + d.LayoutCodeSwitch("float64"); + d.LayoutCodeSwitch("float128"); + d.LayoutCodeSwitch("decimal"); + d.LayoutCodeSwitch("datetime"); + d.LayoutCodeSwitch("unixdatetime"); + d.LayoutCodeSwitch("guid"); + d.LayoutCodeSwitch("mongodbobjectid"); + d.LayoutCodeSwitch("utf8"); + d.LayoutCodeSwitch("binary"); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CrossVersionReadNullSparse() + public void CrossVersionReadNullSparse() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Sparse")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.ReadFrom(this.resolver, + this.expected.getCrossVersionNullSparse()); + d.LayoutCodeSwitch("null"); + d.LayoutCodeSwitch("bool"); + d.LayoutCodeSwitch("int8"); + d.LayoutCodeSwitch("int16"); + d.LayoutCodeSwitch("int32"); + d.LayoutCodeSwitch("int64"); + d.LayoutCodeSwitch("uint8"); + d.LayoutCodeSwitch("uint16"); + d.LayoutCodeSwitch("uint32"); + d.LayoutCodeSwitch("uint64"); + d.LayoutCodeSwitch("float32"); + d.LayoutCodeSwitch("float64"); + d.LayoutCodeSwitch("float128"); + d.LayoutCodeSwitch("decimal"); + d.LayoutCodeSwitch("datetime"); + d.LayoutCodeSwitch("unixdatetime"); + d.LayoutCodeSwitch("guid"); + d.LayoutCodeSwitch("mongodbobjectid"); + d.LayoutCodeSwitch("utf8"); + d.LayoutCodeSwitch("binary"); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CrossVersionReadNullVariable() + public void CrossVersionReadNullVariable() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Variable")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.Create(layout, this.resolver); + d.LayoutCodeSwitch("varint"); + d.LayoutCodeSwitch("varuint"); + d.LayoutCodeSwitch("utf8"); + d.LayoutCodeSwitch("binary"); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][SuppressMessage("StyleCop.CSharp.ReadabilityRules", + // "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Test code.")] public void CrossVersionReadSparse() + public void CrossVersionReadSparse() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Sparse")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.ReadFrom(this.resolver, + this.expected.getCrossVersionSparse()); + d.LayoutCodeSwitch("null"); + d.LayoutCodeSwitch("bool", value:true) + d.LayoutCodeSwitch("int8", value:(byte)-86) + d.LayoutCodeSwitch("int16", value:(short)-21846) + d.LayoutCodeSwitch("int32", value:-1431655766) + d.LayoutCodeSwitch("int64", value:-6148914691236517206L) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint8", value: (byte)0xAA); + d.LayoutCodeSwitch("uint8", value:(byte)0xAA) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint16", value: (ushort)0xAAAA); + d.LayoutCodeSwitch("uint16", value:(short)0xAAAA) + d.LayoutCodeSwitch("uint32", value:0xAAAAAAAA) + d.LayoutCodeSwitch("uint64", value:0xAAAAAAAAAAAAAAAAL) + d.LayoutCodeSwitch("float32", value:1.0F / 3.0F) + d.LayoutCodeSwitch("float64", value:1.0 / 3.0) + d.LayoutCodeSwitch("float128", value:CrossVersioningUnitTests.SampleFloat128) + d.LayoutCodeSwitch("decimal", value:java.math.BigDecimal.ONE / 3.0) + d.LayoutCodeSwitch("datetime", value:CrossVersioningUnitTests.SampleDateTime) + d.LayoutCodeSwitch("unixdatetime", value:CrossVersioningUnitTests.SampleUnixDateTime) + d.LayoutCodeSwitch("guid", value:CrossVersioningUnitTests.SampleGuid) + d.LayoutCodeSwitch("mongodbobjectid", value:CrossVersioningUnitTests.SampleMongoDbObjectId) + d.LayoutCodeSwitch("utf8", value:"abc") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("binary", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("binary", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + d.LayoutCodeSwitch("array_t", value:new byte[] { -86, -86, -86 }) + d.LayoutCodeSwitch("array_t>", value:new float[][] + { + new float[] { 1, 2, 3 }, + new float[] { 1, 2, 3 } + }) + d.LayoutCodeSwitch("array_t", value:new String[] { "abc", "def", "hij" }) + d.LayoutCodeSwitch("tuple", value:Tuple.Create(-6148914691236517206L, -6148914691236517206L)) + d.LayoutCodeSwitch("tuple>", value: + Tuple.Create(NullValue.Default, Tuple.Create((byte)-86, (byte)-86))) + d.LayoutCodeSwitch("tuple", value:Tuple.Create(false, new Point(1, 2))) + d.LayoutCodeSwitch("set_t", value:new String[] { "abc", "efg", "xzy" }) + d.LayoutCodeSwitch("set_t>", value:new byte[][] + { + new byte[] { 1, 2, 3 }, + new byte[] { 4, 5, 6 }, + new byte[] { 7, 8, 9 } + }) + d.LayoutCodeSwitch("set_t>", value:new int[][] + { + new int[] { 1, 2, 3 }, + new int[] { 4, 5, 6 }, + new int[] { 7, 8, 9 } + }) + d.LayoutCodeSwitch("set_t", value:new Point[] + { + new Point(1, 2), + new Point(3, 4), + new Point(5, 6) + }) + d.LayoutCodeSwitch("map_t", value: + new System.Tuple[] { Tuple.Create("Mark", "Luke"), Tuple.Create("Harrison", "Han") }) + d.LayoutCodeSwitch("map_t>", value: + new System.Tuple[] { Tuple.Create((byte)1, new byte[] { 1, 2, 3 }), Tuple.Create((byte)2, + new byte[] { 4, 5, 6 }) }) + + d.LayoutCodeSwitch("map_t>", value: + new System.Tuple[] { Tuple.Create((short)1, new System.Tuple[] { Tuple.Create(1, 2), + Tuple.Create(3, 4) }), Tuple.Create((short)2, new System.Tuple[] { Tuple.Create(5, 6), + Tuple.Create(7, 8) }) }) + + d.LayoutCodeSwitch("map_t", value: + new System.Tuple[] { Tuple.Create(2.0, new Point(3, 4)), Tuple.Create(3.0, new Point(5, 6)), + Tuple.Create(1.0, new Point(1, 2)) }) + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CrossVersionReadVariable() + public void CrossVersionReadVariable() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Variable")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.ReadFrom(this.resolver, + this.expected.getCrossVersionVariable()); + d.LayoutCodeSwitch("varint", value:-6148914691236517206L) + d.LayoutCodeSwitch("varuint", value:0xAAAAAAAAAAAAAAAAL) + d.LayoutCodeSwitch("utf8", value:"abc") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("binary", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("binary", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CrossVersionWriteFixed() + public void CrossVersionWriteFixed() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Fixed")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.Create(layout, this.resolver); + d.LayoutCodeSwitch("null"); + d.LayoutCodeSwitch("bool", value:true) + d.LayoutCodeSwitch("int8", value:(byte)-86) + d.LayoutCodeSwitch("int16", value:(short)-21846) + d.LayoutCodeSwitch("int32", value:-1431655766) + d.LayoutCodeSwitch("int64", value:-6148914691236517206L) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint8", value: (byte)0xAA); + d.LayoutCodeSwitch("uint8", value:(byte)0xAA) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint16", value: (ushort)0xAAAA); + d.LayoutCodeSwitch("uint16", value:(short)0xAAAA) + d.LayoutCodeSwitch("uint32", value:0xAAAAAAAA) + d.LayoutCodeSwitch("uint64", value:0xAAAAAAAAAAAAAAAAL) + d.LayoutCodeSwitch("float32", value:1.0F / 3.0F) + d.LayoutCodeSwitch("float64", value:1.0 / 3.0) + d.LayoutCodeSwitch("float128", value:CrossVersioningUnitTests.SampleFloat128) + d.LayoutCodeSwitch("decimal", value:java.math.BigDecimal.ONE / 3.0) + d.LayoutCodeSwitch("datetime", value:CrossVersioningUnitTests.SampleDateTime) + d.LayoutCodeSwitch("unixdatetime", value:CrossVersioningUnitTests.SampleUnixDateTime) + d.LayoutCodeSwitch("guid", value:CrossVersioningUnitTests.SampleGuid) + d.LayoutCodeSwitch("mongodbobjectid", value:CrossVersioningUnitTests.SampleMongoDbObjectId) + d.LayoutCodeSwitch("utf8", value:"abc") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("binary", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("binary", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + + assert this.expected.getCrossVersionFixed() == d.RowToHex(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CrossVersionWriteNullFixed() + public void CrossVersionWriteNullFixed() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Fixed")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.Create(layout, this.resolver); + assert this.expected.getCrossVersionNullFixed() == d.RowToHex(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CrossVersionWriteNullSparse() + public void CrossVersionWriteNullSparse() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Sparse")).SchemaId); + assert layout != null; + RowOperationDispatcher d = RowOperationDispatcher.Create(layout, this.resolver); + assert this.expected.getCrossVersionNullSparse() == d.RowToHex(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CrossVersionWriteNullVariable() + public void CrossVersionWriteNullVariable() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Variable")).SchemaId); + assert layout != null; + RowOperationDispatcher d = RowOperationDispatcher.Create(layout, this.resolver); + assert this.expected.getCrossVersionNullVariable() == d.RowToHex(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][SuppressMessage("StyleCop.CSharp.ReadabilityRules", + // "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Test code.")] public void CrossVersionWriteSparse() + public void CrossVersionWriteSparse() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Sparse")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.Create(layout, this.resolver); + d.LayoutCodeSwitch("null"); + d.LayoutCodeSwitch("bool", value:true) + d.LayoutCodeSwitch("int8", value:(byte)-86) + d.LayoutCodeSwitch("int16", value:(short)-21846) + d.LayoutCodeSwitch("int32", value:-1431655766) + d.LayoutCodeSwitch("int64", value:-6148914691236517206L) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint8", value: (byte)0xAA); + d.LayoutCodeSwitch("uint8", value:(byte)0xAA) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint16", value: (ushort)0xAAAA); + d.LayoutCodeSwitch("uint16", value:(short)0xAAAA) + d.LayoutCodeSwitch("uint32", value:0xAAAAAAAA) + d.LayoutCodeSwitch("uint64", value:0xAAAAAAAAAAAAAAAAL) + d.LayoutCodeSwitch("float32", value:1.0F / 3.0F) + d.LayoutCodeSwitch("float64", value:1.0 / 3.0) + d.LayoutCodeSwitch("float128", value:CrossVersioningUnitTests.SampleFloat128) + d.LayoutCodeSwitch("decimal", value:java.math.BigDecimal.ONE / 3.0) + d.LayoutCodeSwitch("datetime", value:CrossVersioningUnitTests.SampleDateTime) + d.LayoutCodeSwitch("unixdatetime", value:CrossVersioningUnitTests.SampleUnixDateTime) + d.LayoutCodeSwitch("guid", value:CrossVersioningUnitTests.SampleGuid) + d.LayoutCodeSwitch("mongodbobjectid", value:CrossVersioningUnitTests.SampleMongoDbObjectId) + d.LayoutCodeSwitch("utf8", value:"abc") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("binary", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("binary", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + d.LayoutCodeSwitch("array_t", value:new byte[] { -86, -86, -86 }) + d.LayoutCodeSwitch("array_t>", value:new float[][] + { + new float[] { 1, 2, 3 }, + new float[] { 1, 2, 3 } + }) + d.LayoutCodeSwitch("array_t", value:new String[] { "abc", "def", "hij" }) + d.LayoutCodeSwitch("tuple", value:Tuple.Create(-6148914691236517206L, -6148914691236517206L)) + d.LayoutCodeSwitch("tuple>", value: + Tuple.Create(NullValue.Default, Tuple.Create((byte)-86, (byte)-86))) + d.LayoutCodeSwitch("tuple", value:Tuple.Create(false, new Point(1, 2))) + d.LayoutCodeSwitch("set_t", value:new String[] { "abc", "efg", "xzy" }) + d.LayoutCodeSwitch("set_t>", value:new byte[][] + { + new byte[] { 1, 2, 3 }, + new byte[] { 4, 5, 6 }, + new byte[] { 7, 8, 9 } + }) + d.LayoutCodeSwitch("set_t>", value:new int[][] + { + new int[] { 1, 2, 3 }, + new int[] { 4, 5, 6 }, + new int[] { 7, 8, 9 } + }) + d.LayoutCodeSwitch("set_t", value:new Point[] + { + new Point(1, 2), + new Point(3, 4), + new Point(5, 6) + }) + d.LayoutCodeSwitch("map_t", value: + new System.Tuple[] { Tuple.Create("Mark", "Luke"), Tuple.Create("Harrison", "Han") }) + d.LayoutCodeSwitch("map_t>", value: + new System.Tuple[] { Tuple.Create((byte)1, new byte[] { 1, 2, 3 }), Tuple.Create((byte)2, + new byte[] { 4, 5, 6 }) }) + + d.LayoutCodeSwitch("map_t>", value: + new System.Tuple[] { Tuple.Create((short)1, new System.Tuple[] { Tuple.Create(1, 2), + Tuple.Create(3, 4) }), Tuple.Create((short)2, new System.Tuple[] { Tuple.Create(5, 6), + Tuple.Create(7, 8) }) }) + + d.LayoutCodeSwitch("map_t", value: + new System.Tuple[] { Tuple.Create(1.0, new Point(1, 2)), Tuple.Create(2.0, new Point(3, 4)), + Tuple.Create(3.0, new Point(5, 6)) }) + + assert this.expected.getCrossVersionSparse() == d.RowToHex(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CrossVersionWriteVariable() + public void CrossVersionWriteVariable() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Variable")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.Create(layout, this.resolver); + d.LayoutCodeSwitch("varint", value:-6148914691236517206L) + d.LayoutCodeSwitch("varuint", value:0xAAAAAAAAAAAAAAAAL) + d.LayoutCodeSwitch("utf8", value:"abc") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("binary", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("binary", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + + assert this.expected.getCrossVersionVariable() == d.RowToHex(); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespace() + public void ParseNamespace() { + String json = Files.readString(CrossVersioningUnitTests.SchemaFile); + this.schema = Namespace.Parse(json); + json = Files.readString(CrossVersioningUnitTests.ExpectedFile); + this.expected = JsonConvert.DeserializeObject(json); + this.resolver = new LayoutResolverNamespace(this.schema); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Instantiated through Reflection.")] private sealed class Expected + private final static class Expected { + private String CrossVersionFixed; + private String CrossVersionNullFixed; + private String CrossVersionNullSparse; + private String CrossVersionNullVariable; + private String CrossVersionSparse; + private String CrossVersionVariable; + + public String getCrossVersionFixed() { + return CrossVersionFixed; + } + + public void setCrossVersionFixed(String value) { + CrossVersionFixed = value; + } + + public String getCrossVersionNullFixed() { + return CrossVersionNullFixed; + } + + public void setCrossVersionNullFixed(String value) { + CrossVersionNullFixed = value; + } + + public String getCrossVersionNullSparse() { + return CrossVersionNullSparse; + } + + public void setCrossVersionNullSparse(String value) { + CrossVersionNullSparse = value; + } + + public String getCrossVersionNullVariable() { + return CrossVersionNullVariable; + } + + public void setCrossVersionNullVariable(String value) { + CrossVersionNullVariable = value; + } + + public String getCrossVersionSparse() { + return CrossVersionSparse; + } + + public void setCrossVersionSparse(String value) { + CrossVersionSparse = value; + } + + public String getCrossVersionVariable() { + return CrossVersionVariable; + } + + public void setCrossVersionVariable(String value) { + CrossVersionVariable = value; + } + } + + private final static class Point implements IDispatchable { + public int X; + public int Y; + + public Point(int x, int y) { + this.X = x; + this.Y = y; + } + + public void Dispatch(tangible.RefObject dispatcher, tangible.RefObject scope) { + dispatcher.argValue.LayoutCodeSwitch(scope, "x", value:this.X) + dispatcher.argValue.LayoutCodeSwitch(scope, "y", value:this.Y) + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof null) + { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof Point; + Point point = tempVar ? (Point)obj : null; + return tempVar && this.equals(point); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + return ((new Integer(this.X)).hashCode() * 397) ^ (new Integer(this.Y)).hashCode(); + } + } + + private boolean equals(Point other) { + return this.X == other.X && this.Y == other.Y; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/CustomerExampleUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/CustomerExampleUnitTests.java new file mode 100644 index 0000000..8583371 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/CustomerExampleUnitTests.java @@ -0,0 +1,886 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; +import java.util.UUID; + +// ReSharper disable once StringLiteralTypo +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][SuppressMessage("Naming", "DontUseVarForVariableTypes", Justification = "The types here +// are anonymous.")][DeploymentItem("TestData\\CustomerSchema.json", "TestData")] public sealed class +// CustomerExampleUnitTests +public final class CustomerExampleUnitTests { + private final Hotel hotelExample = new Hotel() { + Id ="The-Westin-St-John-Resort-Villas-1187",Name ="The Westin St. John Resort Villas",Phone ="+1 340-693-8000" + ,Address =new Address + + { + Street = "300B Chocolate Hole", City = "Great Cruz Bay", State = "VI", PostalCode = new PostalCode { + Zip = 00830, Plus4 = 0001 + } + } + }; + private LayoutResolver customerResolver; + private Namespace customerSchema; + private Layout guestLayout; + private Layout hotelLayout; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateGuest() + public void CreateGuest() { + RowBuffer row = new RowBuffer(1024 * 1024); + row.InitLayout(HybridRowVersion.V1, this.guestLayout, this.customerResolver); + + Guest g1 = new Guest(); + g1.Id = UUID.fromString("64d9d6d3-fd6b-4556-8c6e-d960a7ece7b9"); + g1.FirstName = "John"; + g1.LastName = "Adams"; + g1.Title = "President of the United States"; + g1.PhoneNumbers = new ArrayList(Arrays.asList("(202) 456-1111")); + g1.ConfirmNumber = "(202) 456-1111"; + g1.Emails = new TreeSet { + "president@whitehouse.gov" + } + Address tempVar = new Address(); + tempVar.setStreet("1600 Pennsylvania Avenue NW"); + tempVar.setCity("Washington, D.C."); + tempVar.setState("DC"); + PostalCode tempVar2 = new PostalCode(); + tempVar2.setZip(20500); + tempVar2.setPlus4(0001); + tempVar.setPostalCode(tempVar2); + g1.Addresses = new HashMap(Map.ofEntries(Map.entry("home", tempVar))); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowCursor rc1 = RowCursor.Create(tempRef_row); + row = tempRef_row.argValue; + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + tangible.RefObject tempRef_rc1 = + new tangible.RefObject(rc1); + this.WriteGuest(tempRef_row2, tempRef_rc1, g1); + rc1 = tempRef_rc1.argValue; + row = tempRef_row2.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + RowCursor rc2 = RowCursor.Create(tempRef_row3); + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + tangible.RefObject tempRef_rc2 = + new tangible.RefObject(rc2); + Guest g2 = this.ReadGuest(tempRef_row4, tempRef_rc2); + rc2 = tempRef_rc2.argValue; + row = tempRef_row4.argValue; + assert g1 == g2; + + // Append an item to an existing list. + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + RowCursor rc3 = RowCursor.Create(tempRef_row5); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + tangible.RefObject tempRef_rc3 = + new tangible.RefObject(rc3); + int index = this.AppendGuestEmail(tempRef_row6, tempRef_rc3, "vice_president@whitehouse.gov"); + rc3 = tempRef_rc3.argValue; + row = tempRef_row6.argValue; + assert 1 == index; + g1.Emails.add("vice_president@whitehouse.gov"); + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + RowCursor rc4 = RowCursor.Create(tempRef_row7); + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + tangible.RefObject tempRef_rc4 = + new tangible.RefObject(rc4); + g2 = this.ReadGuest(tempRef_row8, tempRef_rc4); + rc4 = tempRef_rc4.argValue; + row = tempRef_row8.argValue; + assert g1 == g2; + + // Prepend an item to an existing list. + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + RowCursor rc5 = RowCursor.Create(tempRef_row9); + row = tempRef_row9.argValue; + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + tangible.RefObject tempRef_rc5 = + new tangible.RefObject(rc5); + index = this.PrependGuestEmail(tempRef_row10, tempRef_rc5, "ex_president@whitehouse.gov"); + rc5 = tempRef_rc5.argValue; + row = tempRef_row10.argValue; + assert 0 == index; + g1.Emails = new TreeSet { + "ex_president@whitehouse.gov", "president@whitehouse.gov", "vice_president@whitehouse.gov" + } + tangible.RefObject tempRef_row11 = + new tangible.RefObject(row); + RowCursor rc6 = RowCursor.Create(tempRef_row11); + row = tempRef_row11.argValue; + tangible.RefObject tempRef_row12 = + new tangible.RefObject(row); + tangible.RefObject tempRef_rc6 = + new tangible.RefObject(rc6); + g2 = this.ReadGuest(tempRef_row12, tempRef_rc6); + rc6 = tempRef_rc6.argValue; + row = tempRef_row12.argValue; + assert g1 == g2; + + // InsertAt an item to an existing list. + tangible.RefObject tempRef_row13 = + new tangible.RefObject(row); + RowCursor rc7 = RowCursor.Create(tempRef_row13); + row = tempRef_row13.argValue; + tangible.RefObject tempRef_row14 = + new tangible.RefObject(row); + tangible.RefObject tempRef_rc7 = + new tangible.RefObject(rc7); + index = this.InsertAtGuestEmail(tempRef_row14, tempRef_rc7, 1, "future_president@whitehouse.gov"); + rc7 = tempRef_rc7.argValue; + row = tempRef_row14.argValue; + assert 1 == index; + g1.Emails = new TreeSet { + "ex_president@whitehouse.gov", "future_president@whitehouse.gov", "president@whitehouse.gov", + "vice_president@whitehouse.gov" + } + + tangible.RefObject tempRef_row15 = + new tangible.RefObject(row); + RowCursor rc8 = RowCursor.Create(tempRef_row15); + row = tempRef_row15.argValue; + tangible.RefObject tempRef_row16 = + new tangible.RefObject(row); + tangible.RefObject tempRef_rc8 = + new tangible.RefObject(rc8); + g2 = this.ReadGuest(tempRef_row16, tempRef_rc8); + rc8 = tempRef_rc8.argValue; + row = tempRef_row16.argValue; + assert g1 == g2; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateHotel() + public void CreateHotel() { + RowBuffer row = new RowBuffer(0); + row.InitLayout(HybridRowVersion.V1, this.hotelLayout, this.customerResolver); + + Hotel h1 = this.hotelExample; + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row); + row = tempRef_row.argValue; + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + tangible.RefObject tempRef_root = + new tangible.RefObject(root); + this.WriteHotel(tempRef_row2, tempRef_root, h1); + root = tempRef_root.argValue; + row = tempRef_row2.argValue; + + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + root = RowCursor.Create(tempRef_row3); + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + tangible.RefObject tempRef_root2 = + new tangible.RefObject(root); + Hotel h2 = this.ReadHotel(tempRef_row4, tempRef_root2); + root = tempRef_root2.argValue; + row = tempRef_row4.argValue; + + assert h1 == h2; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void FrozenHotel() + public void FrozenHotel() { + RowBuffer row = new RowBuffer(0); + row.InitLayout(HybridRowVersion.V1, this.hotelLayout, this.customerResolver); + + Hotel h1 = this.hotelExample; + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row); + row = tempRef_row.argValue; + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + tangible.RefObject tempRef_root = + new tangible.RefObject(root); + this.WriteHotel(tempRef_row2, tempRef_root, h1); + root = tempRef_root.argValue; + row = tempRef_row2.argValue; + + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + root = RowCursor.Create(tempRef_row3); + row = tempRef_row3.argValue; + Address tempVar = new Address(); + tempVar.setStreet("300B Brownie Way"); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + tangible.RefObject tempRef_root2 = + new tangible.RefObject(root); + ResultAssert.InsufficientPermissions(this.PartialUpdateHotelAddress(tempRef_row4, tempRef_root2, tempVar)); + root = tempRef_root2.argValue; + row = tempRef_row4.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public void ParseNamespaceExample() { + String json = Files.readString("TestData\\CustomerSchema.json"); + this.customerSchema = Namespace.Parse(json); + this.customerResolver = new LayoutResolverNamespace(this.customerSchema); + this.hotelLayout = this.customerResolver.Resolve(tangible.ListHelper.find(this.customerSchema.getSchemas(), + x -> x.Name.equals("Hotels")).SchemaId); + this.guestLayout = this.customerResolver.Resolve(tangible.ListHelper.find(this.customerSchema.getSchemas(), + x -> x.Name.equals("Guests")).SchemaId); + } + + private int AppendGuestEmail(tangible.RefObject row, tangible.RefObject root, String email) { + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("emails", out c); + root.argValue.Find(row, c.Path); + RowCursor emailScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(row, root, out emailScope)); + assert !emailScope.MoveTo(row, Integer.MAX_VALUE); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref emailScope, email)); + return emailScope.Index; + } + + private int InsertAtGuestEmail(tangible.RefObject row, tangible.RefObject root, int i, + String email) { + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("emails", out c); + root.argValue.Find(row, c.Path); + RowCursor emailScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(row, root, out emailScope)); + assert emailScope.MoveTo(row, i); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref emailScope, email, + UpdateOptions.InsertAt)); + return emailScope.Index; + } + + private Result PartialUpdateHotelAddress(tangible.RefObject row, tangible.RefObject root, + Address a) { + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.hotelLayout.TryFind("address", out c); + root.argValue.Find(row, c.Path); + RowCursor addressScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = c.TypeAs().ReadScope(row, root, out addressScope); + if (r != Result.Success) { + return r; + } + + Layout addressLayout = addressScope.Layout; + if (a.Street != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert addressLayout.TryFind("street", out c); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = c.TypeAs().WriteVariable(row, ref addressScope, c, a.Street); + if (r != Result.Success) { + return r; + } + } + + if (a.City != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert addressLayout.TryFind("city", out c); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = c.TypeAs().WriteVariable(row, ref addressScope, c, a.City); + if (r != Result.Success) { + return r; + } + } + + if (a.State != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert addressLayout.TryFind("state", out c); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = c.TypeAs().WriteFixed(row, ref addressScope, c, a.State); + if (r != Result.Success) { + return r; + } + } + + if (a.PostalCode != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert addressLayout.TryFind("postal_code", out c); + addressScope.Find(row, c.Path); + RowCursor postalCodeScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = c.TypeAs().WriteScope(row, ref addressScope, c.TypeArgs, out postalCodeScope); + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_postalCodeScope = + new tangible.RefObject(postalCodeScope); + this.WritePostalCode(row, tempRef_postalCodeScope, c.TypeArgs, a.PostalCode); + postalCodeScope = tempRef_postalCodeScope.argValue; + } + + return Result.Success; + } + + private int PrependGuestEmail(tangible.RefObject row, tangible.RefObject root, String email) { + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("emails", out c); + root.argValue.Find(row, c.Path); + RowCursor emailScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(row, root, out emailScope)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref emailScope, email, + UpdateOptions.InsertAt)); + return emailScope.Index; + } + + private static Address ReadAddress(tangible.RefObject row, tangible.RefObject addressScope) { + Address a = new Address(); + Layout addressLayout = addressScope.argValue.getLayout(); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert addressLayout.TryFind("street", out c); + tangible.OutObject tempOut_Street = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, addressScope, c, tempOut_Street)); + a.Street = tempOut_Street.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert addressLayout.TryFind("city", out c); + tangible.OutObject tempOut_City = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, addressScope, c, tempOut_City)); + a.City = tempOut_City.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert addressLayout.TryFind("state", out c); + tangible.OutObject tempOut_State = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadFixed(row, addressScope, c, tempOut_State)); + a.State = tempOut_State.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert addressLayout.TryFind("postal_code", out c); + addressScope.argValue.Find(row, c.Path); + RowCursor postalCodeScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(row, addressScope, out postalCodeScope)); + tangible.RefObject tempRef_postalCodeScope = + new tangible.RefObject(postalCodeScope); + a.PostalCode = CustomerExampleUnitTests.ReadPostalCode(row, tempRef_postalCodeScope); + postalCodeScope = tempRef_postalCodeScope.argValue; + tangible.RefObject tempRef_postalCodeScope2 = + new tangible.RefObject(postalCodeScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(addressScope.argValue.clone(), row, + tempRef_postalCodeScope2); + postalCodeScope = tempRef_postalCodeScope2.argValue; + return a; + } + + private Guest ReadGuest(tangible.RefObject row, tangible.RefObject root) { + Guest g = new Guest(); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("guest_id", out c); + tangible.OutObject tempOut_Id = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadFixed(row, root, c, tempOut_Id)); + g.Id = tempOut_Id.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("first_name", out c); + tangible.OutObject tempOut_FirstName = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, root, c, tempOut_FirstName)); + g.FirstName = tempOut_FirstName.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("last_name", out c); + tangible.OutObject tempOut_LastName = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, root, c, tempOut_LastName)); + g.LastName = tempOut_LastName.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("title", out c); + tangible.OutObject tempOut_Title = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, root, c, tempOut_Title)); + g.Title = tempOut_Title.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("confirm_number", out c); + tangible.OutObject tempOut_ConfirmNumber = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, root, c, tempOut_ConfirmNumber)); + g.ConfirmNumber = tempOut_ConfirmNumber.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("emails", out c); + RowCursor emailScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out emailScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref emailScope, out emailScope) == Result.Success) { + g.Emails = new TreeSet(); + while (emailScope.MoveNext(row)) { + String item; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref emailScope, + out item)); + g.Emails.add(item); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("phone_numbers", out c); + RowCursor phoneNumbersScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out phoneNumbersScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref phoneNumbersScope, out phoneNumbersScope) == Result.Success) { + g.PhoneNumbers = new ArrayList(); + while (phoneNumbersScope.MoveNext(row)) { + String item; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref phoneNumbersScope, + out item)); + g.PhoneNumbers.add(item); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("addresses", out c); + RowCursor addressesScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out addressesScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref addressesScope, out addressesScope) == Result.Success) { + tangible.RefObject tempRef_addressesScope = new tangible.RefObject(addressesScope); + TypeArgument tupleType = LayoutType.TypedMap.FieldType(tempRef_addressesScope).clone(); + addressesScope = tempRef_addressesScope.argValue; + TypeArgument t0 = tupleType.getTypeArgs().get(0).clone(); + TypeArgument t1 = tupleType.getTypeArgs().get(1).clone(); + g.Addresses = new HashMap(); + RowCursor pairScope = null; + tangible.RefObject tempRef_pairScope = new tangible.RefObject(pairScope); + while (addressesScope.MoveNext(row, tempRef_pairScope)) { + pairScope = tempRef_pairScope.argValue; + tangible.RefObject tempRef_addressesScope2 = new tangible.RefObject(addressesScope); + tangible.OutObject tempOut_pairScope = new tangible.OutObject(); + ResultAssert.IsSuccess(tupleType.TypeAs().ReadScope(row, tempRef_addressesScope2, tempOut_pairScope)); + pairScope = tempOut_pairScope.argValue; + addressesScope = tempRef_addressesScope2.argValue; + assert Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(pairScope.clone(), row); + tangible.RefObject tempRef_pairScope2 = new tangible.RefObject(pairScope); + String key; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(t0.TypeAs().ReadSparse(row, tempRef_pairScope2, out key)); + pairScope = tempRef_pairScope2.argValue; + assert Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(pairScope.clone(), row); + tangible.RefObject tempRef_pairScope3 = new tangible.RefObject(pairScope); + RowCursor addressScope; + tangible.OutObject tempOut_addressScope = new tangible.OutObject(); + ResultAssert.IsSuccess(t1.TypeAs().ReadScope(row, tempRef_pairScope3, tempOut_addressScope)); + addressScope = tempOut_addressScope.argValue; + pairScope = tempRef_pairScope3.argValue; + tangible.RefObject tempRef_addressScope = new tangible.RefObject(addressScope); + Address value = CustomerExampleUnitTests.ReadAddress(row, tempRef_addressScope); + addressScope = tempRef_addressScope.argValue; + g.Addresses.put(key, value); + tangible.RefObject tempRef_addressScope2 = new tangible.RefObject(addressScope); + assert !Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(pairScope.clone(), row, tempRef_addressScope2); + addressScope = tempRef_addressScope2.argValue; + } + pairScope = tempRef_pairScope.argValue; + } + + return g; + } + + private Hotel ReadHotel(tangible.RefObject row, tangible.RefObject root) { + Hotel h = new Hotel(); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.hotelLayout.TryFind("hotel_id", out c); + tangible.OutObject tempOut_Id = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, root, c, tempOut_Id)); + h.Id = tempOut_Id.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.hotelLayout.TryFind("name", out c); + tangible.OutObject tempOut_Name = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, root, c, tempOut_Name)); + h.Name = tempOut_Name.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.hotelLayout.TryFind("phone", out c); + tangible.OutObject tempOut_Phone = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, root, c, tempOut_Phone)); + h.Phone = tempOut_Phone.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.hotelLayout.TryFind("address", out c); + assert c.Type.Immutable; + root.argValue.Find(row, c.Path); + RowCursor addressScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(row, root, out addressScope)); + assert addressScope.Immutable; + tangible.RefObject tempRef_addressScope = + new tangible.RefObject(addressScope); + h.Address = CustomerExampleUnitTests.ReadAddress(row, tempRef_addressScope); + addressScope = tempRef_addressScope.argValue; + tangible.RefObject tempRef_addressScope2 = + new tangible.RefObject(addressScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, + tempRef_addressScope2); + addressScope = tempRef_addressScope2.argValue; + return h; + } + + private static PostalCode ReadPostalCode(tangible.RefObject row, + tangible.RefObject postalCodeScope) { + Layout postalCodeLayout = postalCodeScope.argValue.getLayout(); + PostalCode pc = new PostalCode(); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert postalCodeLayout.TryFind("zip", out c); + tangible.OutObject tempOut_Zip = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadFixed(row, postalCodeScope, c, tempOut_Zip)); + pc.Zip = tempOut_Zip.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert postalCodeLayout.TryFind("plus4", out c); + postalCodeScope.argValue.Find(row, c.Path); + short plus4; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadSparse(row, postalCodeScope, out plus4) == Result.Success) { + pc.Plus4 = plus4; + } + + return pc; + } + + private void WriteAddress(tangible.RefObject row, tangible.RefObject addressScope, + TypeArgumentList typeArgs, Address a) { + Layout addressLayout = this.customerResolver.Resolve(typeArgs.getSchemaId().clone()); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert addressLayout.TryFind("street", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, addressScope, c, a.Street)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert addressLayout.TryFind("city", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, addressScope, c, a.City)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert addressLayout.TryFind("state", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteFixed(row, addressScope, c, a.State)); + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert addressLayout.TryFind("postal_code", out c); + addressScope.argValue.Find(row, c.Path); + RowCursor postalCodeScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, addressScope, c.TypeArgs, out postalCodeScope)); + tangible.RefObject tempRef_postalCodeScope = + new tangible.RefObject(postalCodeScope); + this.WritePostalCode(row, tempRef_postalCodeScope, c.TypeArgs, a.PostalCode); + postalCodeScope = tempRef_postalCodeScope.argValue; + tangible.RefObject tempRef_postalCodeScope2 = + new tangible.RefObject(postalCodeScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(addressScope.argValue.clone(), row, + tempRef_postalCodeScope2); + postalCodeScope = tempRef_postalCodeScope2.argValue; + } + + private void WriteGuest(tangible.RefObject row, tangible.RefObject root, Guest g) { + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("guest_id", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteFixed(row, root, c, g.Id)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("first_name", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, root, c, g.FirstName)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("last_name", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, root, c, g.LastName)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("title", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, root, c, g.Title)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.guestLayout.TryFind("confirm_number", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, root, c, g.ConfirmNumber)); + + if (g.Emails != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.guestLayout.TryFind("emails", out c); + root.argValue.Find(row, c.Path); + RowCursor emailScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, root, c.TypeArgs, out emailScope)); + for (String email : g.Emails) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref emailScope, email)); + assert !emailScope.MoveNext(row); + } + + tangible.RefObject tempRef_emailScope = + new tangible.RefObject(emailScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, + tempRef_emailScope); + emailScope = tempRef_emailScope.argValue; + } + + if (g.PhoneNumbers != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.guestLayout.TryFind("phone_numbers", out c); + root.argValue.Find(row, c.Path); + RowCursor phoneNumbersScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, root, c.TypeArgs, + out phoneNumbersScope)); + for (String phone : g.PhoneNumbers) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref phoneNumbersScope + , phone)); + assert !phoneNumbersScope.MoveNext(row); + } + + tangible.RefObject tempRef_phoneNumbersScope = + new tangible.RefObject(phoneNumbersScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, + tempRef_phoneNumbersScope); + phoneNumbersScope = tempRef_phoneNumbersScope.argValue; + } + + if (g.Addresses != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.guestLayout.TryFind("addresses", out c); + root.argValue.Find(row, c.Path); + RowCursor addressesScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, root, c.TypeArgs, out addressesScope)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + TypeArgument tupleType = c.TypeAs().FieldType(ref addressesScope); + TypeArgument t0 = tupleType.getTypeArgs().get(0).clone(); + TypeArgument t1 = tupleType.getTypeArgs().get(1).clone(); + for (Map.Entry pair : g.Addresses.entrySet()) { + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(tupleType.TypeAs().WriteScope(row, ref tempCursor, + c.TypeArgs, out tupleScope)); + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(t0.TypeAs().WriteSparse(row, ref tupleScope, pair.getKey())); + assert tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + RowCursor addressScope; + tangible.OutObject tempOut_addressScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t1.TypeAs().WriteScope(row, tempRef_tupleScope, + t1.getTypeArgs().clone(), tempOut_addressScope)); + addressScope = tempOut_addressScope.argValue; + tupleScope = tempRef_tupleScope.argValue; + tangible.RefObject tempRef_addressScope = + new tangible.RefObject(addressScope); + this.WriteAddress(row, tempRef_addressScope, t1.getTypeArgs().clone(), pair.getValue()); + addressScope = tempRef_addressScope.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert !tupleScope.MoveNext(row, ref addressScope); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, ref addressesScope, + ref tempCursor)); + } + + tangible.RefObject tempRef_addressesScope = + new tangible.RefObject(addressesScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, + tempRef_addressesScope); + addressesScope = tempRef_addressesScope.argValue; + } + } + + private void WriteHotel(tangible.RefObject row, tangible.RefObject root, Hotel h) { + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.hotelLayout.TryFind("hotel_id", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, root, c, h.Id)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.hotelLayout.TryFind("name", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, root, c, h.Name)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.hotelLayout.TryFind("phone", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, root, c, h.Phone)); + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.hotelLayout.TryFind("address", out c); + root.argValue.Find(row, c.Path); + RowCursor addressScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, root, c.TypeArgs, out addressScope)); + tangible.RefObject tempRef_addressScope = + new tangible.RefObject(addressScope); + this.WriteAddress(row, tempRef_addressScope, c.TypeArgs, h.Address); + addressScope = tempRef_addressScope.argValue; + tangible.RefObject tempRef_addressScope2 = + new tangible.RefObject(addressScope); + Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.Skip(root.argValue.clone(), row, + tempRef_addressScope2); + addressScope = tempRef_addressScope2.argValue; + } + + private void WritePostalCode(tangible.RefObject row, tangible.RefObject postalCodeScope, + TypeArgumentList typeArgs, PostalCode pc) { + Layout postalCodeLayout = this.customerResolver.Resolve(typeArgs.getSchemaId().clone()); + assert postalCodeLayout != null; + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert postalCodeLayout.TryFind("zip", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteFixed(row, postalCodeScope, c, pc.Zip)); + if (pc.Plus4.HasValue) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert postalCodeLayout.TryFind("plus4", out c); + postalCodeScope.argValue.Find(row, c.Path); + ResultAssert.IsSuccess(c.TypeAs().WriteSparse(row, postalCodeScope, pc.Plus4.Value)); + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/DeleteRowDispatcher.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/DeleteRowDispatcher.java new file mode 100644 index 0000000..f72d5ed --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/DeleteRowDispatcher.java @@ -0,0 +1,161 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.util.List; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: internal struct DeleteRowDispatcher : IDispatcher +public final class DeleteRowDispatcher implements IDispatcher { + + public , TValue> void Dispatch(tangible.RefObject dispatcher, tangible.RefObject root, LayoutColumn col, LayoutType t) { + Dispatch(dispatcher, root, col, t, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public void Dispatch(ref RowOperationDispatcher dispatcher, ref RowCursor root, + // LayoutColumn col, LayoutType t, TValue value = default) where TLayout : LayoutType + public , TValue> void Dispatch(tangible.RefObject dispatcher, tangible.RefObject root, LayoutColumn col, LayoutType t, TValue value) { + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + ResultAssert.IsSuccess(t.TypeAs().DeleteSparse(tempRef_Row, root)); + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + } + + public void DispatchArray(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 1); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor arrayScope; + tangible.OutObject tempOut_arrayScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadScope(tempRef_Row, scope, tempOut_arrayScope)); + arrayScope = tempOut_arrayScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + + if (!arrayScope.Immutable) { + List items = (List)value; + for (Object item : items) { + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + assert arrayScope.MoveNext(tempRef_Row2); + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + dispatcher.argValue.LayoutCodeSwitch(ref arrayScope, null, typeArgs.get(0).getType(), + typeArgs.get(0).getTypeArgs().clone(), item); + } + } + + tangible.RefObject tempRef_Row3 = + new tangible.RefObject(dispatcher.argValue.Row); + ResultAssert.IsSuccess(t.TypeAs().DeleteScope(tempRef_Row3, scope)); + dispatcher.argValue.argValue.Row = tempRef_Row3.argValue; + } + + public void DispatchMap(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 2); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor mapScope; + tangible.OutObject tempOut_mapScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadScope(tempRef_Row, scope, tempOut_mapScope)); + mapScope = tempOut_mapScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + if (!mapScope.Immutable) { + List items = (List)value; + for (Object item : items) { + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + assert mapScope.MoveNext(tempRef_Row2); + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + dispatcher.argValue.LayoutCodeSwitch(ref mapScope, null, LayoutType.TypedTuple, typeArgs.clone(), item); + } + } + + tangible.RefObject tempRef_Row3 = + new tangible.RefObject(dispatcher.argValue.Row); + ResultAssert.IsSuccess(t.TypeAs().DeleteScope(tempRef_Row3, scope)); + dispatcher.argValue.argValue.Row = tempRef_Row3.argValue; + } + + public void DispatchNullable(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 1); + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + ResultAssert.IsSuccess(t.TypeAs().DeleteScope(tempRef_Row, scope)); + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + } + + public void DispatchObject(tangible.RefObject dispatcher, + tangible.RefObject scope) { + } + + public void DispatchSet(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 1); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor setScope; + tangible.OutObject tempOut_setScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadScope(tempRef_Row, scope, tempOut_setScope)); + setScope = tempOut_setScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + if (!setScope.Immutable) { + List items = (List)value; + for (Object item : items) { + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + assert setScope.MoveNext(tempRef_Row2); + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + dispatcher.argValue.LayoutCodeSwitch(ref setScope, null, typeArgs.get(0).getType(), + typeArgs.get(0).getTypeArgs().clone(), item); + } + } + + tangible.RefObject tempRef_Row3 = + new tangible.RefObject(dispatcher.argValue.Row); + ResultAssert.IsSuccess(t.TypeAs().DeleteScope(tempRef_Row3, scope)); + dispatcher.argValue.argValue.Row = tempRef_Row3.argValue; + } + + public void DispatchTuple(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() >= 2); + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + ResultAssert.IsSuccess(t.TypeAs().DeleteScope(tempRef_Row, scope)); + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + } + + public void DispatchUDT(tangible.RefObject dispatcher, tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, Object value) { + tangible.RefObject tempRef_Row = new tangible.RefObject(dispatcher.argValue.Row); + ResultAssert.IsSuccess(t.TypeAs().DeleteScope(tempRef_Row, scope)); + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/IDispatchable.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/IDispatchable.java new file mode 100644 index 0000000..748d31e --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/IDispatchable.java @@ -0,0 +1,11 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +public interface IDispatchable { + void Dispatch(tangible.RefObject dispatcher, tangible.RefObject scope); +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/IDispatcher.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/IDispatcher.java new file mode 100644 index 0000000..2fe0cd0 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/IDispatcher.java @@ -0,0 +1,41 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +public interface IDispatcher { + + , TValue> void Dispatch(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutColumn col, + LayoutType t); + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: void Dispatch(ref RowOperationDispatcher dispatcher, ref RowCursor scope, + // LayoutColumn col, LayoutType t, TValue value = default) where TLayout : LayoutType; + , TValue> void Dispatch(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutColumn col, + LayoutType t, TValue value); + + void DispatchArray(tangible.RefObject dispatcher, tangible.RefObject scope, + LayoutType t, TypeArgumentList typeArgs, Object value); + + void DispatchMap(tangible.RefObject dispatcher, tangible.RefObject scope, + LayoutType t, TypeArgumentList typeArgs, Object value); + + void DispatchNullable(tangible.RefObject dispatcher, tangible.RefObject scope, + LayoutType t, TypeArgumentList typeArgs, Object value); + + void DispatchObject(tangible.RefObject dispatcher, tangible.RefObject scope); + + void DispatchSet(tangible.RefObject dispatcher, tangible.RefObject scope, + LayoutType t, TypeArgumentList typeArgs, Object value); + + void DispatchTuple(tangible.RefObject dispatcher, tangible.RefObject scope, + LayoutType t, TypeArgumentList typeArgs, Object value); + + void DispatchUDT(tangible.RefObject dispatcher, tangible.RefObject scope, + LayoutType type, TypeArgumentList typeArgs, Object value); +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/LayoutCompilerUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/LayoutCompilerUnitTests.java new file mode 100644 index 0000000..5491016 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/LayoutCompilerUnitTests.java @@ -0,0 +1,3234 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.NullValue; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; +import azure.data.cosmos.serialization.hybridrow.SchemaId; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.UUID; + +// ReSharper disable CommentTypo +// ReSharper disable StringLiteralTypo +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1201 // Elements should appear in the correct order +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Fields should be private +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable IDE0008 // Use explicit type + + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][SuppressMessage("Naming", "DontUseVarForVariableTypes", Justification = "The types here +// are anonymous.")] public class LayoutCompilerUnitTests +public class LayoutCompilerUnitTests { + private static final int InitialRowSize = 2 * 1024 * 1024; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void PackNullAndBoolBits() + public final void PackNullAndBoolBits() { + // Test that null bits and bool bits are packed tightly in the layout. + Schema s = new Schema(); + s.setName("TestSchema"); + s.setSchemaId(new SchemaId(1)); + s.setType(TypeKind.Schema); + for (int i = 0; i < 32; i++) { + Property tempVar = new Property(); + tempVar.setPath(String.valueOf(i)); + PrimitivePropertyType tempVar2 = new PrimitivePropertyType(); + tempVar2.setType(TypeKind.Boolean); + tempVar2.setStorage(StorageKind.Fixed); + tempVar.setPropertyType(tempVar2); + s.getProperties().add(tempVar); + + Namespace tempVar3 = new Namespace(); + tempVar3.setSchemas(new ArrayList(Arrays.asList(s))); + Layout layout = s.Compile(tempVar3); + Assert.IsTrue(layout.getSize() == LayoutBit.DivCeiling((i + 1) * 2, LayoutType.BitsPerByte), "Size: {0}, " + + "i: {1}", layout.getSize(), i); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaFixed() + public final void ParseSchemaFixed() { + // Test all fixed column types. + RoundTripFixed.Expected tempVar = new RoundTripFixed.Expected(); + tempVar.TypeName = "null"; + tempVar.Default = new NullValue(); + tempVar.Value = NullValue.Default; + RoundTripFixed.Expected tempVar2 = new RoundTripFixed.Expected(); + tempVar2.TypeName = "bool"; + tempVar2.Default = false; + tempVar2.Value = false; + RoundTripFixed.Expected tempVar3 = new RoundTripFixed.Expected(); + tempVar3.TypeName = "int8"; + tempVar3.Default = 0; + tempVar3.Value = (byte)42; + RoundTripFixed.Expected tempVar4 = new RoundTripFixed.Expected(); + tempVar4.TypeName = "int16"; + tempVar4.Default = 0; + tempVar4.Value = (short)42; + RoundTripFixed.Expected tempVar5 = new RoundTripFixed.Expected(); + tempVar5.TypeName = "int32"; + tempVar5.Default = 0; + tempVar5.Value = 42; + RoundTripFixed.Expected tempVar6 = new RoundTripFixed.Expected(); + tempVar6.TypeName = "int64"; + tempVar6.Default = 0; + tempVar6.Value = 42L; + RoundTripFixed.Expected tempVar7 = new RoundTripFixed.Expected(); + tempVar7.TypeName = "uint8"; + tempVar7.Default = 0; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar7.Value = (byte)42; + tempVar7.Value = (byte)42; + RoundTripFixed.Expected tempVar8 = new RoundTripFixed.Expected(); + tempVar8.TypeName = "uint16"; + tempVar8.Default = 0; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar8.Value = (ushort)42; + tempVar8.Value = (short)42; + RoundTripFixed.Expected tempVar9 = new RoundTripFixed.Expected(); + tempVar9.TypeName = "uint32"; + tempVar9.Default = 0; + tempVar9.Value = 42; + RoundTripFixed.Expected tempVar10 = new RoundTripFixed.Expected(); + tempVar10.TypeName = "uint64"; + tempVar10.Default = 0; + tempVar10.Value = 42; + RoundTripFixed.Expected tempVar11 = new RoundTripFixed.Expected(); + tempVar11.TypeName = "float32"; + tempVar11.Default = 0; + tempVar11.Value = 4.2F; + RoundTripFixed.Expected tempVar12 = new RoundTripFixed.Expected(); + tempVar12.TypeName = "float64"; + tempVar12.Default = 0; + tempVar12.Value = 4.2; + RoundTripFixed.Expected tempVar13 = new RoundTripFixed.Expected(); + tempVar13.TypeName = "float128"; + tempVar13.Default = new Float128(); + tempVar13.Value = new Float128(0, 42); + RoundTripFixed.Expected tempVar14 = new RoundTripFixed.Expected(); + tempVar14.TypeName = "decimal"; + tempVar14.Default = new BigDecimal(0); + tempVar14.Value = 4.2; + RoundTripFixed.Expected tempVar15 = new RoundTripFixed.Expected(); + tempVar15.TypeName = "datetime"; + tempVar15.Default = LocalDateTime.MIN; + tempVar15.Value = LocalDateTime.UtcNow; + RoundTripFixed.Expected tempVar16 = new RoundTripFixed.Expected(); + tempVar16.TypeName = "unixdatetime"; + tempVar16.Default = new UnixDateTime(); + tempVar16.Value = new UnixDateTime(42); + RoundTripFixed.Expected tempVar17 = new RoundTripFixed.Expected(); + tempVar17.TypeName = "guid"; + tempVar17.Default = null; + tempVar17.Value = UUID.NewGuid(); + RoundTripFixed.Expected tempVar18 = new RoundTripFixed.Expected(); + tempVar18.TypeName = "mongodbobjectid"; + tempVar18.Default = new MongoDbObjectId(); + tempVar18.Value = new MongoDbObjectId(0, 42); + RoundTripFixed.Expected tempVar19 = new RoundTripFixed.Expected(); + tempVar19.TypeName = "utf8"; + tempVar19.Default = "\0\0"; + tempVar19.Value = "AB"; + tempVar19.Length = 2; + RoundTripFixed.Expected tempVar20 = new RoundTripFixed.Expected(); + tempVar20.TypeName = "binary"; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar20.Default = new byte[] { 0x00, 0x00 }; + tempVar20.Default = new byte[] { 0x00, 0x00 }; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar20.Value = new byte[] { 0x01, 0x02 }; + tempVar20.Value = new byte[] { 0x01, 0x02 }; + tempVar20.Length = 2; + RoundTripFixed.Expected[] expectedSchemas = + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripFixed.Expected[] { tempVar, tempVar2, tempVar3, tempVar4, tempVar5, tempVar6, tempVar7, tempVar8, tempVar9, tempVar10, tempVar11, tempVar12, tempVar13, tempVar14, tempVar15, tempVar16, tempVar17, tempVar18, tempVar19, tempVar20 }; + + RowBuffer row = new RowBuffer(LayoutCompilerUnitTests.InitialRowSize); + for (String nullable : new String[] { "true", "false" }) { + for (RoundTripFixed.Expected exp : expectedSchemas) { + RoundTripFixed.Expected expected = exp.clone(); + String typeSchema = String.format("{'type': '%1$s', 'storage': 'fixed', 'length': %2$s, 'nullable': " + + "%3$s", expected.TypeName, expected.Length, nullable + } + }) + expected.Json = typeSchema; + String propSchema = String.format("{'path': 'a', 'type': %1$s", typeSchema + } +}); + String tableSchema=String.format("{'name': 'table', 'id': -1, 'type': 'schema', 'properties': [%1$s] }",propSchema); + try + { + Schema s=Schema.Parse(tableSchema); + Namespace tempVar21=new Namespace(); + tempVar21.setSchemas(new ArrayList(Arrays.asList(s))); + LayoutResolverNamespace resolver=new LayoutResolverNamespace(tempVar21); + Layout layout=resolver.Resolve(new SchemaId(-1)); + Assert.AreEqual(1,layout.getColumns().Length,"Json: {0}",expected.Json); + Assert.AreEqual(s.getName(),layout.getName(),"Json: {0}",expected.Json); + Assert.IsTrue(layout.toString().length()>0,"Json: {0}",expected.Json); + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + boolean found=layout.TryFind("a",out col); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Fixed,col.Storage,"Json: {0}",expected.Json); + Assert.AreEqual(expected.Length==0,col.Type.IsFixed,"Json: {0}",expected.Json); + + // Try writing a row using the layout. + row.Reset(); + row.InitLayout(HybridRowVersion.V1,layout,resolver); + + HybridRowHeader header=row.getHeader().clone(); + assert HybridRowVersion.V1==header.getVersion(); + assert layout.getSchemaId().clone()==header.getSchemaId().clone(); + + tangible.RefObjecttempRef_row=new tangible.RefObject(row); + RowCursor root=RowCursor.Create(tempRef_row); + row=tempRef_row.argValue; + RoundTripFixed.Closure tempVar22=new RoundTripFixed.Closure(); + tempVar22.Col=col; + tempVar22.Expected=expected.clone(); + tangible.RefObjecttempRef_row2=new tangible.RefObject(row); + tangible.RefObjecttempRef_root=new tangible.RefObject(root); + this.LayoutCodeSwitch(col.Type.LayoutCode,tempRef_row2,tempRef_root, + tempVar22.clone()); + root=tempRef_root.argValue; + row=tempRef_row2.argValue; + } + catch(LayoutCompilationException e) + { + assert expected.TypeName.equals("null"); + assert"false"==nullable; + } + } + } + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaVariable() +public final void ParseSchemaVariable() + { + // Helper functions to create sample arrays. + // TODO: C# TO JAVA CONVERTER: Local functions are not converted by C# to Java Converter: + // string MakeS(int size) + // { + // StringBuilder ret = new StringBuilder(size); + // for (int i = 0; i < size; i++) + // { + // ret.Append(unchecked((char)('a' + (i % 26)))); // allow wrapping (this also allows \0 chars) + // } + // + // return ret.ToString(); + // } + + // TODO: C# TO JAVA CONVERTER: Local functions are not converted by C# to Java Converter: + // byte[] MakeB(int size) + // { + // byte[] ret = new byte[size]; + // for (int i = 0; i < size; i++) + // { + // ret[i] = unchecked((byte)(i + 1)); // allow wrapping + // } + // + // return ret; + // } + + // Test all variable column types. + RoundTripVariable.Expected tempVar=new RoundTripVariable.Expected(); + tempVar.Json="{'type': 'utf8', 'storage': 'variable', 'length': 100}"; + tempVar.Short=MakeS(2); + tempVar.Value=MakeS(20); + tempVar.Long=MakeS(100); + tempVar.TooBig=MakeS(200); + RoundTripVariable.Expected tempVar2=new RoundTripVariable.Expected(); + tempVar2.Json="{'type': 'binary', 'storage': 'variable', 'length': 100}"; + tempVar2.Short=MakeB(2); + tempVar2.Value=MakeB(20); + tempVar2.Long=MakeB(100); + tempVar2.TooBig=MakeB(200); + RoundTripVariable.Expected tempVar3=new RoundTripVariable.Expected(); + tempVar3.Json="{'type': 'varint', 'storage': 'variable'}"; + tempVar3.Short=1L; + tempVar3.Value=255L; + tempVar3.Long=Long.MAX_VALUE; + RoundTripVariable.Expected tempVar4=new RoundTripVariable.Expected(); + tempVar4.Json="{'type': 'varuint', 'storage': 'variable'}"; + tempVar4.Short=1; + tempVar4.Value=255; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar4.Long = ulong.MaxValue; + tempVar4.Long=Long.MAX_VALUE; + RoundTripVariable.Expected[]expectedSchemas= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripVariable.Expected[]{tempVar,tempVar2,tempVar3,tempVar4}; + + RowBuffer row=new RowBuffer(LayoutCompilerUnitTests.InitialRowSize); + for(RoundTripVariable.Expected expected:expectedSchemas) + { + String propSchema=String.format("{'path': 'a', 'type': %1$s, ",expected.Json}})+"\r\n"+ + " {{'path': 'b', 'type': {expected.Json}}}, "+"\r\n"+ + " {{'path': 'c', 'type': {expected.Json}}}"; + + String tableSchema=String.format("{'name': 'table', 'id': -1, 'type': 'schema', 'properties': [%1$s] }",propSchema); + Schema s=Schema.Parse(tableSchema); + Namespace tempVar5=new Namespace(); + tempVar5.setSchemas(new ArrayList(Arrays.asList(s))); + LayoutResolverNamespace resolver=new LayoutResolverNamespace(tempVar5); + Layout layout=resolver.Resolve(new SchemaId(-1)); + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + boolean found=layout.TryFind("a",out col); + Assert.IsTrue(found,"Json: {0}",expected.Json); + assert col.Type.AllowVariable; + Assert.AreEqual(StorageKind.Variable,col.Storage,"Json: {0}",expected.Json); + + // Try writing a row using the layout. + row.Reset(); + row.InitLayout(HybridRowVersion.V1,layout,resolver); + + HybridRowHeader header=row.getHeader().clone(); + assert HybridRowVersion.V1==header.getVersion(); + assert layout.getSchemaId().clone()==header.getSchemaId().clone(); + + tangible.RefObjecttempRef_row=new tangible.RefObject(row); + RowCursor root=RowCursor.Create(tempRef_row); + row=tempRef_row.argValue; + RoundTripVariable.Closure tempVar6=new RoundTripVariable.Closure(); + tempVar6.Layout=layout; + tempVar6.Col=col; + tempVar6.Expected=expected.clone(); + tangible.RefObjecttempRef_row2=new tangible.RefObject(row); + tangible.RefObjecttempRef_root=new tangible.RefObject(root); + this.LayoutCodeSwitch(col.Type.LayoutCode,tempRef_row2, + tempRef_root,tempVar6.clone()); + root=tempRef_root.argValue; + row=tempRef_row2.argValue; + } + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void SparseOrdering() +public final void SparseOrdering() + { + // Test various orderings of multiple sparse column types. + RoundTripSparseOrdering.Expected tempVar=new RoundTripSparseOrdering.Expected(); + tempVar.Path="a"; + tempVar.Type=LayoutType.Utf8; + tempVar.Value="aa"; + RoundTripSparseOrdering.Expected tempVar2=new RoundTripSparseOrdering.Expected(); + tempVar2.Path="b"; + tempVar2.Type=LayoutType.Utf8; + tempVar2.Value="bb"; + RoundTripSparseOrdering.Expected tempVar3=new RoundTripSparseOrdering.Expected(); + tempVar3.Path="a"; + tempVar3.Type=LayoutType.VarInt; + tempVar3.Value=42L; + RoundTripSparseOrdering.Expected tempVar4=new RoundTripSparseOrdering.Expected(); + tempVar4.Path="b"; + tempVar4.Type=LayoutType.Int64; + tempVar4.Value=43L; + RoundTripSparseOrdering.Expected tempVar5=new RoundTripSparseOrdering.Expected(); + tempVar5.Path="a"; + tempVar5.Type=LayoutType.VarInt; + tempVar5.Value=42L; + RoundTripSparseOrdering.Expected tempVar6=new RoundTripSparseOrdering.Expected(); + tempVar6.Path="b"; + tempVar6.Type=LayoutType.Utf8; + tempVar6.Value="aa"; + RoundTripSparseOrdering.Expected tempVar7=new RoundTripSparseOrdering.Expected(); + tempVar7.Path="c"; + tempVar7.Type=LayoutType.Null; + tempVar7.Value=NullValue.Default; + RoundTripSparseOrdering.Expected tempVar8=new RoundTripSparseOrdering.Expected(); + tempVar8.Path="d"; + tempVar8.Type=LayoutType.Boolean; + tempVar8.Value=true; + RoundTripSparseOrdering.Expected[][]expectedOrders= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseOrdering.Expected[][] + { + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseOrdering.Expected[]{tempVar,tempVar2}, + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseOrdering.Expected[]{tempVar3,tempVar4}, + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseOrdering.Expected[]{tempVar5,tempVar6,tempVar7,tempVar8} + }; + + RowBuffer row=new RowBuffer(LayoutCompilerUnitTests.InitialRowSize); + for(RoundTripSparseOrdering.Expected[]expectedSet:expectedOrders) + { + for(java.lang.Iterablepermutation:expectedSet.Permute()) + { + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to LINQ query syntax: + String json=tangible.StringHelper.join(", ",from p in permutation select p.Path+": "+p.Type.Name); + System.out.printf("%1$s"+"\r\n",json); + + row.Reset(); + row.InitLayout(HybridRowVersion.V1,Layout.Empty,SystemSchema.LayoutResolver); + for(RoundTripSparseOrdering.Expected field:permutation) + { + tangible.RefObjecttempRef_row=new tangible.RefObject(row); + RowCursor root=RowCursor.Create(tempRef_row); + row=tempRef_row.argValue; + RoundTripSparseOrdering.Closure tempVar9=new RoundTripSparseOrdering.Closure(); + tempVar9.Expected=field.clone(); + tempVar9.Json=json; + tangible.RefObjecttempRef_row2=new tangible.RefObject(row); + tangible.RefObjecttempRef_root=new tangible.RefObject(root); + this.LayoutCodeSwitch(field.Type.LayoutCode, + tempRef_row2,tempRef_root,tempVar9.clone()); + root=tempRef_root.argValue; + row=tempRef_row2.argValue; + } + } + } + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaSparseSimple() +public final void ParseSchemaSparseSimple() + { + // Test all sparse column types. + RoundTripSparseSimple.Expected tempVar=new RoundTripSparseSimple.Expected(); + tempVar.Json="{'type': 'null', 'storage': 'sparse'}"; + tempVar.Value=NullValue.Default; + RoundTripSparseSimple.Expected tempVar2=new RoundTripSparseSimple.Expected(); + tempVar2.Json="{'type': 'bool', 'storage': 'sparse'}"; + tempVar2.Value=true; + RoundTripSparseSimple.Expected tempVar3=new RoundTripSparseSimple.Expected(); + tempVar3.Json="{'type': 'bool', 'storage': 'sparse'}"; + tempVar3.Value=false; + RoundTripSparseSimple.Expected tempVar4=new RoundTripSparseSimple.Expected(); + tempVar4.Json="{'type': 'int8', 'storage': 'sparse'}"; + tempVar4.Value=(byte)42; + RoundTripSparseSimple.Expected tempVar5=new RoundTripSparseSimple.Expected(); + tempVar5.Json="{'type': 'int16', 'storage': 'sparse'}"; + tempVar5.Value=(short)42; + RoundTripSparseSimple.Expected tempVar6=new RoundTripSparseSimple.Expected(); + tempVar6.Json="{'type': 'int32', 'storage': 'sparse'}"; + tempVar6.Value=42; + RoundTripSparseSimple.Expected tempVar7=new RoundTripSparseSimple.Expected(); + tempVar7.Json="{'type': 'int64', 'storage': 'sparse'}"; + tempVar7.Value=42L; + RoundTripSparseSimple.Expected tempVar8=new RoundTripSparseSimple.Expected(); + tempVar8.Json="{'type': 'uint8', 'storage': 'sparse'}"; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar8.Value = (byte)42; + tempVar8.Value=(byte)42; + RoundTripSparseSimple.Expected tempVar9=new RoundTripSparseSimple.Expected(); + tempVar9.Json="{'type': 'uint16', 'storage': 'sparse'}"; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar9.Value = (ushort)42; + tempVar9.Value=(short)42; + RoundTripSparseSimple.Expected tempVar10=new RoundTripSparseSimple.Expected(); + tempVar10.Json="{'type': 'uint32', 'storage': 'sparse'}"; + tempVar10.Value=42; + RoundTripSparseSimple.Expected tempVar11=new RoundTripSparseSimple.Expected(); + tempVar11.Json="{'type': 'uint64', 'storage': 'sparse'}"; + tempVar11.Value=42; + RoundTripSparseSimple.Expected tempVar12=new RoundTripSparseSimple.Expected(); + tempVar12.Json="{'type': 'varint', 'storage': 'sparse'}"; + tempVar12.Value=42L; + RoundTripSparseSimple.Expected tempVar13=new RoundTripSparseSimple.Expected(); + tempVar13.Json="{'type': 'varuint', 'storage': 'sparse'}"; + tempVar13.Value=42; + RoundTripSparseSimple.Expected tempVar14=new RoundTripSparseSimple.Expected(); + tempVar14.Json="{'type': 'float32', 'storage': 'sparse'}"; + tempVar14.Value=4.2F; + RoundTripSparseSimple.Expected tempVar15=new RoundTripSparseSimple.Expected(); + tempVar15.Json="{'type': 'float64', 'storage': 'sparse'}"; + tempVar15.Value=4.2; + RoundTripSparseSimple.Expected tempVar16=new RoundTripSparseSimple.Expected(); + tempVar16.Json="{'type': 'float128', 'storage': 'sparse'}"; + tempVar16.Value=new Float128(0,42); + RoundTripSparseSimple.Expected tempVar17=new RoundTripSparseSimple.Expected(); + tempVar17.Json="{'type': 'decimal', 'storage': 'sparse'}"; + tempVar17.Value=4.2; + RoundTripSparseSimple.Expected tempVar18=new RoundTripSparseSimple.Expected(); + tempVar18.Json="{'type': 'datetime', 'storage': 'sparse'}"; + tempVar18.Value=LocalDateTime.UtcNow; + RoundTripSparseSimple.Expected tempVar19=new RoundTripSparseSimple.Expected(); + tempVar19.Json="{'type': 'unixdatetime', 'storage': 'sparse'}"; + tempVar19.Value=new UnixDateTime(42); + RoundTripSparseSimple.Expected tempVar20=new RoundTripSparseSimple.Expected(); + tempVar20.Json="{'type': 'guid', 'storage': 'sparse'}"; + tempVar20.Value=UUID.NewGuid(); + RoundTripSparseSimple.Expected tempVar21=new RoundTripSparseSimple.Expected(); + tempVar21.Json="{'type': 'mongodbobjectid', 'storage': 'sparse'}"; + tempVar21.Value=new MongoDbObjectId(0,42); + RoundTripSparseSimple.Expected tempVar22=new RoundTripSparseSimple.Expected(); + tempVar22.Json="{'type': 'utf8', 'storage': 'sparse'}"; + tempVar22.Value="AB"; + RoundTripSparseSimple.Expected tempVar23=new RoundTripSparseSimple.Expected(); + tempVar23.Json="{'type': 'binary', 'storage': 'sparse'}"; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar23.Value = new byte[] { 0x01, 0x02 }; + tempVar23.Value=new byte[]{0x01,0x02}; + RoundTripSparseSimple.Expected[]expectedSchemas= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseSimple.Expected[]{tempVar,tempVar2,tempVar3,tempVar4,tempVar5,tempVar6,tempVar7,tempVar8,tempVar9,tempVar10,tempVar11,tempVar12,tempVar13,tempVar14,tempVar15,tempVar16,tempVar17,tempVar18,tempVar19,tempVar20,tempVar21,tempVar22,tempVar23}; + + RowBuffer row=new RowBuffer(LayoutCompilerUnitTests.InitialRowSize); + for(RoundTripSparseSimple.Expected expected:expectedSchemas) + { + String propSchema=String.format("{'path': 'a', 'type': %1$s",expected.Json}}); + String tableSchema=String.format("{'name': 'table', 'id': -1, 'type': 'schema', 'properties': [%1$s] }",propSchema); + Schema s=Schema.Parse(tableSchema); + Namespace tempVar24=new Namespace(); + tempVar24.setSchemas(new ArrayList(Arrays.asList(s))); + LayoutResolverNamespace resolver=new LayoutResolverNamespace(tempVar24); + Layout layout=resolver.Resolve(new SchemaId(-1)); + Assert.AreEqual(1,layout.getColumns().Length,"Json: {0}",expected.Json); + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + boolean found=layout.TryFind("a",out col); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Sparse,col.Storage,"Json: {0}",expected.Json); + + // Try writing a row using the layout. + row.Reset(); + row.InitLayout(HybridRowVersion.V1,layout,resolver); + + HybridRowHeader header=row.getHeader().clone(); + assert HybridRowVersion.V1==header.getVersion(); + assert layout.getSchemaId().clone()==header.getSchemaId().clone(); + + tangible.RefObjecttempRef_row=new tangible.RefObject(row); + RowCursor root=RowCursor.Create(tempRef_row); + row=tempRef_row.argValue; + RoundTripSparseSimple.Closure tempVar25=new RoundTripSparseSimple.Closure(); + tempVar25.Col=col; + tempVar25.Expected=expected.clone(); + tangible.RefObjecttempRef_row2=new tangible.RefObject(row); + tangible.RefObjecttempRef_root=new tangible.RefObject(root); + this.LayoutCodeSwitch(col.Type.LayoutCode,tempRef_row2, + tempRef_root,tempVar25.clone()); + root=tempRef_root.argValue; + row=tempRef_row2.argValue; + } + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaUDT() +public final void ParseSchemaUDT() + { + String namespaceJson=""+"\r\n"+ + " {'name': 'myNamespace', "+"\r\n"+ + " 'schemas': ["+"\r\n"+ + " {'name': 'udtA', 'id': 1, 'type': 'schema', 'options': { 'disallowUnschematized': false }, " + +"\r\n"+ + " 'properties': [ "+"\r\n"+ + " { 'path': 'a', 'type': { 'type': 'int8', 'storage': 'fixed' }}, "+"\r\n"+ + " { 'path': 'b', 'type': { 'type': 'utf8', 'storage': 'variable', 'length': 100 }} "+"\r\n"+ + " ]"+"\r\n"+ + " },"+"\r\n"+ + " {'name': 'udtB', 'id': 2, 'type': 'schema'},"+"\r\n"+ + " {'name': 'udtB', 'id': 3, 'type': 'schema'},"+"\r\n"+ + " {'name': 'udtB', 'id': 4, 'type': 'schema'},"+"\r\n"+ + " {'name': 'table', 'id': -1, 'type': 'schema', "+"\r\n"+ + " 'properties': ["+"\r\n"+ + " { 'path': 'u', 'type': { 'type': 'schema', 'name': 'udtA' }}, "+"\r\n"+ + " { 'path': 'v', 'type': { 'type': 'schema', 'name': 'udtB', 'id': 3 }}, "+"\r\n"+ + " ] "+"\r\n"+ + " }"+"\r\n"+ + " ]"+"\r\n"+ + " }"; + + Namespace n1=Namespace.Parse(namespaceJson); + + String tag=String.format("Json: %1$s",namespaceJson); + + RowBuffer row=new RowBuffer(LayoutCompilerUnitTests.InitialRowSize); + Schema s=tangible.ListHelper.find(n1.getSchemas(),x->x.Name.equals("table")); + assert s!=null; + assert"table"==s.getName(); + Layout layout=s.Compile(n1); + LayoutColumn udtACol; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + boolean found=layout.TryFind("u",out udtACol); + Assert.IsTrue(found,tag); + Assert.AreEqual(StorageKind.Sparse,udtACol.Storage,tag); + + Schema udtASchema=tangible.ListHelper.find(n1.getSchemas(),x->x.SchemaId==udtACol.TypeArgs.SchemaId); + assert udtASchema!=null; + assert"udtA"==udtASchema.getName(); + + // Verify that UDT versioning works through schema references. + LayoutColumn udtBCol; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + found=layout.TryFind("v",out udtBCol); + Assert.IsTrue(found,tag); + Assert.AreEqual(StorageKind.Sparse,udtBCol.Storage,tag); + Schema udtBSchema=tangible.ListHelper.find(n1.getSchemas(),x->x.SchemaId==udtBCol.TypeArgs.SchemaId); + assert udtBSchema!=null; + assert"udtB"==udtBSchema.getName(); + assert new SchemaId(3)==udtBSchema.getSchemaId().clone(); + + LayoutResolver resolver=new LayoutResolverNamespace(n1); + Layout udtLayout=resolver.Resolve(udtASchema.getSchemaId().clone()); + row.Reset(); + row.InitLayout(HybridRowVersion.V1,layout,resolver); + + HybridRowHeader header=row.getHeader().clone(); + assert HybridRowVersion.V1==header.getVersion(); + assert layout.getSchemaId().clone()==header.getSchemaId().clone(); + + // Verify the udt doesn't yet exist. + tangible.RefObjecttempRef_row=new tangible.RefObject(row); + tangible.RefObjecttempRef_row2=new tangible.RefObject(row); + RowCursor scope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row,out scope).Find(tempRef_row2,udtACol.Path); + row=tempRef_row2.argValue; + row=tempRef_row.argValue; + tangible.RefObjecttempRef_row3=new tangible.RefObject(row); + tangible.RefObjecttempRef_scope=new tangible.RefObject(scope); + tangible.OutObjecttempOut__=new tangible.OutObject(); + Result r=LayoutType.UDT.ReadScope(tempRef_row3,tempRef_scope,tempOut__); + _=tempOut__.argValue; + scope=tempRef_scope.argValue; + row=tempRef_row3.argValue; + ResultAssert.NotFound(r,tag); + tangible.RefObjecttempRef_row4=new tangible.RefObject(row); + tangible.RefObjecttempRef_scope2=new tangible.RefObject(scope); + RowCursor udtScope1; + tangible.OutObjecttempOut_udtScope1= + new tangible.OutObject(); + r=LayoutType.UDT.WriteScope(tempRef_row4,tempRef_scope2,udtACol.TypeArgs,tempOut_udtScope1); + udtScope1=tempOut_udtScope1.argValue; + scope=tempRef_scope2.argValue; + row=tempRef_row4.argValue; + ResultAssert.IsSuccess(r,tag); + tangible.RefObjecttempRef_row5=new tangible.RefObject(row); + tangible.RefObjecttempRef_scope3=new tangible.RefObject(scope); + RowCursor udtScope2; + tangible.OutObjecttempOut_udtScope2= + new tangible.OutObject(); + r=LayoutType.UDT.ReadScope(tempRef_row5,tempRef_scope3,tempOut_udtScope2); + udtScope2=tempOut_udtScope2.argValue; + scope=tempRef_scope3.argValue; + row=tempRef_row5.argValue; + ResultAssert.IsSuccess(r,tag); + Assert.AreSame(udtLayout,udtScope2.Layout,tag); + Assert.AreEqual(udtScope1.ScopeType,udtScope2.ScopeType,tag); + Assert.AreEqual(udtScope1.start,udtScope2.start,tag); + Assert.AreEqual(udtScope1.Immutable,udtScope2.Immutable,tag); + + // TODO: C# TO JAVA CONVERTER: There is no equivalent to implicit typing in Java unless the Java 10 inferred + // typing option is selected: + var expectedSchemas=new[]{new{Storage=StorageKind.Fixed,Path="a",FixedExpected=new RoundTripFixed.Expected(); + FixedExpected.Json="{ 'type': 'int8', 'storage': 'fixed' }"; + FixedExpected.Value=(byte)42; + + // TODO: C# TO JAVA CONVERTER: There is no equivalent to implicit typing in Java unless the Java 10 inferred + // typing option is selected: + for(var expected:expectedSchemas) + { + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + found=udtLayout.TryFind(expected.Path,out col); + Assert.IsTrue(found,"Path: {0}",expected.Path); + StorageKind storage=expected.Storage; + switch(storage) + { + case Fixed: + RoundTripFixed.Closure tempVar=new RoundTripFixed.Closure(); + tempVar.Col=col; + tempVar.Expected=expected.FixedExpected; + tangible.RefObjecttempRef_row6=new tangible.RefObject(row); + tangible.RefObjecttempRef_udtScope1= + new tangible.RefObject(udtScope1); + this.LayoutCodeSwitch(col.Type.LayoutCode,tempRef_row6,tempRef_udtScope1, + tempVar.clone()); + udtScope1=tempRef_udtScope1.argValue; + row=tempRef_row6.argValue; + break; + case Variable: + RoundTripVariable.Closure tempVar2=new RoundTripVariable.Closure(); + tempVar2.Col=col; + tempVar2.Layout=layout; + tempVar2.Expected=expected.VariableExpected; + tangible.RefObjecttempRef_row7=new tangible.RefObject(row); + tangible.RefObjecttempRef_udtScope12= + new tangible.RefObject(udtScope1); + this.LayoutCodeSwitch(col.Type.LayoutCode,tempRef_row7, + tempRef_udtScope12,tempVar2.clone()); + udtScope1=tempRef_udtScope12.argValue; + row=tempRef_row7.argValue; + break; + } + } + + tangible.RefObjecttempRef_row8=new tangible.RefObject(row); + tangible.RefObjecttempRef_row9=new tangible.RefObject(row); + RowCursor roRoot; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row8).AsReadOnly(out roRoot).Find(tempRef_row9,udtACol.Path); + row=tempRef_row9.argValue; + row=tempRef_row8.argValue; + tangible.RefObjecttempRef_row10=new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these cannot + // be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.InsufficientPermissions(udtACol.TypeAs().DeleteScope(tempRef_row10,ref roRoot)); + row=tempRef_row10.argValue; + tangible.RefObjecttempRef_row11=new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these cannot + // be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.InsufficientPermissions(udtACol.TypeAs().WriteScope(tempRef_row11,ref roRoot, + udtACol.TypeArgs,out udtScope2)); + row=tempRef_row11.argValue; + + // Overwrite the whole scope. + tangible.RefObjecttempRef_row12=new tangible.RefObject(row); + tangible.RefObjecttempRef_row13=new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row12,out scope).Find(tempRef_row13,udtACol.Path); + row=tempRef_row13.argValue; + row=tempRef_row12.argValue; + tangible.RefObjecttempRef_row14=new tangible.RefObject(row); + tangible.RefObjecttempRef_scope4=new tangible.RefObject(scope); + r=LayoutType.Null.WriteSparse(tempRef_row14,tempRef_scope4,NullValue.Default); + scope=tempRef_scope4.argValue; + row=tempRef_row14.argValue; + ResultAssert.IsSuccess(r,tag); + tangible.RefObjecttempRef_row15=new tangible.RefObject(row); + tangible.RefObjecttempRef_scope5=new tangible.RefObject(scope); + RowCursor _; + tangible.OutObjecttempOut__2=new tangible.OutObject(); + r=LayoutType.UDT.ReadScope(tempRef_row15,tempRef_scope5,tempOut__2); + _=tempOut__2.argValue; + scope=tempRef_scope5.argValue; + row=tempRef_row15.argValue; + ResultAssert.TypeMismatch(r,tag); + tangible.RefObjecttempRef_row16=new tangible.RefObject(row); + tangible.RefObjecttempRef_scope6=new tangible.RefObject(scope); + r=LayoutType.UDT.DeleteScope(tempRef_row16,tempRef_scope6); + scope=tempRef_scope6.argValue; + row=tempRef_row16.argValue; + ResultAssert.TypeMismatch(r,tag); + + // Overwrite it again, then delete it. + tangible.RefObjecttempRef_row17=new tangible.RefObject(row); + tangible.RefObjecttempRef_row18=new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row17,out scope).Find(tempRef_row18,udtACol.Path); + row=tempRef_row18.argValue; + row=tempRef_row17.argValue; + tangible.RefObjecttempRef_row19=new tangible.RefObject(row); + tangible.RefObjecttempRef_scope7=new tangible.RefObject(scope); + RowCursor _; + tangible.OutObjecttempOut__3=new tangible.OutObject(); + r=LayoutType.UDT.WriteScope(tempRef_row19,tempRef_scope7,udtACol.TypeArgs,tempOut__3); + _=tempOut__3.argValue; + scope=tempRef_scope7.argValue; + row=tempRef_row19.argValue; + ResultAssert.IsSuccess(r,tag); + tangible.RefObjecttempRef_row20=new tangible.RefObject(row); + tangible.RefObjecttempRef_scope8=new tangible.RefObject(scope); + r=LayoutType.UDT.DeleteScope(tempRef_row20,tempRef_scope8); + scope=tempRef_scope8.argValue; + row=tempRef_row20.argValue; + ResultAssert.IsSuccess(r,tag); + tangible.RefObjecttempRef_row21=new tangible.RefObject(row); + tangible.RefObjecttempRef_row22=new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row21,out scope).Find(tempRef_row22,udtACol.Path); + row=tempRef_row22.argValue; + row=tempRef_row21.argValue; + tangible.RefObjecttempRef_row23=new tangible.RefObject(row); + tangible.RefObjecttempRef_scope9=new tangible.RefObject(scope); + RowCursor _; + tangible.OutObjecttempOut__4=new tangible.OutObject(); + r=LayoutType.UDT.ReadScope(tempRef_row23,tempRef_scope9,tempOut__4); + _=tempOut__4.argValue; + scope=tempRef_scope9.argValue; + row=tempRef_row23.argValue; + ResultAssert.NotFound(r,tag); + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaSparseObject() +public final void ParseSchemaSparseObject() + { + // Test all fixed column types. + RoundTripSparseObject.Expected tempVar=new RoundTripSparseObject.Expected(); + tempVar.Json="{'path': 'b', 'type': {'type': 'int8'}}"; + tempVar.Value=(byte)42; + RoundTripSparseObject.Expected[]expectedSchemas= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObject.Expected[]{tempVar}; + + RowBuffer row=new RowBuffer(LayoutCompilerUnitTests.InitialRowSize); + for(RoundTripSparseObject.Expected expected:expectedSchemas) + { + String objectColumnSchema=String.format("{'path': 'a', 'type': {'type': 'object', 'properties': [%1$s] } }", + expected.Json); + String tableSchema=String.format("{'name': 'table', 'id': -1, 'type': 'schema', 'properties': [%1$s] }", + objectColumnSchema); + Schema s=Schema.Parse(tableSchema); + Namespace tempVar2=new Namespace(); + tempVar2.setSchemas(new ArrayList(Arrays.asList(s))); + LayoutResolverNamespace resolver=new LayoutResolverNamespace(tempVar2); + Layout layout=resolver.Resolve(new SchemaId(-1)); + Assert.AreEqual(1,layout.getColumns().Length,"Json: {0}",expected.Json); + LayoutColumn objCol; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + boolean found=layout.TryFind("a",out objCol); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Sparse,objCol.Storage,"Json: {0}",expected.Json); + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + found=layout.TryFind("a.b",out col); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Sparse,col.Storage,"Json: {0}",expected.Json); + + // Try writing a row using the layout. + row.Reset(); + row.InitLayout(HybridRowVersion.V1,layout,resolver); + + HybridRowHeader header=row.getHeader().clone(); + assert HybridRowVersion.V1==header.getVersion(); + assert layout.getSchemaId().clone()==header.getSchemaId().clone(); + + tangible.RefObjecttempRef_row=new tangible.RefObject(row); + RowCursor root=RowCursor.Create(tempRef_row); + row=tempRef_row.argValue; + RoundTripSparseObject.Closure tempVar3=new RoundTripSparseObject.Closure(); + tempVar3.ObjCol=objCol; + tempVar3.Col=col; + tempVar3.Expected=expected.clone(); + tangible.RefObjecttempRef_row2=new tangible.RefObject(row); + tangible.RefObjecttempRef_root=new tangible.RefObject(root); + this.LayoutCodeSwitch(col.Type.LayoutCode,tempRef_row2, + tempRef_root,tempVar3.clone()); + root=tempRef_root.argValue; + row=tempRef_row2.argValue; + } + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaSparseObjectMulti() +public final void ParseSchemaSparseObjectMulti() + { + // Test sparse object columns with various kinds of sparse column fields. + RoundTripSparseObjectMulti.Expected tempVar=new RoundTripSparseObjectMulti.Expected(); + tempVar.Json="{'path': 'b', 'type': {'type': 'int8'}}"; + RoundTripSparseObjectMulti.Property tempVar2=new RoundTripSparseObjectMulti.Property(); + tempVar2.setPath("a.b"); + tempVar2.Value=(byte)42; + tempVar.Props= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObjectMulti.Property[]{tempVar2}; + RoundTripSparseObjectMulti.Expected tempVar3=new RoundTripSparseObjectMulti.Expected(); + tempVar3.Json="{'path': 'b', 'type': {'type': 'int8'}}, {'path': 'c', 'type': {'type': 'utf8'}}"; + RoundTripSparseObjectMulti.Property tempVar4=new RoundTripSparseObjectMulti.Property(); + tempVar4.setPath("a.b"); + tempVar4.Value=(byte)42; + RoundTripSparseObjectMulti.Property tempVar5=new RoundTripSparseObjectMulti.Property(); + tempVar5.setPath("a.c"); + tempVar5.Value="abc"; + tempVar3.Props= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObjectMulti.Property[]{tempVar4,tempVar5}; + RoundTripSparseObjectMulti.Expected tempVar6=new RoundTripSparseObjectMulti.Expected(); + tempVar6.Json="{'path': 'b', 'type': {'type': 'int8'}}, {'path': 'c', 'type': {'type': 'bool'}}, {'path': 'd', " + + "'type': {'type': 'binary'}}, {'path': 'e', 'type': {'type': 'null'}}"; + RoundTripSparseObjectMulti.Property tempVar7=new RoundTripSparseObjectMulti.Property(); + tempVar7.setPath("a.b"); + tempVar7.Value=(byte)42; + RoundTripSparseObjectMulti.Property tempVar8=new RoundTripSparseObjectMulti.Property(); + tempVar8.setPath("a.c"); + tempVar8.Value=true; + RoundTripSparseObjectMulti.Property tempVar9=new RoundTripSparseObjectMulti.Property(); + tempVar9.setPath("a.d"); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar9.Value = new byte[] { 0x01, 0x02, 0x03 }; + tempVar9.Value=new byte[]{0x01,0x02,0x03}; + RoundTripSparseObjectMulti.Property tempVar10=new RoundTripSparseObjectMulti.Property(); + tempVar10.setPath("a.e"); + tempVar10.Value=NullValue.Default; + tempVar6.Props= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObjectMulti.Property[]{tempVar7,tempVar8,tempVar9,tempVar10}; + RoundTripSparseObjectMulti.Expected tempVar11=new RoundTripSparseObjectMulti.Expected(); + tempVar11.Json="{'path': 'b', 'type': {'type': 'object'}}"; + RoundTripSparseObjectMulti.Property tempVar12=new RoundTripSparseObjectMulti.Property(); + tempVar12.setPath("a.b"); + tempVar11.Props= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObjectMulti.Property[]{tempVar12}; + RoundTripSparseObjectMulti.Expected[]expectedSchemas= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObjectMulti.Expected[]{tempVar,tempVar3,tempVar6,tempVar11}; + + RowBuffer row=new RowBuffer(LayoutCompilerUnitTests.InitialRowSize); + for(RoundTripSparseObjectMulti.Expected expected:expectedSchemas) + { + String objectColumnSchema=String.format("{'path': 'a', 'type': {'type': 'object', 'properties': [%1$s] } }", + expected.Json); + String tableSchema=String.format("{'name': 'table', 'id': -1, 'type': 'schema', 'properties': [%1$s] }", + objectColumnSchema); + Schema s=Schema.Parse(tableSchema); + Namespace tempVar13=new Namespace(); + tempVar13.setSchemas(new ArrayList(Arrays.asList(s))); + LayoutResolverNamespace resolver=new LayoutResolverNamespace(tempVar13); + Layout layout=resolver.Resolve(new SchemaId(-1)); + Assert.AreEqual(1,layout.getColumns().Length,"Json: {0}",expected.Json); + LayoutColumn objCol; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + boolean found=layout.TryFind("a",out objCol); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Sparse,objCol.Storage,"Json: {0}",expected.Json); + + // Try writing a row using the layout. + row.Reset(); + row.InitLayout(HybridRowVersion.V1,layout,resolver); + + HybridRowHeader header=row.getHeader().clone(); + assert HybridRowVersion.V1==header.getVersion(); + assert layout.getSchemaId().clone()==header.getSchemaId().clone(); + + // Verify the object doesn't exist. + LayoutObject objT=objCol.Type instanceof LayoutObject?(LayoutObject)objCol.Type:null; + assert objT!=null; + tangible.RefObjecttempRef_row=new tangible.RefObject(row); + tangible.RefObjecttempRef_row2=new tangible.RefObject(row); + RowCursor field; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row,out field).Find(tempRef_row2,objCol.Path); + row=tempRef_row2.argValue; + row=tempRef_row.argValue; + tangible.RefObjecttempRef_row3=new tangible.RefObject(row); + tangible.RefObjecttempRef_field=new tangible.RefObject(field); + RowCursor scope; + tangible.OutObjecttempOut_scope=new tangible.OutObject(); + Result r=objT.ReadScope(tempRef_row3,tempRef_field,tempOut_scope); + scope=tempOut_scope.argValue; + field=tempRef_field.argValue; + row=tempRef_row3.argValue; + ResultAssert.NotFound(r,"Json: {0}",expected.Json); + + // Write the object and the nested column. + tangible.RefObjecttempRef_row4=new tangible.RefObject(row); + tangible.RefObjecttempRef_field2=new tangible.RefObject(field); + tangible.OutObjecttempOut_scope2=new tangible.OutObject(); + r=objT.WriteScope(tempRef_row4,tempRef_field2,objCol.TypeArgs,tempOut_scope2); + scope=tempOut_scope2.argValue; + field=tempRef_field2.argValue; + row=tempRef_row4.argValue; + ResultAssert.IsSuccess(r,"Json: {0}",expected.Json); + + for(java.lang.Iterablepermutation:expected.Props.Permute()) + { + for(RoundTripSparseObjectMulti.Property prop:permutation) + { + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + found=layout.TryFind(prop.Path,out col); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Sparse,col.Storage,"Json: {0}",expected.Json); + + RoundTripSparseObjectMulti.Closure tempVar14=new RoundTripSparseObjectMulti.Closure(); + tempVar14.Col=col; + tempVar14.Prop=prop.clone(); + tempVar14.Expected=expected.clone(); + tangible.RefObjecttempRef_row5=new tangible.RefObject(row); + tangible.RefObjecttempRef_scope=new tangible.RefObject(scope); + this.LayoutCodeSwitch(col.Type.LayoutCode, + tempRef_row5,tempRef_scope,tempVar14.clone()); + scope=tempRef_scope.argValue; + row=tempRef_row5.argValue; + } + } + + // Write something after the scope. + UtfAnyString otherColumnPath="not-"+objCol.Path; + tangible.RefObjecttempRef_row6=new tangible.RefObject(row); + RowCursor otherColumn; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + field.Clone(out otherColumn).Find(tempRef_row6,otherColumnPath); + row=tempRef_row6.argValue; + tangible.RefObjecttempRef_row7=new tangible.RefObject(row); + tangible.RefObjecttempRef_otherColumn= + new tangible.RefObject(otherColumn); + r=LayoutType.Boolean.WriteSparse(tempRef_row7,tempRef_otherColumn,true); + otherColumn=tempRef_otherColumn.argValue; + row=tempRef_row7.argValue; + ResultAssert.IsSuccess(r,"Json: {0}",expected.Json); + + // Overwrite the whole scope. + tangible.RefObjecttempRef_row8=new tangible.RefObject(row); + tangible.RefObjecttempRef_field3=new tangible.RefObject(field); + r=LayoutType.Null.WriteSparse(tempRef_row8,tempRef_field3,NullValue.Default); + field=tempRef_field3.argValue; + row=tempRef_row8.argValue; + ResultAssert.IsSuccess(r,"Json: {0}",expected.Json); + tangible.RefObjecttempRef_row9=new tangible.RefObject(row); + tangible.RefObjecttempRef_field4=new tangible.RefObject(field); + RowCursor _; + tangible.OutObjecttempOut__=new tangible.OutObject(); + r=objT.ReadScope(tempRef_row9,tempRef_field4,tempOut__); + _=tempOut__.argValue; + field=tempRef_field4.argValue; + row=tempRef_row9.argValue; + ResultAssert.TypeMismatch(r,"Json: {0}",expected.Json); + + // Read the thing after the scope and verify it is still there. + tangible.RefObjecttempRef_row10=new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + field.Clone(out otherColumn).Find(tempRef_row10,otherColumnPath); + row=tempRef_row10.argValue; + tangible.RefObjecttempRef_row11=new tangible.RefObject(row); + tangible.RefObjecttempRef_otherColumn2= + new tangible.RefObject(otherColumn); + boolean notScope; + tangible.OutObject tempOut_notScope=new tangible.OutObject(); + r=LayoutType.Boolean.ReadSparse(tempRef_row11,tempRef_otherColumn2,tempOut_notScope); + notScope=tempOut_notScope.argValue; + otherColumn=tempRef_otherColumn2.argValue; + row=tempRef_row11.argValue; + ResultAssert.IsSuccess(r,"Json: {0}",expected.Json); + assert notScope; + } + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaSparseObjectNested() +public final void ParseSchemaSparseObjectNested() + { + // Test nested sparse object columns with various kinds of sparse column fields. + RoundTripSparseObjectNested.Expected tempVar=new RoundTripSparseObjectNested.Expected(); + tempVar.Json="{'path': 'c', 'type': {'type': 'int8'}}"; + RoundTripSparseObjectNested.Property tempVar2=new RoundTripSparseObjectNested.Property(); + tempVar2.setPath("a.b.c"); + tempVar2.Value=(byte)42; + tempVar.Props= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObjectNested.Property[]{tempVar2}; + RoundTripSparseObjectNested.Expected tempVar3=new RoundTripSparseObjectNested.Expected(); + tempVar3.Json="{'path': 'b', 'type': {'type': 'int8'}}, {'path': 'c', 'type': {'type': 'utf8'}}"; + RoundTripSparseObjectNested.Property tempVar4=new RoundTripSparseObjectNested.Property(); + tempVar4.setPath("a.b.b"); + tempVar4.Value=(byte)42; + RoundTripSparseObjectNested.Property tempVar5=new RoundTripSparseObjectNested.Property(); + tempVar5.setPath("a.b.c"); + tempVar5.Value="abc"; + tempVar3.Props= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObjectNested.Property[]{tempVar4,tempVar5}; + RoundTripSparseObjectNested.Expected tempVar6=new RoundTripSparseObjectNested.Expected(); + tempVar6.Json="{'path': 'b', 'type': {'type': 'int8'}}, {'path': 'c', 'type': {'type': 'bool'}}, {'path': 'd', " + + "'type': {'type': 'binary'}}, {'path': 'e', 'type': {'type': 'null'}}"; + RoundTripSparseObjectNested.Property tempVar7=new RoundTripSparseObjectNested.Property(); + tempVar7.setPath("a.b.b"); + tempVar7.Value=(byte)42; + RoundTripSparseObjectNested.Property tempVar8=new RoundTripSparseObjectNested.Property(); + tempVar8.setPath("a.b.c"); + tempVar8.Value=true; + RoundTripSparseObjectNested.Property tempVar9=new RoundTripSparseObjectNested.Property(); + tempVar9.setPath("a.b.d"); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar9.Value = new byte[] { 0x01, 0x02, 0x03 }; + tempVar9.Value=new byte[]{0x01,0x02,0x03}; + RoundTripSparseObjectNested.Property tempVar10=new RoundTripSparseObjectNested.Property(); + tempVar10.setPath("a.b.e"); + tempVar10.Value=NullValue.Default; + tempVar6.Props= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObjectNested.Property[]{tempVar7,tempVar8,tempVar9,tempVar10}; + RoundTripSparseObjectNested.Expected tempVar11=new RoundTripSparseObjectNested.Expected(); + tempVar11.Json="{'path': 'b', 'type': {'type': 'object'}}"; + RoundTripSparseObjectNested.Property tempVar12=new RoundTripSparseObjectNested.Property(); + tempVar12.setPath("a.b.b"); + tempVar11.Props= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObjectNested.Property[]{tempVar12}; + RoundTripSparseObjectNested.Expected[]expectedSchemas= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseObjectNested.Expected[]{tempVar,tempVar3,tempVar6,tempVar11}; + + RowBuffer row=new RowBuffer(LayoutCompilerUnitTests.InitialRowSize); + for(RoundTripSparseObjectNested.Expected expected:expectedSchemas) + { + String nestedColumnSchema=String.format("{'path': 'b', 'type': {'type': 'object', 'properties': [%1$s] } }", + expected.Json); + String objectColumnSchema=String.format("{'path': 'a', 'type': {'type': 'object', 'properties': [%1$s] } }", + nestedColumnSchema); + String tableSchema=String.format("{'name': 'table', 'id': -1, 'type': 'schema', 'properties': [%1$s] }", + objectColumnSchema); + Schema s=Schema.Parse(tableSchema); + Namespace tempVar13=new Namespace(); + tempVar13.setSchemas(new ArrayList(Arrays.asList(s))); + LayoutResolverNamespace resolver=new LayoutResolverNamespace(tempVar13); + Layout layout=resolver.Resolve(new SchemaId(-1)); + LayoutColumn objCol; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + boolean found=layout.TryFind("a",out objCol); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Sparse,objCol.Storage,"Json: {0}",expected.Json); + LayoutColumn objCol2; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + found=layout.TryFind("a.b",out objCol2); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Sparse,objCol2.Storage,"Json: {0}",expected.Json); + + // Try writing a row using the layout. + row.Reset(); + row.InitLayout(HybridRowVersion.V1,layout,resolver); + tangible.RefObjecttempRef_row=new tangible.RefObject(row); + RowCursor root=RowCursor.Create(tempRef_row); + row=tempRef_row.argValue; + + HybridRowHeader header=row.getHeader().clone(); + assert HybridRowVersion.V1==header.getVersion(); + assert layout.getSchemaId().clone()==header.getSchemaId().clone(); + + // Write the object. + LayoutObject objT=objCol.Type instanceof LayoutObject?(LayoutObject)objCol.Type:null; + assert objT!=null; + tangible.RefObjecttempRef_row2=new tangible.RefObject(row); + RowCursor field; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out field).Find(tempRef_row2,objCol.Path); + row=tempRef_row2.argValue; + tangible.RefObjecttempRef_row3=new tangible.RefObject(row); + tangible.RefObjecttempRef_field=new tangible.RefObject(field); + RowCursor _; + tangible.OutObjecttempOut__=new tangible.OutObject(); + Result r=objT.WriteScope(tempRef_row3,tempRef_field,objCol.TypeArgs,tempOut__); + _=tempOut__.argValue; + field=tempRef_field.argValue; + row=tempRef_row3.argValue; + ResultAssert.IsSuccess(r,"Json: {0}",expected.Json); + + for(java.lang.Iterablepermutation:expected.Props.Permute()) + { + for(RoundTripSparseObjectNested.Property prop:permutation) + { + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + found=layout.TryFind(prop.Path,out col); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Sparse,col.Storage,"Json: {0}",expected.Json); + + RoundTripSparseObjectNested.Closure tempVar14=new RoundTripSparseObjectNested.Closure(); + tempVar14.Col=col; + tempVar14.Prop=prop.clone(); + tempVar14.Expected=expected.clone(); + tangible.RefObjecttempRef_row4=new tangible.RefObject(row); + tangible.RefObjecttempRef_root=new tangible.RefObject(root); + this.LayoutCodeSwitch(col.Type.LayoutCode, + tempRef_row4,tempRef_root,tempVar14.clone()); + root=tempRef_root.argValue; + row=tempRef_row4.argValue; + } + } + } + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaSparseArray() +public final void ParseSchemaSparseArray() + { + // Test all fixed column types. + RoundTripSparseArray.Expected tempVar=new RoundTripSparseArray.Expected(); + tempVar.Json="array[null]"; + tempVar.Type=LayoutType.Null; + tempVar.Value=new ArrayList(Arrays.asList(NullValue.Default,NullValue.Default,NullValue.Default)); + RoundTripSparseArray.Expected tempVar2=new RoundTripSparseArray.Expected(); + tempVar2.Json="array[bool]"; + tempVar2.Type=LayoutType.Boolean; + tempVar2.Value=new ArrayList(Arrays.asList(true,false,true)); + RoundTripSparseArray.Expected tempVar3=new RoundTripSparseArray.Expected(); + tempVar3.Json="array[int8]"; + tempVar3.Type=LayoutType.Int8; + tempVar3.Value=new ArrayList(Arrays.asList((byte)42,(byte)43,(byte)44)); + RoundTripSparseArray.Expected tempVar4=new RoundTripSparseArray.Expected(); + tempVar4.Json="array[int16]"; + tempVar4.Type=LayoutType.Int16; + tempVar4.Value=new ArrayList(Arrays.asList((short)42,(short)43,(short)44)); + RoundTripSparseArray.Expected tempVar5=new RoundTripSparseArray.Expected(); + tempVar5.Json="array[int32]"; + tempVar5.Type=LayoutType.Int32; + tempVar5.Value=new ArrayList(Arrays.asList(42,43,44)); + RoundTripSparseArray.Expected tempVar6=new RoundTripSparseArray.Expected(); + tempVar6.Json="array[int64]"; + tempVar6.Type=LayoutType.Int64; + tempVar6.Value=new ArrayList(Arrays.asList(42L,43L,44L)); + RoundTripSparseArray.Expected tempVar7=new RoundTripSparseArray.Expected(); + tempVar7.Json="array[uint8]"; + tempVar7.Type=LayoutType.UInt8; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar7.Value = new List { (byte)42, (byte)43, (byte)44 }; + tempVar7.Value=new ArrayList(Arrays.asList((byte)42,(byte)43,(byte)44)); + RoundTripSparseArray.Expected tempVar8=new RoundTripSparseArray.Expected(); + tempVar8.Json="array[uint16]"; + tempVar8.Type=LayoutType.UInt16; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar8.Value = new List { (ushort)42, (ushort)43, (ushort)44 }; + tempVar8.Value=new ArrayList(Arrays.asList((short)42,(short)43,(short)44)); + RoundTripSparseArray.Expected tempVar9=new RoundTripSparseArray.Expected(); + tempVar9.Json="array[uint32]"; + tempVar9.Type=LayoutType.UInt32; + tempVar9.Value=new ArrayList(Arrays.asList(42,43,44)); + RoundTripSparseArray.Expected tempVar10=new RoundTripSparseArray.Expected(); + tempVar10.Json="array[uint64]"; + tempVar10.Type=LayoutType.UInt64; + tempVar10.Value=new ArrayList(Arrays.asList(42,43,44)); + RoundTripSparseArray.Expected tempVar11=new RoundTripSparseArray.Expected(); + tempVar11.Json="array[varint]"; + tempVar11.Type=LayoutType.VarInt; + tempVar11.Value=new ArrayList(Arrays.asList(42L,43L,44L)); + RoundTripSparseArray.Expected tempVar12=new RoundTripSparseArray.Expected(); + tempVar12.Json="array[varuint]"; + tempVar12.Type=LayoutType.VarUInt; + tempVar12.Value=new ArrayList(Arrays.asList(42,43,44)); + RoundTripSparseArray.Expected tempVar13=new RoundTripSparseArray.Expected(); + tempVar13.Json="array[float32]"; + tempVar13.Type=LayoutType.Float32; + tempVar13.Value=new ArrayList(Arrays.asList(4.2F,4.3F,4.4F)); + RoundTripSparseArray.Expected tempVar14=new RoundTripSparseArray.Expected(); + tempVar14.Json="array[float64]"; + tempVar14.Type=LayoutType.Float64; + tempVar14.Value=new ArrayList(Arrays.asList(4.2,4.3,4.4)); + RoundTripSparseArray.Expected tempVar15=new RoundTripSparseArray.Expected(); + tempVar15.Json="array[float128]"; + tempVar15.Type=LayoutType.Float128; + tempVar15.Value=new ArrayList(Arrays.asList(new Float128(0,42),new Float128(0,43),new Float128(0,44))); + RoundTripSparseArray.Expected tempVar16=new RoundTripSparseArray.Expected(); + tempVar16.Json="array[decimal]"; + tempVar16.Type=LayoutType.Decimal; + tempVar16.Value=new ArrayList(Arrays.asList(4.2,4.3,4.4)); + RoundTripSparseArray.Expected tempVar17=new RoundTripSparseArray.Expected(); + tempVar17.Json="array[datetime]"; + tempVar17.Type=LayoutType.DateTime; + tempVar17.Value=new ArrayList(Arrays.asList(LocalDateTime.UtcNow,LocalDateTime.UtcNow.AddTicks(1), + LocalDateTime.UtcNow.AddTicks(2))); + RoundTripSparseArray.Expected tempVar18=new RoundTripSparseArray.Expected(); + tempVar18.Json="array[unixdatetime]"; + tempVar18.Type=LayoutType.UnixDateTime; + tempVar18.Value=new ArrayList(Arrays.asList(new UnixDateTime(1),new UnixDateTime(2),new UnixDateTime(3))); + RoundTripSparseArray.Expected tempVar19=new RoundTripSparseArray.Expected(); + tempVar19.Json="array[guid]"; + tempVar19.Type=LayoutType.Guid; + tempVar19.Value=new ArrayList(Arrays.asList(UUID.NewGuid(),UUID.NewGuid(),UUID.NewGuid())); + RoundTripSparseArray.Expected tempVar20=new RoundTripSparseArray.Expected(); + tempVar20.Json="array[mongodbobjectid]"; + tempVar20.Type=LayoutType.MongoDbObjectId; + tempVar20.Value=new ArrayList(Arrays.asList(new MongoDbObjectId(0,1),new MongoDbObjectId(0,2), + new MongoDbObjectId(0,3))); + RoundTripSparseArray.Expected tempVar21=new RoundTripSparseArray.Expected(); + tempVar21.Json="array[utf8]"; + tempVar21.Type=LayoutType.Utf8; + tempVar21.Value=new ArrayList(Arrays.asList("abc","def","xyz")); + RoundTripSparseArray.Expected tempVar22=new RoundTripSparseArray.Expected(); + tempVar22.Json="array[binary]"; + tempVar22.Type=LayoutType.Binary; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar22.Value = new List { new byte[] { 0x01, 0x02 }, new byte[] { 0x03, 0x04 }, new + // byte[] { 0x05, 0x06 } }; + tempVar22.Value=new ArrayList(Arrays.asList(new Byte[]{0x01,0x02},new byte[]{0x03,0x04},new byte[]{0x05, + 0x06})); + RoundTripSparseArray.Expected[]expectedSchemas= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseArray.Expected[]{tempVar,tempVar2,tempVar3,tempVar4,tempVar5,tempVar6,tempVar7,tempVar8,tempVar9,tempVar10,tempVar11,tempVar12,tempVar13,tempVar14,tempVar15,tempVar16,tempVar17,tempVar18,tempVar19,tempVar20,tempVar21,tempVar22}; + + RowBuffer row=new RowBuffer(LayoutCompilerUnitTests.InitialRowSize); + for(RoundTripSparseArray.Expected expected:expectedSchemas) + { + for(java.lang.Class arrT:new java.lang.Class[]{LayoutTypedArray.class,LayoutArray.class}) + { + String arrayColumnSchema="{'path': 'a', 'type': {'type': 'array', 'items': {'type': 'any'}} }"; + if(arrT==LayoutTypedArray.class) + { + arrayColumnSchema=String.format("{'path': 'a', 'type': {'type': 'array',"+"\r\n"+ + " 'items': {'type': '%1$s', 'nullable': " + + "false }} }",expected.Type.getName()); + } + + String tableSchema=String.format("{'name': 'table', 'id': -1, 'type': 'schema', 'properties': [%1$s] }", + arrayColumnSchema); + Schema s=Schema.Parse(tableSchema); + Namespace tempVar23=new Namespace(); + tempVar23.setSchemas(new ArrayList(Arrays.asList(s))); + LayoutResolverNamespace resolver=new LayoutResolverNamespace(tempVar23); + Layout layout=resolver.Resolve(new SchemaId(-1)); + LayoutColumn arrCol; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + boolean found=layout.TryFind("a",out arrCol); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Sparse,arrCol.Storage,"Json: {0}",expected.Json); + + // Try writing a row using the layout. + row.Reset(); + row.InitLayout(HybridRowVersion.V1,layout,resolver); + + HybridRowHeader header=row.getHeader().clone(); + assert HybridRowVersion.V1==header.getVersion(); + assert layout.getSchemaId().clone()==header.getSchemaId().clone(); + + tangible.RefObjecttempRef_row=new tangible.RefObject(row); + RowCursor root=RowCursor.Create(tempRef_row); + row=tempRef_row.argValue; + RoundTripSparseArray.Closure tempVar24=new RoundTripSparseArray.Closure(); + tempVar24.ArrCol=arrCol; + tempVar24.Expected=expected.clone(); + tangible.RefObjecttempRef_row2=new tangible.RefObject(row); + tangible.RefObjecttempRef_root=new tangible.RefObject(root); + this.LayoutCodeSwitch(expected.Type.LayoutCode,tempRef_row2, + tempRef_root,tempVar24.clone()); + root=tempRef_root.argValue; + row=tempRef_row2.argValue; + } + } + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")][SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1139", +// Justification = "Need to control the binary ordering.")] public void ParseSchemaSparseSet() +public final void ParseSchemaSparseSet() + { + // Test all fixed column types. + RoundTripSparseSet.Expected tempVar=new RoundTripSparseSet.Expected(); + tempVar.Json="set[null]"; + tempVar.Type=LayoutType.Null; + tempVar.Value=new ArrayList(Arrays.asList(NullValue.Default)); + RoundTripSparseSet.Expected tempVar2=new RoundTripSparseSet.Expected(); + tempVar2.Json="set[bool]"; + tempVar2.Type=LayoutType.Boolean; + tempVar2.Value=new ArrayList(Arrays.asList(false,true)); + RoundTripSparseSet.Expected tempVar3=new RoundTripSparseSet.Expected(); + tempVar3.Json="set[int8]"; + tempVar3.Type=LayoutType.Int8; + tempVar3.Value=new ArrayList(Arrays.asList((byte)42,(byte)43,(byte)44)); + RoundTripSparseSet.Expected tempVar4=new RoundTripSparseSet.Expected(); + tempVar4.Json="set[int16]"; + tempVar4.Type=LayoutType.Int16; + tempVar4.Value=new ArrayList(Arrays.asList((short)42,(short)43,(short)44)); + RoundTripSparseSet.Expected tempVar5=new RoundTripSparseSet.Expected(); + tempVar5.Json="set[int32]"; + tempVar5.Type=LayoutType.Int32; + tempVar5.Value=new ArrayList(Arrays.asList(42,43,44)); + RoundTripSparseSet.Expected tempVar6=new RoundTripSparseSet.Expected(); + tempVar6.Json="set[int64]"; + tempVar6.Type=LayoutType.Int64; + tempVar6.Value=new ArrayList(Arrays.asList(42L,43L,44L)); + RoundTripSparseSet.Expected tempVar7=new RoundTripSparseSet.Expected(); + tempVar7.Json="set[uint8]"; + tempVar7.Type=LayoutType.UInt8; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar7.Value = new List { (byte)42, (byte)43, (byte)44 }; + tempVar7.Value=new ArrayList(Arrays.asList((byte)42,(byte)43,(byte)44)); + RoundTripSparseSet.Expected tempVar8=new RoundTripSparseSet.Expected(); + tempVar8.Json="set[uint16]"; + tempVar8.Type=LayoutType.UInt16; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar8.Value = new List { (ushort)42, (ushort)43, (ushort)44 }; + tempVar8.Value=new ArrayList(Arrays.asList((short)42,(short)43,(short)44)); + RoundTripSparseSet.Expected tempVar9=new RoundTripSparseSet.Expected(); + tempVar9.Json="set[uint32]"; + tempVar9.Type=LayoutType.UInt32; + tempVar9.Value=new ArrayList(Arrays.asList(42,43,44)); + RoundTripSparseSet.Expected tempVar10=new RoundTripSparseSet.Expected(); + tempVar10.Json="set[uint64]"; + tempVar10.Type=LayoutType.UInt64; + tempVar10.Value=new ArrayList(Arrays.asList(42,43,44)); + RoundTripSparseSet.Expected tempVar11=new RoundTripSparseSet.Expected(); + tempVar11.Json="set[varint]"; + tempVar11.Type=LayoutType.VarInt; + tempVar11.Value=new ArrayList(Arrays.asList(42L,43L,44L)); + RoundTripSparseSet.Expected tempVar12=new RoundTripSparseSet.Expected(); + tempVar12.Json="set[varuint]"; + tempVar12.Type=LayoutType.VarUInt; + tempVar12.Value=new ArrayList(Arrays.asList(42,43,44)); + RoundTripSparseSet.Expected tempVar13=new RoundTripSparseSet.Expected(); + tempVar13.Json="set[float32]"; + tempVar13.Type=LayoutType.Float32; + tempVar13.Value=new ArrayList(Arrays.asList(4.2F,4.3F,4.4F)); + RoundTripSparseSet.Expected tempVar14=new RoundTripSparseSet.Expected(); + tempVar14.Json="set[float64]"; + tempVar14.Type=LayoutType.Float64; + tempVar14.Value=new ArrayList(Arrays.asList((double)0xAAAAAAAAAAAAAAAA,(double)0xBBBBBBBBBBBBBBBB, + (double)0xCCCCCCCCCCCCCCCC)); + RoundTripSparseSet.Expected tempVar15=new RoundTripSparseSet.Expected(); + tempVar15.Json="set[decimal]"; + tempVar15.Type=LayoutType.Decimal; + tempVar15.Value=new ArrayList(Arrays.asList(4.2,4.3,4.4)); + RoundTripSparseSet.Expected tempVar16=new RoundTripSparseSet.Expected(); + tempVar16.Json="set[datetime]"; + tempVar16.Type=LayoutType.DateTime; + tempVar16.Value=new ArrayList(Arrays.asList(LocalDateTime.of(1,DateTimeKind.Unspecified), + LocalDateTime.of(2,DateTimeKind.Unspecified),LocalDateTime.of(3,DateTimeKind.Unspecified))); + RoundTripSparseSet.Expected tempVar17=new RoundTripSparseSet.Expected(); + tempVar17.Json="set[guid]"; + tempVar17.Type=LayoutType.Guid; + tempVar17.Value=new ArrayList(Arrays.asList(UUID.fromString("AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA"), + UUID.fromString("BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB"),UUID.fromString("CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC"))); + RoundTripSparseSet.Expected tempVar18=new RoundTripSparseSet.Expected(); + tempVar18.Json="set[utf8]"; + tempVar18.Type=LayoutType.Utf8; + tempVar18.Value=new ArrayList(Arrays.asList("abc","def","xyz")); + RoundTripSparseSet.Expected tempVar19=new RoundTripSparseSet.Expected(); + tempVar19.Json="set[binary]"; + tempVar19.Type=LayoutType.Binary; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar19.Value = new List { new byte[] { 0x01, 0x02 }, new byte[] { 0x03, 0x04 }, new + // byte[] { 0x05, 0x06 } }; + tempVar19.Value=new ArrayList(Arrays.asList(new Byte[]{0x01,0x02},new byte[]{0x03,0x04},new byte[]{0x05, + 0x06})); + RoundTripSparseSet.Expected[]expectedSchemas= + new Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.LayoutCompilerUnitTests.RoundTripSparseSet.Expected[]{tempVar,tempVar2,tempVar3,tempVar4,tempVar5,tempVar6,tempVar7,tempVar8,tempVar9,tempVar10,tempVar11,tempVar12,tempVar13,tempVar14,tempVar15,tempVar16,tempVar17,tempVar18,tempVar19}; + + RowBuffer row=new RowBuffer(LayoutCompilerUnitTests.InitialRowSize); + for(RoundTripSparseSet.Expected expected:expectedSchemas) + { + for(java.lang.Class setT:new java.lang.Class[]{LayoutTypedSet.class}) + { + String setColumnSchema="{'path': 'a', 'type': {'type': 'set', 'items': {'type': 'any'}} }"; + if(setT==LayoutTypedSet.class) + { + setColumnSchema=String.format("{'path': 'a', 'type': {'type': 'set', "+"\r\n"+ + " 'items': {'type': '%1$s', 'nullable': " + + "false }} }",expected.Type.getName()); + } + + String tableSchema=String.format("{'name': 'table', 'id': -1, 'type': 'schema', 'properties': [%1$s] }", + setColumnSchema); + Schema s=Schema.Parse(tableSchema); + Namespace tempVar20=new Namespace(); + tempVar20.setSchemas(new ArrayList(Arrays.asList(s))); + LayoutResolverNamespace resolver=new LayoutResolverNamespace(tempVar20); + Layout layout=resolver.Resolve(new SchemaId(-1)); + LayoutColumn setCol; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + boolean found=layout.TryFind("a",out setCol); + Assert.IsTrue(found,"Json: {0}",expected.Json); + Assert.AreEqual(StorageKind.Sparse,setCol.Storage,"Json: {0}",expected.Json); + + // Try writing a row using the layout. + row.Reset(); + row.InitLayout(HybridRowVersion.V1,layout,resolver); + + HybridRowHeader header=row.getHeader().clone(); + assert HybridRowVersion.V1==header.getVersion(); + assert layout.getSchemaId().clone()==header.getSchemaId().clone(); + + tangible.RefObjecttempRef_row=new tangible.RefObject(row); + RowCursor root=RowCursor.Create(tempRef_row); + row=tempRef_row.argValue; + RoundTripSparseSet.Closure tempVar21=new RoundTripSparseSet.Closure(); + tempVar21.SetCol=setCol; + tempVar21.Expected=expected.clone(); + tangible.RefObjecttempRef_row2=new tangible.RefObject(row); + tangible.RefObjecttempRef_root=new tangible.RefObject(root); + this.LayoutCodeSwitch(expected.Type.LayoutCode,tempRef_row2, + tempRef_root,tempVar21.clone()); + root=tempRef_root.argValue; + row=tempRef_row2.argValue; + } + } + } + +/** + * Ensure that a parent scope exists in the row. + * + * @param row The row to create the desired scope. + * @param root The root scope. + * @param col The scope to create. + * @param tag A string to tag errors with. + * @return The enclosing scope. + */ +private static RowCursor EnsureScope(tangible.RefObject row,tangible.RefObject root, + LayoutColumn col,String tag) + { + if(col==null) + { + return root.argValue.clone(); + } + + RowCursor parentScope=LayoutCompilerUnitTests.EnsureScope(row,root,col.getParent(),tag); + + azure.data.cosmos.serialization.hybridrow.layouts.LayoutType tempVar=col.getType(); + LayoutObject pT=tempVar instanceof LayoutObject?(LayoutObject)tempVar:null; + assert pT!=null; + RowCursor field; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot + // be converted using the 'OutObject' helper class unless the method is within the code being modified: + parentScope.Clone(out field).Find(row,col.getPath()); + tangible.RefObjecttempRef_field=new tangible.RefObject(field); + RowCursor scope; + tangible.OutObjecttempOut_scope=new tangible.OutObject(); + Result r=pT.ReadScope(row,tempRef_field,tempOut_scope); + scope=tempOut_scope.argValue; + field=tempRef_field.argValue; + if(r==Result.NotFound) + { + tangible.RefObjecttempRef_field2=new tangible.RefObject(field); + tangible.OutObjecttempOut_scope2=new tangible.OutObject(); + r=pT.WriteScope(row,tempRef_field2,col.getTypeArgs().clone(),tempOut_scope2); + scope=tempOut_scope2.argValue; + field=tempRef_field2.argValue; + } + + ResultAssert.IsSuccess(r,tag); + return scope; + } + +// TODO: C# TO JAVA CONVERTER: The C# 'new()' constraint has no equivalent in Java: +//ORIGINAL LINE: private void LayoutCodeSwitch(LayoutCode code, ref RowBuffer row, ref +// RowCursor scope, TClosure closure) where TDispatcher : TestActionDispatcher, new() +private, TClosure> void LayoutCodeSwitch(LayoutCode code, + tangible.RefObject row,tangible.RefObject scope,TClosure closure) + { + TDispatcher dispatcher=new TDispatcher(); + switch(code) + { + case Null: + dispatcher.Dispatch(row,scope,closure); + break; + case Boolean: + dispatcher.Dispatch(row,scope,closure); + break; + case Int8: + dispatcher.Dispatch(row,scope,closure); + break; + case Int16: + dispatcher.Dispatch(row,scope,closure); + break; + case Int32: + dispatcher.Dispatch(row,scope,closure); + break; + case Int64: + dispatcher.Dispatch(row,scope,closure); + break; + case UInt8: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: dispatcher.Dispatch(ref row, ref scope, closure); + dispatcher.Dispatch(row,scope,closure); + break; + case UInt16: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: dispatcher.Dispatch(ref row, ref scope, closure); + dispatcher.Dispatch(row,scope,closure); + break; + case UInt32: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: dispatcher.Dispatch(ref row, ref scope, closure); + dispatcher.Dispatch(row,scope,closure); + break; + case UInt64: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: dispatcher.Dispatch(ref row, ref scope, closure); + dispatcher.Dispatch(row,scope,closure); + break; + case VarInt: + dispatcher.Dispatch(row,scope,closure); + break; + case VarUInt: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: dispatcher.Dispatch(ref row, ref scope, closure); + dispatcher.Dispatch(row,scope,closure); + break; + case Float32: + dispatcher.Dispatch(row,scope,closure); + break; + case Float64: + dispatcher.Dispatch(row,scope,closure); + break; + case Float128: + dispatcher.Dispatch(row,scope,closure); + break; + case Decimal: + dispatcher.Dispatch(row,scope,closure); + break; + case DateTime: + dispatcher.Dispatch(row,scope,closure); + break; + case UnixDateTime: + dispatcher.Dispatch(row,scope,closure); + break; + case Guid: + dispatcher.Dispatch(row,scope,closure); + break; + case MongoDbObjectId: + dispatcher.Dispatch(row,scope,closure); + break; + case Utf8: + dispatcher.Dispatch(row,scope,closure); + break; + case Binary: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: dispatcher.Dispatch(ref row, ref scope, closure); + dispatcher.Dispatch(row,scope,closure); + break; + case ObjectScope: + dispatcher.DispatchObject(row,scope,closure); + break; +default: + Contract.Assert(false,String.format("Unknown type will be ignored: %1$s",code)); + break; + } + } + +private final static class RoundTripFixed extends TestActionDispatcher { + @Override + public void Dispatch(tangible.RefObject row, tangible.RefObject root, + Closure closure) { + LayoutColumn col = closure.Col; + Expected expected = closure.Expected.clone(); + Result r; + TValue value; + + System.out.printf("%1$s" + "\r\n", expected.Json); + TLayout t = (TLayout)col.getType(); + if (azure.data.cosmos.serialization.hybridrow.layouts.LayoutBit.opNotEquals(col.getNullBit().clone(), + LayoutBit.Invalid)) { + tangible.OutObject tempOut_value = new tangible.OutObject(); + r = t.ReadFixed(row, root, col, tempOut_value); + value = tempOut_value.argValue; + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + } else { + tangible.OutObject tempOut_value2 = new tangible.OutObject(); + r = t.ReadFixed(row, root, col, tempOut_value2); + value = tempOut_value2.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + boolean tempVar = expected.Default instanceof Array; + Array defaultArray = tempVar ? (Array)expected.Default : null; + if (tempVar) { + CollectionAssert.AreEqual(defaultArray, (Collection)value, "Json: {0}", expected.Json); + } else { + Assert.AreEqual(expected.Default, value, "Json: {0}", expected.Json); + } + } + + r = t.WriteFixed(row, root, col, (TValue)expected.Value); + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + tangible.OutObject tempOut_value3 = new tangible.OutObject(); + r = t.ReadFixed(row, root, col, tempOut_value3); + value = tempOut_value3.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + boolean tempVar2 = expected.Value instanceof Array; + Array array = tempVar2 ? (Array)expected.Value : null; + if (tempVar2) { + CollectionAssert.AreEqual(array, (Collection)value, "Json: {0}", expected.Json); + } else { + Assert.AreEqual(expected.Value, value, "Json: {0}", expected.Json); + } + + RowCursor roRoot; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.AsReadOnly(out roRoot); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.InsufficientPermissions(t.WriteFixed(row, ref roRoot, col, (TValue)expected.Value)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.InsufficientPermissions(t.DeleteFixed(row, ref roRoot, col)); + + if (azure.data.cosmos.serialization.hybridrow.layouts.LayoutBit.opNotEquals(col.getNullBit().clone(), + LayoutBit.Invalid)) { + ResultAssert.IsSuccess(t.DeleteFixed(row, root, col)); + } else { + ResultAssert.TypeMismatch(t.DeleteFixed(row, root, col)); + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Closure + public final static class Closure { + public LayoutColumn Col; + public Expected Expected = new Expected(); + + public Closure clone() { + Closure varCopy = new Closure(); + + varCopy.Col = this.Col; + varCopy.Expected = this.Expected.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Expected + public final static class Expected { + public Object Default; + public String Json; + public int Length; + public String TypeName; + public Object Value; + + public Expected clone() { + Expected varCopy = new Expected(); + + varCopy.TypeName = this.TypeName; + varCopy.Json = this.Json; + varCopy.Value = this.Value; + varCopy.Default = this.Default; + varCopy.Length = this.Length; + + return varCopy; + } + } +} + +private final static class RoundTripSparseArray extends TestActionDispatcher { + @Override + public void Dispatch(tangible.RefObject row, tangible.RefObject root, + Closure closure) { + LayoutColumn arrCol = closure.ArrCol; + azure.data.cosmos.serialization.hybridrow.layouts.LayoutType tempVar = arrCol.getType(); + LayoutIndexedScope arrT = tempVar instanceof LayoutIndexedScope ? (LayoutIndexedScope)tempVar : null; + Expected expected = closure.Expected.clone(); + String tag = String.format("Json: %1$s, Array: %2$s", expected.Json, arrCol.getType().getName()); + + System.out.println(tag); + Assert.IsNotNull(arrT, tag); + + TLayout t = (TLayout)expected.Type; + + // Verify the array doesn't yet exist. + RowCursor field; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out field).Find(row, arrCol.getPath()); + tangible.RefObject tempRef_field = + new tangible.RefObject(field); + RowCursor scope; + tangible.OutObject tempOut_scope = + new tangible.OutObject(); + Result r = arrT.ReadScope(row, tempRef_field, tempOut_scope); + scope = tempOut_scope.argValue; + field = tempRef_field.argValue; + ResultAssert.NotFound(r, tag); + + // Write the array. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = arrT.WriteScope(row, ref field, arrCol.getTypeArgs().clone(), out scope); + ResultAssert.IsSuccess(r, tag); + + // Verify the nested field doesn't yet appear within the new scope. + assert !scope.MoveNext(row); + TValue value; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref scope, out value); + ResultAssert.NotFound(r, tag); + + // Write the nested fields. + RowCursor elm; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + scope.Clone(out elm); + for (Object item : expected.Value) { + // Write the ith index. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.WriteSparse(row, ref elm, (TValue)item); + ResultAssert.IsSuccess(r, tag); + + // Move cursor to the ith+1 index. + assert !elm.MoveNext(row); + } + + // Read the array and the nested column, validate the nested column has the proper value. + tangible.RefObject tempRef_field2 = + new tangible.RefObject(field); + RowCursor scope2; + tangible.OutObject tempOut_scope2 = + new tangible.OutObject(); + r = arrT.ReadScope(row, tempRef_field2, tempOut_scope2); + scope2 = tempOut_scope2.argValue; + field = tempRef_field2.argValue; + ResultAssert.IsSuccess(r, tag); + Assert.AreEqual(scope.ScopeType, scope2.ScopeType, tag); + Assert.AreEqual(scope.start, scope2.start, tag); + Assert.AreEqual(scope.Immutable, scope2.Immutable, tag); + + // Read the nested fields + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + scope2.Clone(out elm); + for (Object item : expected.Value) { + assert elm.MoveNext(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.ReadSparse(row, ref elm, out value); + ResultAssert.IsSuccess(r, tag); + boolean tempVar2 = item instanceof Array; + Array array = tempVar2 ? (Array)item : null; + if (tempVar2) { + CollectionAssert.AreEqual(array, (Collection)value, tag); + } else { + Assert.AreEqual((TValue)item, value, tag); + } + } + + // Delete an item. + int indexToDelete = 1; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert scope2.Clone(out elm).MoveTo(row, indexToDelete); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.DeleteSparse(row, ref elm); + ResultAssert.IsSuccess(r, tag); + ArrayList remainingValues = new ArrayList(expected.Value); + remainingValues.remove(indexToDelete); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + scope2.Clone(out elm); + for (Object item : remainingValues) { + assert elm.MoveNext(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.ReadSparse(row, ref elm, out value); + ResultAssert.IsSuccess(r, tag); + boolean tempVar3 = item instanceof Array; + Array array = tempVar3 ? (Array)item : null; + if (tempVar3) { + CollectionAssert.AreEqual(array, (Collection)value, tag); + } else { + Assert.AreEqual(item, value, tag); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert !scope2.Clone(out elm).MoveTo(row, remainingValues.size()); + + RowCursor roRoot; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.AsReadOnly(out roRoot).Find(row, arrCol.getPath()); + tangible.RefObject tempRef_roRoot = + new tangible.RefObject(roRoot); + ResultAssert.InsufficientPermissions(arrT.DeleteScope(row, tempRef_roRoot)); + roRoot = tempRef_roRoot.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.InsufficientPermissions(arrT.WriteScope(row, ref roRoot, arrCol.getTypeArgs().clone(), + out scope2)); + + // Overwrite the whole scope. + tangible.RefObject tempRef_field3 = + new tangible.RefObject(field); + r = LayoutType.Null.WriteSparse(row, tempRef_field3, NullValue.Default); + field = tempRef_field3.argValue; + ResultAssert.IsSuccess(r, tag); + tangible.RefObject tempRef_field4 = + new tangible.RefObject(field); + RowCursor _; + tangible.OutObject tempOut__ = + new tangible.OutObject(); + r = arrT.ReadScope(row, tempRef_field4, tempOut__); + _ = tempOut__.argValue; + field = tempRef_field4.argValue; + ResultAssert.TypeMismatch(r, tag); + tangible.RefObject tempRef_field5 = + new tangible.RefObject(field); + r = arrT.DeleteScope(row, tempRef_field5); + field = tempRef_field5.argValue; + ResultAssert.TypeMismatch(r, "Json: {0}", expected.Json); + + // Overwrite it again, then delete it. + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = arrT.WriteScope(row, ref field, arrCol.getTypeArgs().clone(), out _, UpdateOptions.Update); + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + tangible.RefObject tempRef_field6 = + new tangible.RefObject(field); + r = arrT.DeleteScope(row, tempRef_field6); + field = tempRef_field6.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + tangible.RefObject tempRef_field7 = + new tangible.RefObject(field); + RowCursor _; + tangible.OutObject tempOut__2 = + new tangible.OutObject(); + r = arrT.ReadScope(row, tempRef_field7, tempOut__2); + _ = tempOut__2.argValue; + field = tempRef_field7.argValue; + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Closure + public final static class Closure { + public LayoutColumn ArrCol; + public Expected Expected = new Expected(); + + public Closure clone() { + Closure varCopy = new Closure(); + + varCopy.ArrCol = this.ArrCol; + varCopy.Expected = this.Expected.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Expected + public final static class Expected { + public String Json; + public LayoutType Type; + public ArrayList Value; + + public Expected clone() { + Expected varCopy = new Expected(); + + varCopy.Json = this.Json; + varCopy.Type = this.Type; + varCopy.Value = this.Value; + + return varCopy; + } + } +} + +private final static class RoundTripSparseObject extends TestActionDispatcher { + @Override + public void Dispatch(tangible.RefObject row, tangible.RefObject root, + Closure closure) { + LayoutColumn objCol = closure.ObjCol; + azure.data.cosmos.serialization.hybridrow.layouts.LayoutType tempVar = objCol.getType(); + LayoutObject objT = tempVar instanceof LayoutObject ? (LayoutObject)tempVar : null; + LayoutColumn col = closure.Col; + Expected expected = closure.Expected.clone(); + + System.out.printf("%1$s" + "\r\n", col.getType().getName()); + Assert.IsNotNull(objT, "Json: {0}", expected.Json); + Assert.AreEqual(objCol, col.getParent(), "Json: {0}", expected.Json); + + TLayout t = (TLayout)col.getType(); + + // Attempt to read the object and the nested column. + RowCursor field; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out field).Find(row, objCol.getPath()); + tangible.RefObject tempRef_field = + new tangible.RefObject(field); + RowCursor scope; + tangible.OutObject tempOut_scope = + new tangible.OutObject(); + Result r = objT.ReadScope(row, tempRef_field, tempOut_scope); + scope = tempOut_scope.argValue; + field = tempRef_field.argValue; + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + + // Write the object and the nested column. + tangible.RefObject tempRef_field2 = + new tangible.RefObject(field); + tangible.OutObject tempOut_scope2 = + new tangible.OutObject(); + r = objT.WriteScope(row, tempRef_field2, objCol.getTypeArgs().clone(), tempOut_scope2); + scope = tempOut_scope2.argValue; + field = tempRef_field2.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + + // Verify the nested field doesn't yet appear within the new scope. + RowCursor nestedField; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + scope.Clone(out nestedField).Find(row, col.getPath()); + TValue value; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref nestedField, out value); + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + + // Write the nested field. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.WriteSparse(row, ref nestedField, (TValue)expected.Value); + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + + // Read the object and the nested column, validate the nested column has the proper value. + tangible.RefObject tempRef_field3 = + new tangible.RefObject(field); + RowCursor scope2; + tangible.OutObject tempOut_scope2 = + new tangible.OutObject(); + r = objT.ReadScope(row, tempRef_field3, tempOut_scope2); + scope2 = tempOut_scope2.argValue; + field = tempRef_field3.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + Assert.AreEqual(scope.ScopeType, scope2.ScopeType, "Json: {0}", expected.Json); + Assert.AreEqual(scope.start, scope2.start, "Json: {0}", expected.Json); + Assert.AreEqual(scope.Immutable, scope2.Immutable, "Json: {0}", expected.Json); + + // Read the nested field + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + scope2.Clone(out nestedField).Find(row, col.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref nestedField, out value); + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + boolean tempVar2 = expected.Value instanceof Array; + Array array = tempVar2 ? (Array)expected.Value : null; + if (tempVar2) { + CollectionAssert.AreEqual(array, (Collection)value, "Json: {0}", expected.Json); + } else { + Assert.AreEqual(expected.Value, value, "Json: {0}", expected.Json); + } + + RowCursor roRoot; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.AsReadOnly(out roRoot).Find(row, objCol.getPath()); + tangible.RefObject tempRef_roRoot = + new tangible.RefObject(roRoot); + ResultAssert.InsufficientPermissions(objT.DeleteScope(row, tempRef_roRoot)); + roRoot = tempRef_roRoot.argValue; + tangible.RefObject tempRef_roRoot2 = + new tangible.RefObject(roRoot); + tangible.OutObject tempOut_scope22 = + new tangible.OutObject(); + ResultAssert.InsufficientPermissions(objT.WriteScope(row, tempRef_roRoot2, objCol.getTypeArgs().clone(), + tempOut_scope22)); + scope2 = tempOut_scope22.argValue; + roRoot = tempRef_roRoot2.argValue; + + // Overwrite the whole scope. + tangible.RefObject tempRef_field4 = + new tangible.RefObject(field); + r = LayoutType.Null.WriteSparse(row, tempRef_field4, NullValue.Default); + field = tempRef_field4.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + tangible.RefObject tempRef_field5 = + new tangible.RefObject(field); + RowCursor _; + tangible.OutObject tempOut__ = + new tangible.OutObject(); + r = objT.ReadScope(row, tempRef_field5, tempOut__); + _ = tempOut__.argValue; + field = tempRef_field5.argValue; + ResultAssert.TypeMismatch(r, "Json: {0}", expected.Json); + tangible.RefObject tempRef_field6 = + new tangible.RefObject(field); + r = objT.DeleteScope(row, tempRef_field6); + field = tempRef_field6.argValue; + ResultAssert.TypeMismatch(r, "Json: {0}", expected.Json); + + // Overwrite it again, then delete it. + tangible.RefObject tempRef_field7 = + new tangible.RefObject(field); + RowCursor _; + tangible.OutObject tempOut__2 = + new tangible.OutObject(); + r = objT.WriteScope(row, tempRef_field7, objCol.getTypeArgs().clone(), tempOut__2, UpdateOptions.Update); + _ = tempOut__2.argValue; + field = tempRef_field7.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + tangible.RefObject tempRef_field8 = + new tangible.RefObject(field); + r = objT.DeleteScope(row, tempRef_field8); + field = tempRef_field8.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + tangible.RefObject tempRef_field9 = + new tangible.RefObject(field); + RowCursor _; + tangible.OutObject tempOut__3 = + new tangible.OutObject(); + r = objT.ReadScope(row, tempRef_field9, tempOut__3); + _ = tempOut__3.argValue; + field = tempRef_field9.argValue; + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Closure + public final static class Closure { + public LayoutColumn Col; + public Expected Expected = new Expected(); + public LayoutColumn ObjCol; + + public Closure clone() { + Closure varCopy = new Closure(); + + varCopy.ObjCol = this.ObjCol; + varCopy.Col = this.Col; + varCopy.Expected = this.Expected.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Expected + public final static class Expected { + public String Json; + public Object Value; + + public Expected clone() { + Expected varCopy = new Expected(); + + varCopy.Json = this.Json; + varCopy.Value = this.Value; + + return varCopy; + } + } +} + +private final static class RoundTripSparseObjectMulti extends TestActionDispatcher { + @Override + public void Dispatch(tangible.RefObject row, tangible.RefObject scope, + Closure closure) { + LayoutColumn col = closure.Col; + Property prop = closure.Prop.clone(); + Expected expected = closure.Expected.clone(); + String tag = String.format("Prop: %2$s: Json: %1$s", expected.Json, prop.Path); + + System.out.println(tag); + + TLayout t = (TLayout)col.getType(); + + // Verify the nested field doesn't yet appear within the new scope. + RowCursor nestedField; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + scope.argValue.Clone(out nestedField).Find(row, col.getPath()); + TValue value; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + Result r = t.ReadSparse(row, ref nestedField, out value); + Assert.IsTrue(r == Result.NotFound || r == Result.TypeMismatch, tag); + + // Write the nested field. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.WriteSparse(row, ref nestedField, (TValue)prop.Value); + ResultAssert.IsSuccess(r, tag); + + // Read the nested field + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref nestedField, out value); + ResultAssert.IsSuccess(r, tag); + boolean tempVar = prop.Value instanceof Array; + Array array = tempVar ? (Array)prop.Value : null; + if (tempVar) { + CollectionAssert.AreEqual(array, (Collection)value, tag); + } else { + Assert.AreEqual(prop.Value, value, tag); + } + + // Overwrite the nested field. + if (t instanceof LayoutNull) { + tangible.RefObject tempRef_nestedField = + new tangible.RefObject(nestedField); + r = LayoutType.Boolean.WriteSparse(row, tempRef_nestedField, false); + nestedField = tempRef_nestedField.argValue; + ResultAssert.IsSuccess(r, tag); + } else { + tangible.RefObject tempRef_nestedField2 = + new tangible.RefObject(nestedField); + r = LayoutType.Null.WriteSparse(row, tempRef_nestedField2, NullValue.Default); + nestedField = tempRef_nestedField2.argValue; + ResultAssert.IsSuccess(r, tag); + } + + // Verify nested field no longer there. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref nestedField, out value); + ResultAssert.TypeMismatch(r, tag); + } + + @Override + public void DispatchObject(tangible.RefObject row, tangible.RefObject scope, + Closure closure) { + LayoutColumn col = closure.Col; + Property prop = closure.Prop.clone(); + Expected expected = closure.Expected.clone(); + String tag = String.format("Prop: %2$s: Json: %1$s", expected.Json, prop.Path); + + System.out.println(tag); + + LayoutObject t = (LayoutObject)col.getType(); + + // Verify the nested field doesn't yet appear within the new scope. + RowCursor nestedField; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + scope.argValue.Clone(out nestedField).Find(row, col.getPath()); + tangible.RefObject tempRef_nestedField = + new tangible.RefObject(nestedField); + RowCursor scope2; + tangible.OutObject tempOut_scope2 = + new tangible.OutObject(); + Result r = t.ReadScope(row, tempRef_nestedField, tempOut_scope2); + scope2 = tempOut_scope2.argValue; + nestedField = tempRef_nestedField.argValue; + ResultAssert.NotFound(r, tag); + + // Write the nested field. + tangible.RefObject tempRef_nestedField2 = + new tangible.RefObject(nestedField); + tangible.OutObject tempOut_scope22 = + new tangible.OutObject(); + r = t.WriteScope(row, tempRef_nestedField2, col.getTypeArgs().clone(), tempOut_scope22); + scope2 = tempOut_scope22.argValue; + nestedField = tempRef_nestedField2.argValue; + ResultAssert.IsSuccess(r, tag); + + // Read the nested field + tangible.RefObject tempRef_nestedField3 = + new tangible.RefObject(nestedField); + RowCursor scope3; + tangible.OutObject tempOut_scope3 = + new tangible.OutObject(); + r = t.ReadScope(row, tempRef_nestedField3, tempOut_scope3); + scope3 = tempOut_scope3.argValue; + nestedField = tempRef_nestedField3.argValue; + ResultAssert.IsSuccess(r, tag); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Assert.AreEqual(scope2.AsReadOnly(out _).ScopeType, scope3.ScopeType, tag); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Assert.AreEqual(scope2.AsReadOnly(out _).start, scope3.start, tag); + + // Overwrite the nested field. + tangible.RefObject tempRef_nestedField4 = + new tangible.RefObject(nestedField); + r = LayoutType.Null.WriteSparse(row, tempRef_nestedField4, NullValue.Default); + nestedField = tempRef_nestedField4.argValue; + ResultAssert.IsSuccess(r, tag); + + // Verify nested field no longer there. + tangible.RefObject tempRef_nestedField5 = + new tangible.RefObject(nestedField); + tangible.OutObject tempOut_scope32 = + new tangible.OutObject(); + r = t.ReadScope(row, tempRef_nestedField5, tempOut_scope32); + scope3 = tempOut_scope32.argValue; + nestedField = tempRef_nestedField5.argValue; + ResultAssert.TypeMismatch(r, tag); + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Closure + public final static class Closure { + public LayoutColumn Col; + public Expected Expected = new Expected(); + public Property Prop = new Property(); + + public Closure clone() { + Closure varCopy = new Closure(); + + varCopy.Col = this.Col; + varCopy.Prop = this.Prop.clone(); + varCopy.Expected = this.Expected.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Expected + public final static class Expected { + public String Json; + public Property[] Props; + + public Expected clone() { + Expected varCopy = new Expected(); + + varCopy.Json = this.Json; + varCopy.Props = this.Props.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Property + public final static class Property { + public String Path; + public Object Value; + + public Property clone() { + Property varCopy = new Property(); + + varCopy.Path = this.Path; + varCopy.Value = this.Value; + + return varCopy; + } + } +} + +private final static class RoundTripSparseObjectNested extends TestActionDispatcher { + @Override + public void Dispatch(tangible.RefObject row, tangible.RefObject root, + Closure closure) { + LayoutColumn col = closure.Col; + Property prop = closure.Prop.clone(); + Expected expected = closure.Expected.clone(); + String tag = String.format("Prop: %2$s: Json: %1$s", expected.Json, prop.Path); + + System.out.println(tag); + + TLayout t = (TLayout)col.getType(); + + // Ensure scope exists. + RowCursor scope = LayoutCompilerUnitTests.EnsureScope(row, root, col.getParent(), tag); + + // Write the nested field. + RowCursor field; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + scope.Clone(out field).Find(row, col.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + Result r = t.WriteSparse(row, ref field, (TValue)prop.Value); + ResultAssert.IsSuccess(r, tag); + + // Read the nested field + TValue value; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref field, out value); + ResultAssert.IsSuccess(r, tag); + boolean tempVar = prop.Value instanceof Array; + Array array = tempVar ? (Array)prop.Value : null; + if (tempVar) { + CollectionAssert.AreEqual(array, (Collection)value, tag); + } else { + Assert.AreEqual(prop.Value, value, tag); + } + + // Overwrite the nested field. + if (t instanceof LayoutNull) { + tangible.RefObject tempRef_field = + new tangible.RefObject(field); + r = LayoutType.Boolean.WriteSparse(row, tempRef_field, false); + field = tempRef_field.argValue; + ResultAssert.IsSuccess(r, tag); + } else { + tangible.RefObject tempRef_field2 = + new tangible.RefObject(field); + r = LayoutType.Null.WriteSparse(row, tempRef_field2, NullValue.Default); + field = tempRef_field2.argValue; + ResultAssert.IsSuccess(r, tag); + } + + // Verify nested field no longer there. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref field, out value); + ResultAssert.TypeMismatch(r, tag); + } + + @Override + public void DispatchObject(tangible.RefObject row, tangible.RefObject root, Closure closure) { + LayoutColumn col = closure.Col; + Property prop = closure.Prop.clone(); + Expected expected = closure.Expected.clone(); + String tag = String.format("Prop: %2$s: Json: %1$s", expected.Json, prop.Path); + + System.out.println(tag); + + // Ensure scope exists. + RowCursor scope = LayoutCompilerUnitTests.EnsureScope(row, root, col, tag); + assert root.argValue.clone() != scope.clone(); + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Closure + public final static class Closure { + public LayoutColumn Col; + public Expected Expected = new Expected(); + public Property Prop = new Property(); + + public Closure clone() { + Closure varCopy = new Closure(); + + varCopy.Col = this.Col; + varCopy.Prop = this.Prop.clone(); + varCopy.Expected = this.Expected.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Expected + public final static class Expected { + public String Json; + public Property[] Props; + + public Expected clone() { + Expected varCopy = new Expected(); + + varCopy.Json = this.Json; + varCopy.Props = this.Props.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Property + public final static class Property { + public String Path; + public Object Value; + + public Property clone() { + Property varCopy = new Property(); + + varCopy.Path = this.Path; + varCopy.Value = this.Value; + + return varCopy; + } + } +} + +private final static class RoundTripSparseOrdering extends TestActionDispatcher { + @Override + public void Dispatch(tangible.RefObject row, tangible.RefObject root, + Closure closure) { + LayoutType type = closure.Expected.Type; + String path = closure.Expected.Path; + Object exValue = closure.Expected.Value; + String json = closure.Json; + + TLayout t = (TLayout)type; + TValue value = (TValue)exValue; + RowCursor field; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out field).Find(row, path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + Result r = t.WriteSparse(row, ref field, value); + ResultAssert.IsSuccess(r, "Json: {0}", json); + tangible.OutObject tempOut_value = new tangible.OutObject(); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref field, tempOut_value); + value = tempOut_value.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", json); + boolean tempVar = exValue instanceof Array; + Array array = tempVar ? (Array)exValue : null; + if (tempVar) { + CollectionAssert.AreEqual(array, (Collection)value, "Json: {0}", json); + } else { + Assert.AreEqual(exValue, value, "Json: {0}", json); + } + + if (t instanceof LayoutNull) { + tangible.RefObject tempRef_field = + new tangible.RefObject(field); + r = LayoutType.Boolean.WriteSparse(row, tempRef_field, false); + field = tempRef_field.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", json); + tangible.OutObject tempOut_value2 = new tangible.OutObject(); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.ReadSparse(row, ref field, tempOut_value2); + value = tempOut_value2.argValue; + ResultAssert.TypeMismatch(r, "Json: {0}", json); + } else { + tangible.RefObject tempRef_field2 = + new tangible.RefObject(field); + r = LayoutType.Null.WriteSparse(row, tempRef_field2, NullValue.Default); + field = tempRef_field2.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", json); + tangible.OutObject tempOut_value3 = new tangible.OutObject(); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.ReadSparse(row, ref field, tempOut_value3); + value = tempOut_value3.argValue; + ResultAssert.TypeMismatch(r, "Json: {0}", json); + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Closure + public final static class Closure { + public Expected Expected = new Expected(); + public String Json; + + public Closure clone() { + Closure varCopy = new Closure(); + + varCopy.Json = this.Json; + varCopy.Expected = this.Expected.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Expected + public final static class Expected { + public String Path; + public LayoutType Type; + public Object Value; + + public Expected clone() { + Expected varCopy = new Expected(); + + varCopy.Path = this.Path; + varCopy.Type = this.Type; + varCopy.Value = this.Value; + + return varCopy; + } + } +} + +private final static class RoundTripSparseSet extends TestActionDispatcher { + @Override + public void Dispatch(tangible.RefObject row, tangible.RefObject root, + Closure closure) { + LayoutColumn setCol = closure.SetCol; + azure.data.cosmos.serialization.hybridrow.layouts.LayoutType tempVar = setCol.getType(); + LayoutUniqueScope setT = tempVar instanceof LayoutUniqueScope ? (LayoutUniqueScope)tempVar : null; + Expected expected = closure.Expected.clone(); + String tag = String.format("Json: %1$s, Set: %2$s", expected.Json, setCol.getType().getName()); + + System.out.println(tag); + Assert.IsNotNull(setT, tag); + + TLayout t = (TLayout)expected.Type; + + // Verify the Set doesn't yet exist. + RowCursor field; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out field).Find(row, setCol.getPath()); + tangible.RefObject tempRef_field = + new tangible.RefObject(field); + RowCursor scope; + tangible.OutObject tempOut_scope = + new tangible.OutObject(); + Result r = setT.ReadScope(row, tempRef_field, tempOut_scope); + scope = tempOut_scope.argValue; + field = tempRef_field.argValue; + ResultAssert.NotFound(r, tag); + + // Write the Set. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = setT.WriteScope(row, ref field, setCol.getTypeArgs().clone(), out scope); + ResultAssert.IsSuccess(r, tag); + + // Verify the nested field doesn't yet appear within the new scope. + assert !scope.MoveNext(row); + TValue value; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref scope, out value); + ResultAssert.NotFound(r, tag); + + // Write the nested fields. + for (Object v1 : expected.Value) { + // Write the ith item into staging storage. + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.WriteSparse(row, ref tempCursor, (TValue)v1); + ResultAssert.IsSuccess(r, tag); + + // Move item into the set. + tangible.RefObject tempRef_scope = + new tangible.RefObject(scope); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + r = setT.MoveField(row, tempRef_scope, tempRef_tempCursor); + tempCursor = tempRef_tempCursor.argValue; + scope = tempRef_scope.argValue; + ResultAssert.IsSuccess(r, tag); + } + + // Attempts to insert the same items into the set again will fail. + for (Object v2 : expected.Value) { + // Write the ith item into staging storage. + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.WriteSparse(row, ref tempCursor, (TValue)v2); + ResultAssert.IsSuccess(r, tag); + + // Move item into the set. + tangible.RefObject tempRef_scope2 = + new tangible.RefObject(scope); + tangible.RefObject tempRef_tempCursor2 = + new tangible.RefObject(tempCursor); + r = setT.MoveField(row, tempRef_scope2, tempRef_tempCursor2, UpdateOptions.Insert); + tempCursor = tempRef_tempCursor2.argValue; + scope = tempRef_scope2.argValue; + ResultAssert.Exists(r, tag); + } + + // Read the Set and the nested column, validate the nested column has the proper value. + tangible.RefObject tempRef_field2 = + new tangible.RefObject(field); + RowCursor scope2; + tangible.OutObject tempOut_scope2 = + new tangible.OutObject(); + r = setT.ReadScope(row, tempRef_field2, tempOut_scope2); + scope2 = tempOut_scope2.argValue; + field = tempRef_field2.argValue; + ResultAssert.IsSuccess(r, tag); + Assert.AreEqual(scope.ScopeType, scope2.ScopeType, tag); + Assert.AreEqual(scope.start, scope2.start, tag); + Assert.AreEqual(scope.Immutable, scope2.Immutable, tag); + + // Read the nested fields + tangible.RefObject tempRef_field3 = + new tangible.RefObject(field); + tangible.OutObject tempOut_scope2 = + new tangible.OutObject(); + ResultAssert.IsSuccess(setT.ReadScope(row, tempRef_field3, tempOut_scope2)); + scope = tempOut_scope2.argValue; + field = tempRef_field3.argValue; + for (Object item : expected.Value) { + assert scope.MoveNext(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.ReadSparse(row, ref scope, out value); + ResultAssert.IsSuccess(r, tag); + boolean tempVar2 = item instanceof Array; + Array array = tempVar2 ? (Array)item : null; + if (tempVar2) { + CollectionAssert.AreEqual(array, (Collection)value, tag); + } else { + Assert.AreEqual(item, value, tag); + } + } + + // Delete all of the items and then insert them again in the opposite order. + tangible.RefObject tempRef_field4 = + new tangible.RefObject(field); + tangible.OutObject tempOut_scope3 = + new tangible.OutObject(); + ResultAssert.IsSuccess(setT.ReadScope(row, tempRef_field4, tempOut_scope3)); + scope = tempOut_scope3.argValue; + field = tempRef_field4.argValue; + for (int i = 0; i < expected.Value.size(); i++) { + assert scope.MoveNext(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.DeleteSparse(row, ref scope); + ResultAssert.IsSuccess(r, tag); + } + + tangible.RefObject tempRef_field5 = + new tangible.RefObject(field); + tangible.OutObject tempOut_scope4 = + new tangible.OutObject(); + ResultAssert.IsSuccess(setT.ReadScope(row, tempRef_field5, tempOut_scope4)); + scope = tempOut_scope4.argValue; + field = tempRef_field5.argValue; + for (int i = expected.Value.size() - 1; i >= 0; i--) { + // Write the ith item into staging storage. + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.WriteSparse(row, ref tempCursor, (TValue)expected.Value.get(i)); + ResultAssert.IsSuccess(r, tag); + + // Move item into the set. + tangible.RefObject tempRef_scope3 = + new tangible.RefObject(scope); + tangible.RefObject tempRef_tempCursor3 = + new tangible.RefObject(tempCursor); + r = setT.MoveField(row, tempRef_scope3, tempRef_tempCursor3); + tempCursor = tempRef_tempCursor3.argValue; + scope = tempRef_scope3.argValue; + ResultAssert.IsSuccess(r, tag); + } + + // Verify they still enumerate in sorted order. + tangible.RefObject tempRef_field6 = + new tangible.RefObject(field); + tangible.OutObject tempOut_scope5 = + new tangible.OutObject(); + ResultAssert.IsSuccess(setT.ReadScope(row, tempRef_field6, tempOut_scope5)); + scope = tempOut_scope5.argValue; + field = tempRef_field6.argValue; + for (Object item : expected.Value) { + assert scope.MoveNext(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.ReadSparse(row, ref scope, out value); + ResultAssert.IsSuccess(r, tag); + boolean tempVar3 = item instanceof Array; + Array array = tempVar3 ? (Array)item : null; + if (tempVar3) { + CollectionAssert.AreEqual(array, (Collection)value, tag); + } else { + Assert.AreEqual(item, value, tag); + } + } + + // Delete one item. + if (expected.Value.size() > 1) { + int indexToDelete = 1; + tangible.RefObject tempRef_field7 = + new tangible.RefObject(field); + tangible.OutObject tempOut_scope6 = new tangible.OutObject(); + ResultAssert.IsSuccess(setT.ReadScope(row, tempRef_field7, tempOut_scope6)); + scope = tempOut_scope6.argValue; + field = tempRef_field7.argValue; + assert scope.MoveTo(row, indexToDelete); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.DeleteSparse(row, ref scope); + ResultAssert.IsSuccess(r, tag); + ArrayList remainingValues = new ArrayList(expected.Value); + remainingValues.remove(indexToDelete); + + tangible.RefObject tempRef_field8 = new tangible.RefObject(field); + tangible.OutObject tempOut_scope7 = new tangible.OutObject(); + ResultAssert.IsSuccess(setT.ReadScope(row, tempRef_field8, tempOut_scope7)); + scope = tempOut_scope7.argValue; + field = tempRef_field8.argValue; + for (Object item : remainingValues) { + assert scope.MoveNext(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref scope, out value); + ResultAssert.IsSuccess(r, tag); + boolean tempVar4 = item instanceof Array; + Array array = tempVar4 ? (Array)item : null; + if (tempVar4) { + CollectionAssert.AreEqual(array, (Collection)value, tag); + } else { + Assert.AreEqual(item, value, tag); + } + } + + assert !scope.MoveTo(row, remainingValues.size()); + } + + RowCursor roRoot; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.AsReadOnly(out roRoot).Find(row, setCol.getPath()); + tangible.RefObject tempRef_roRoot = new tangible.RefObject(roRoot); + ResultAssert.InsufficientPermissions(setT.DeleteScope(row, tempRef_roRoot)); + roRoot = tempRef_roRoot.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.InsufficientPermissions(setT.WriteScope(row, ref roRoot, setCol.getTypeArgs().clone(), out _)); + + // Overwrite the whole scope. + tangible.RefObject tempRef_field9 = new tangible.RefObject(field); + r = LayoutType.Null.WriteSparse(row, tempRef_field9, NullValue.Default); + field = tempRef_field9.argValue; + ResultAssert.IsSuccess(r, tag); + tangible.RefObject tempRef_field10 = new tangible.RefObject(field); + RowCursor _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + r = setT.ReadScope(row, tempRef_field10, tempOut__); + _ = tempOut__.argValue; + field = tempRef_field10.argValue; + ResultAssert.TypeMismatch(r, tag); + tangible.RefObject tempRef_field11 = new tangible.RefObject(field); + r = setT.DeleteScope(row, tempRef_field11); + field = tempRef_field11.argValue; + ResultAssert.TypeMismatch(r, "Json: {0}", expected.Json); + + // Overwrite it again, then delete it. + tangible.RefObject tempRef_field12 = new tangible.RefObject(field); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + r = setT.WriteScope(row, tempRef_field12, setCol.getTypeArgs().clone(), out _, UpdateOptions.Update); + field = tempRef_field12.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + tangible.RefObject tempRef_field13 = new tangible.RefObject(field); + r = setT.DeleteScope(row, tempRef_field13); + field = tempRef_field13.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + tangible.RefObject tempRef_field14 = new tangible.RefObject(field); + RowCursor _; + tangible.OutObject tempOut__2 = new tangible.OutObject(); + r = setT.ReadScope(row, tempRef_field14, tempOut__2); + _ = tempOut__2.argValue; + field = tempRef_field14.argValue; + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Closure + public final static class Closure { + public Expected Expected = new Expected(); + public LayoutColumn SetCol; + + public Closure clone() { + Closure varCopy = new Closure(); + + varCopy.SetCol = this.SetCol; + varCopy.Expected = this.Expected.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Expected + public final static class Expected { + public String Json; + public LayoutType Type; + public ArrayList Value; + + public Expected clone() { + Expected varCopy = new Expected(); + + varCopy.Json = this.Json; + varCopy.Type = this.Type; + varCopy.Value = this.Value; + + return varCopy; + } + } +} + +private final static class RoundTripSparseSimple extends TestActionDispatcher { + @Override + public void Dispatch(tangible.RefObject row, tangible.RefObject root, + Closure closure) { + LayoutColumn col = closure.Col; + Expected expected = closure.Expected.clone(); + + System.out.printf("%1$s" + "\r\n", col.getType().getName()); + TLayout t = (TLayout)col.getType(); + RowCursor field; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out field).Find(row, col.getPath()); + TValue value; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + Result r = t.ReadSparse(row, ref field, out value); + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.WriteSparse(row, ref field, (TValue)expected.Value, UpdateOptions.Update); + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.WriteSparse(row, ref field, (TValue)expected.Value); + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.WriteSparse(row, ref field, (TValue)expected.Value, UpdateOptions.Insert); + ResultAssert.Exists(r, "Json: {0}", expected.Json); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref field, out value); + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + boolean tempVar = expected.Value instanceof Array; + Array array = tempVar ? (Array)expected.Value : null; + if (tempVar) { + CollectionAssert.AreEqual(array, (Collection)value, "Json: {0}", expected.Json); + } else { + Assert.AreEqual(expected.Value, value, "Json: {0}", expected.Json); + } + + RowCursor roRoot; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.AsReadOnly(out roRoot).Find(row, col.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.InsufficientPermissions(t.DeleteSparse(row, ref roRoot)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.InsufficientPermissions(t.WriteSparse(row, ref roRoot, (TValue)expected.Value, + UpdateOptions.Update)); + + if (t instanceof LayoutNull) { + tangible.RefObject tempRef_field = + new tangible.RefObject(field); + r = LayoutType.Boolean.WriteSparse(row, tempRef_field, false); + field = tempRef_field.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.ReadSparse(row, ref field, out value); + ResultAssert.TypeMismatch(r, "Json: {0}", expected.Json); + } else { + tangible.RefObject tempRef_field2 = + new tangible.RefObject(field); + r = LayoutType.Null.WriteSparse(row, tempRef_field2, NullValue.Default); + field = tempRef_field2.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + r = t.ReadSparse(row, ref field, out value); + ResultAssert.TypeMismatch(r, "Json: {0}", expected.Json); + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.DeleteSparse(row, ref field); + ResultAssert.TypeMismatch(r, "Json: {0}", expected.Json); + + // Overwrite it again, then delete it. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.WriteSparse(row, ref field, (TValue)expected.Value, UpdateOptions.Update); + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.DeleteSparse(row, ref field); + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + r = t.ReadSparse(row, ref field, out value); + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Closure + public final static class Closure { + public LayoutColumn Col; + public Expected Expected = new Expected(); + + public Closure clone() { + Closure varCopy = new Closure(); + + varCopy.Col = this.Col; + varCopy.Expected = this.Expected.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Expected + public final static class Expected { + public String Json; + public Object Value; + + public Expected clone() { + Expected varCopy = new Expected(); + + varCopy.Json = this.Json; + varCopy.Value = this.Value; + + return varCopy; + } + } +} + +private static class RoundTripVariable extends TestActionDispatcher { + @Override + public void Dispatch(tangible.RefObject row, tangible.RefObject root, + Closure closure) { + LayoutColumn col = closure.Col; + Expected expected = closure.Expected.clone(); + + System.out.printf("%1$s" + "\r\n", expected.Json); + + this.RoundTrip(row, root, col, expected.Value, expected.clone()); + } + + protected final , TValue> void Compare(tangible.RefObject row, + tangible.RefObject root, LayoutColumn col, Object exValue, Expected expected) { + TLayout t = (TLayout)col.getType(); + TValue value; + tangible.OutObject tempOut_value = new tangible.OutObject(); + Result r = t.ReadVariable(row, root, col, tempOut_value); + value = tempOut_value.argValue; + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + boolean tempVar = exValue instanceof Array; + Array array = tempVar ? (Array)exValue : null; + if (tempVar) { + CollectionAssert.AreEqual(array, (Collection)value, "Json: {0}", expected.Json); + } else { + Assert.AreEqual(exValue, value, "Json: {0}", expected.Json); + } + } + + protected final , TValue> void RoundTrip(tangible.RefObject row, + tangible.RefObject root, LayoutColumn col, Object exValue, Expected expected) { + TLayout t = (TLayout)col.getType(); + Result r = t.WriteVariable(row, root, col, (TValue)exValue); + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + this.Compare(row, root, col, exValue, expected.clone()); + + RowCursor roRoot; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.AsReadOnly(out roRoot); + tangible.RefObject tempRef_roRoot = + new tangible.RefObject(roRoot); + ResultAssert.InsufficientPermissions(t.WriteVariable(row, tempRef_roRoot, col, (TValue)expected.Value)); + roRoot = tempRef_roRoot.argValue; + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Closure + public final static class Closure { + public LayoutColumn Col; + public Expected Expected = new Expected(); + public Layout Layout; + + public Closure clone() { + Closure varCopy = new Closure(); + + varCopy.Col = this.Col; + varCopy.Layout = this.Layout; + varCopy.Expected = this.Expected.clone(); + + return varCopy; + } + } + + //C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may + // differ from the original: + //ORIGINAL LINE: public struct Expected + public final static class Expected { + public String Json; + public Object Long; + public Object Short; + public Object TooBig; + public Object Value; + + public Expected clone() { + Expected varCopy = new Expected(); + + varCopy.Json = this.Json; + varCopy.Short = this.Short; + varCopy.Value = this.Value; + varCopy.Long = this.Long; + varCopy.TooBig = this.TooBig; + + return varCopy; + } + } +} + +private abstract static class TestActionDispatcher { + public abstract , TValue> void Dispatch(tangible.RefObject row, tangible.RefObject scope, TClosure closure); + + public void DispatchObject(tangible.RefObject row, tangible.RefObject scope, TClosure closure) { + Assert.Fail("not implemented"); + } +} + +private final static class VariableInterleaving extends RoundTripVariable { + @Override + public void Dispatch(tangible.RefObject row, tangible.RefObject root, + Closure closure) { + Layout layout = closure.Layout; + Expected expected = closure.Expected.clone(); + + System.out.printf("%1$s" + "\r\n", expected.Json); + + LayoutColumn a = this.Verify(row, root, layout, "a", expected.clone()); + LayoutColumn b = this.Verify(row, root, layout, "b", expected.clone()); + LayoutColumn c = this.Verify(row, root, layout, "c", expected.clone()); + + this.RoundTrip(row, root, b, expected.Value, expected.clone()); + this.RoundTrip(row, root, a, expected.Value, expected.clone()); + this.RoundTrip(row, root, c, expected.Value, expected.clone()); + + // Make the var column shorter. + int rowSizeBeforeShrink = row.argValue.getLength(); + this.RoundTrip(row, root, a, expected.Short, expected.clone()); + this.Compare(row, root, c, expected.Value, expected.clone()); + int rowSizeAfterShrink = row.argValue.getLength(); + Assert.IsTrue(rowSizeAfterShrink < rowSizeBeforeShrink, "Json: {0}", expected.Json); + + // Make the var column longer. + this.RoundTrip(row, root, a, expected.Long, expected.clone()); + this.Compare(row, root, c, expected.Value, expected.clone()); + int rowSizeAfterGrow = row.argValue.getLength(); + Assert.IsTrue(rowSizeAfterGrow > rowSizeAfterShrink, "Json: {0}", expected.Json); + Assert.IsTrue(rowSizeAfterGrow > rowSizeBeforeShrink, "Json: {0}", expected.Json); + + // Check for size overflow errors. + if (a.getSize() > 0) { + this.TooBig(row, root, a, expected.clone()); + } + + // Delete the var column. + this.Delete(row, root, b, expected.clone()); + this.Delete(row, root, c, expected.clone()); + this.Delete(row, root, a, expected.clone()); + } + + private , TValue> void Delete(tangible.RefObject row, + tangible.RefObject root, LayoutColumn col, Expected expected) { + TLayout t = (TLayout)col.getType(); + RowCursor roRoot; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.AsReadOnly(out roRoot); + tangible.RefObject tempRef_roRoot = + new tangible.RefObject(roRoot); + ResultAssert.InsufficientPermissions(t.DeleteVariable(row, tempRef_roRoot, col)); + roRoot = tempRef_roRoot.argValue; + Result r = t.DeleteVariable(row, root, col); + ResultAssert.IsSuccess(r, "Json: {0}", expected.Json); + TValue _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + r = t.ReadVariable(row, root, col, tempOut__); + _ = tempOut__.argValue; + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + } + + private , TValue> void TooBig(tangible.RefObject row, + tangible.RefObject root, LayoutColumn col, Expected expected) { + TLayout t = (TLayout)col.getType(); + Result r = t.WriteVariable(row, root, col, (TValue)expected.TooBig); + Assert.AreEqual(Result.TooBig, r, "Json: {0}", expected.Json); + } + + private , TValue> LayoutColumn Verify(tangible.RefObject row, + tangible.RefObject root, Layout layout, String path, Expected expected) { + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + boolean found = layout.TryFind(path, out col); + Assert.IsTrue(found, "Json: {0}", expected.Json); + assert col.Type.AllowVariable; + TLayout t = (TLayout)col.Type; + TValue _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + Result r = t.ReadVariable(row, root, col, tempOut__); + _ = tempOut__.argValue; + ResultAssert.NotFound(r, "Json: {0}", expected.Json); + return col; + } +} +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/LayoutTypeUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/LayoutTypeUnitTests.java new file mode 100644 index 0000000..d89b798 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/LayoutTypeUnitTests.java @@ -0,0 +1,47 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass] public class LayoutTypeUnitTests +public class LayoutTypeUnitTests { + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void LayoutTypeTest() + public final void LayoutTypeTest() { + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Boolean); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Int8); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Int16); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Int32); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Int64); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.UInt8); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.UInt16); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.UInt32); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.UInt64); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.VarInt); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.VarUInt); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Float32); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Float64); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Decimal); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Null); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Boolean); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.DateTime); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Guid); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Utf8); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Binary); + LayoutTypeUnitTests.TestLayoutTypeApi(LayoutType.Object); + } + + private static void TestLayoutTypeApi(LayoutType t) { + assert t.getName() != null; + assert !tangible.StringHelper.isNullOrWhiteSpace(t.getName()); + Assert.AreNotSame(null, t.getIsFixed(), t.getName()); + Assert.AreNotSame(null, t.getAllowVariable(), t.getName()); + Assert.AreNotSame(null, t.getIsBool(), t.getName()); + Assert.AreNotSame(null, t.getIsNull(), t.getName()); + Assert.AreNotSame(null, t.getIsVarint(), t.getName()); + Assert.IsTrue(t.Size >= 0, t.getName()); + Assert.AreNotEqual(LayoutCode.Invalid, t.LayoutCode, t.getName()); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/NullRowDispatcher.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/NullRowDispatcher.java new file mode 100644 index 0000000..eb6d238 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/NullRowDispatcher.java @@ -0,0 +1,85 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: internal struct NullRowDispatcher : IDispatcher +public final class NullRowDispatcher implements IDispatcher { + + public , TValue> void Dispatch(tangible.RefObject dispatcher, tangible.RefObject root, LayoutColumn col, LayoutType t) { + Dispatch(dispatcher, root, col, t, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public void Dispatch(ref RowOperationDispatcher dispatcher, ref RowCursor root, + // LayoutColumn col, LayoutType t, TValue expected = default) where TLayout : LayoutType + public , TValue> void Dispatch(tangible.RefObject dispatcher, tangible.RefObject root, LayoutColumn col, LayoutType t, TValue expected) { + switch (col == null ? null : col.getStorage()) { + case Fixed: + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + TValue _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + ResultAssert.NotFound(t.TypeAs().ReadFixed(tempRef_Row, root, col, out _)); + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + break; + case Variable: + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + TValue _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + ResultAssert.NotFound(t.TypeAs().ReadVariable(tempRef_Row2, root, col, out _)); + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + break; + default: + tangible.RefObject tempRef_Row3 = + new tangible.RefObject(dispatcher.argValue.Row); + TValue _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + ResultAssert.NotFound(t.TypeAs().ReadSparse(tempRef_Row3, root, out _)); + dispatcher.argValue.argValue.Row = tempRef_Row3.argValue; + break; + } + } + + public void DispatchArray(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + } + + public void DispatchMap(tangible.RefObject dispatcher, tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, Object value) { + } + + public void DispatchNullable(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + } + + public void DispatchObject(tangible.RefObject dispatcher, + tangible.RefObject scope) { + } + + public void DispatchSet(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + } + + public void DispatchTuple(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + } + + public void DispatchUDT(tangible.RefObject dispatcher, tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, Object value) { + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/NullableUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/NullableUnitTests.java new file mode 100644 index 0000000..2ef2d71 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/NullableUnitTests.java @@ -0,0 +1,749 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +// ReSharper disable StringLiteralTypo + + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][DeploymentItem(NullableUnitTests.SchemaFile, "TestData")] public sealed class +// NullableUnitTests +public final class NullableUnitTests { + private static final int InitialRowSize = 2 * 1024 * 1024; + private static final String SchemaFile = "TestData\\NullableSchema.json"; + private Layout layout; + private LayoutResolver resolver; + private Namespace schema; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateNullables() + public void CreateNullables() { + RowBuffer row = new RowBuffer(NullableUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + + Nullables t1 = new Nullables(); + t1.NullBool = new ArrayList(Arrays.asList(true, false, null)); + t1.NullArray = new ArrayList(Arrays.asList(1.2F, null, 3.0F)); + t1.NullSet = new ArrayList(Arrays.asList(null, "abc", "def")); + t1.NullTuple = new ArrayList<(Integer, Long) > (Arrays.asList((1, 2), (null, 3),(4, null),(null, null))) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: t1.NullMap = new Dictionary> { { System.Guid.Parse + // ("{00000000-0000-0000-0000-000000000000}"), 1 }, { System.Guid.Parse + // ("{4674962B-CE11-4916-81C5-0421EE36F168}"), 20 }, { System.Guid.Parse + // ("{7499C40E-7077-45C1-AE5F-3E384966B3B9}"), null }}; + t1.NullMap = new HashMap(Map.ofEntries(Map.entry(UUID.fromString("{00000000-0000-0000-0000" + + "-000000000000}"), 1), Map.entry(UUID.fromString("{4674962B-CE11-4916-81C5-0421EE36F168}"), 20), + Map.entry(UUID.fromString("{7499C40E-7077-45C1-AE5F-3E384966B3B9}"), null))); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteNullables(tempRef_row, RowCursor.Create(tempRef_row2, out _), t1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Nullables t2 = this.ReadNullables(tempRef_row3, RowCursor.Create(tempRef_row4, out _)); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + assert t1 == t2; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public void ParseNamespaceExample() { + String json = Files.readString(NullableUnitTests.SchemaFile); + this.schema = Namespace.Parse(json); + this.resolver = new LayoutResolverNamespace(this.schema); + this.layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Nullables")).SchemaId); + } + + // TODO: C# TO JAVA CONVERTER: The C# 'struct' constraint has no equivalent in Java: + //ORIGINAL LINE: private static Result ReadNullable(ref RowBuffer row, ref RowCursor scope, TypeArgument + // itemType, out Nullable item, out RowCursor nullableScope) where TValue : struct + private static Result ReadNullable(tangible.RefObject row, + tangible.RefObject scope, TypeArgument itemType, + tangible.OutObject item, + tangible.OutObject nullableScope) { + TValue value; + tangible.OutObject tempOut_value = new tangible.OutObject(); + Result r = NullableUnitTests.ReadNullableImpl(row, scope, itemType.clone(), tempOut_value, + nullableScope.clone()); + value = tempOut_value.argValue; + if ((r != Result.Success) && (r != Result.NotFound)) { + item.argValue = null; + return r; + } + + item.argValue = (r == Result.NotFound) ? null : value; + return Result.Success; + } + + private static Result ReadNullable(tangible.RefObject row, + tangible.RefObject scope, TypeArgument itemType, + tangible.OutObject item, + tangible.OutObject nullableScope) { + Result r = NullableUnitTests.ReadNullableImpl(row, scope, itemType.clone(), item, nullableScope.clone()); + return (r == Result.NotFound) ? Result.Success : r; + } + + private static Result ReadNullableImpl(tangible.RefObject row, + tangible.RefObject scope, TypeArgument itemType, + tangible.OutObject item, + tangible.OutObject nullableScope) { + Result r = itemType.getType().TypeAs().ReadScope(row, scope, nullableScope.clone()); + if (r != Result.Success) { + item.argValue = null; + return r; + } + + if (Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(nullableScope.argValue.clone(), row)) { + ResultAssert.IsSuccess(LayoutNullable.HasValue(row, nullableScope.clone())); + return itemType.getTypeArgs().get(0).getType().>TypeAs().ReadSparse(row, + nullableScope.clone(), item); + } + + ResultAssert.NotFound(LayoutNullable.HasValue(row, nullableScope.clone())); + item.argValue = null; + return Result.NotFound; + } + + private Nullables ReadNullables(tangible.RefObject row, tangible.RefObject root) { + Nullables value = new Nullables(); + + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("nullbool", out c); + RowCursor scope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out scope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref scope, out scope) == Result.Success) { + value.NullBool = new ArrayList(); + RowCursor nullableScope = null; + tangible.RefObject tempRef_nullableScope = + new tangible.RefObject(nullableScope); + while (scope.MoveNext(row, tempRef_nullableScope)) { + nullableScope = tempRef_nullableScope.argValue; + tangible.RefObject tempRef_scope = + new tangible.RefObject(scope); + Nullable item; + tangible.OutObject tempOut_item = new tangible.OutObject(); + tangible.OutObject tempOut_nullableScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.ReadNullable(row, tempRef_scope, c.TypeArgs[0], tempOut_item + , tempOut_nullableScope)); + nullableScope = tempOut_nullableScope.argValue; + item = tempOut_item.argValue; + scope = tempRef_scope.argValue; + value.NullBool.add(item); + } + nullableScope = tempRef_nullableScope.argValue; + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("nullarray", out c); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out scope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref scope, out scope) == Result.Success) { + value.NullArray = new ArrayList(); + RowCursor nullableScope = null; + tangible.RefObject tempRef_nullableScope2 = + new tangible.RefObject(nullableScope); + while (scope.MoveNext(row, tempRef_nullableScope2)) { + nullableScope = tempRef_nullableScope2.argValue; + tangible.RefObject tempRef_scope2 = + new tangible.RefObject(scope); + Nullable item; + tangible.OutObject tempOut_item2 = new tangible.OutObject(); + tangible.OutObject tempOut_nullableScope2 = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.ReadNullable(row, tempRef_scope2, c.TypeArgs[0], + tempOut_item2, tempOut_nullableScope2)); + nullableScope = tempOut_nullableScope2.argValue; + item = tempOut_item2.argValue; + scope = tempRef_scope2.argValue; + value.NullArray.add(item); + } + nullableScope = tempRef_nullableScope2.argValue; + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("nullset", out c); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out scope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref scope, out scope) == Result.Success) { + value.NullSet = new ArrayList(); + RowCursor nullableScope = null; + tangible.RefObject tempRef_nullableScope3 = + new tangible.RefObject(nullableScope); + while (scope.MoveNext(row, tempRef_nullableScope3)) { + nullableScope = tempRef_nullableScope3.argValue; + tangible.RefObject tempRef_scope3 = + new tangible.RefObject(scope); + String item; + tangible.OutObject tempOut_item3 = new tangible.OutObject(); + tangible.OutObject tempOut_nullableScope3 = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.ReadNullable(row, tempRef_scope3, c.TypeArgs[0], + tempOut_item3, tempOut_nullableScope3)); + nullableScope = tempOut_nullableScope3.argValue; + item = tempOut_item3.argValue; + scope = tempRef_scope3.argValue; + value.NullSet.add(item); + } + nullableScope = tempRef_nullableScope3.argValue; + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("nulltuple", out c); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out scope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref scope, out scope) == Result.Success) { + value.NullTuple = new ArrayList<(Integer, Long) > (); + RowCursor tupleScope = null; + TypeArgument tupleType = c.TypeArgs[0]; + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + while (scope.MoveNext(row, tempRef_tupleScope)) { + tupleScope = tempRef_tupleScope.argValue; + tangible.RefObject tempRef_scope4 = + new tangible.RefObject(scope); + tangible.OutObject tempOut_tupleScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(tupleType.TypeAs().ReadScope(row, tempRef_scope4, + tempOut_tupleScope)); + tupleScope = tempOut_tupleScope.argValue; + scope = tempRef_scope4.argValue; + + assert Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(tupleScope.clone() + , row); + tangible.RefObject tempRef_tupleScope2 = + new tangible.RefObject(tupleScope); + Nullable item1; + tangible.OutObject tempOut_item1 = new tangible.OutObject(); + RowCursor nullableScope; + tangible.OutObject tempOut_nullableScope4 = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.ReadNullable(row, tempRef_tupleScope2, + tupleType.getTypeArgs().get(0).clone(), tempOut_item1, tempOut_nullableScope4)); + nullableScope = tempOut_nullableScope4.argValue; + item1 = tempOut_item1.argValue; + tupleScope = tempRef_tupleScope2.argValue; + tangible.RefObject tempRef_nullableScope4 = + new tangible.RefObject(nullableScope); + assert Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(tupleScope.clone() + , row, tempRef_nullableScope4); + nullableScope = tempRef_nullableScope4.argValue; + tangible.RefObject tempRef_tupleScope3 = + new tangible.RefObject(tupleScope); + Nullable item2; + tangible.OutObject tempOut_item2 = new tangible.OutObject(); + tangible.OutObject tempOut_nullableScope5 = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.ReadNullable(row, tempRef_tupleScope3, + tupleType.getTypeArgs().get(1).clone(), tempOut_item2, tempOut_nullableScope5)); + nullableScope = tempOut_nullableScope5.argValue; + item2 = tempOut_item2.argValue; + tupleScope = tempRef_tupleScope3.argValue; + + tangible.RefObject tempRef_nullableScope5 = + new tangible.RefObject(nullableScope); + assert !Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(tupleScope.clone(), row, tempRef_nullableScope5); + nullableScope = tempRef_nullableScope5.argValue; + value.NullTuple.add((item1, item2)) + } + tupleScope = tempRef_tupleScope.argValue; + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("nullmap", out c); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out scope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref scope, out scope) == Result.Success) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: value.NullMap = new Dictionary>(); + value.NullMap = new HashMap(); + RowCursor tupleScope = null; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + TypeArgument tupleType = c.TypeAs().FieldType(ref scope); + tangible.RefObject tempRef_tupleScope4 = + new tangible.RefObject(tupleScope); + while (scope.MoveNext(row, tempRef_tupleScope4)) { + tupleScope = tempRef_tupleScope4.argValue; + tangible.RefObject tempRef_scope5 = + new tangible.RefObject(scope); + tangible.OutObject tempOut_tupleScope2 = + new tangible.OutObject(); + ResultAssert.IsSuccess(tupleType.TypeAs().ReadScope(row, tempRef_scope5, + tempOut_tupleScope2)); + tupleScope = tempOut_tupleScope2.argValue; + scope = tempRef_scope5.argValue; + + assert Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(tupleScope.clone() + , row); + tangible.RefObject tempRef_tupleScope5 = + new tangible.RefObject(tupleScope); + Nullable itemKey; + tangible.OutObject tempOut_itemKey = new tangible.OutObject(); + RowCursor nullableScope; + tangible.OutObject tempOut_nullableScope6 = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.ReadNullable(row, tempRef_tupleScope5, + tupleType.getTypeArgs().get(0).clone(), tempOut_itemKey, tempOut_nullableScope6)); + nullableScope = tempOut_nullableScope6.argValue; + itemKey = tempOut_itemKey.argValue; + tupleScope = tempRef_tupleScope5.argValue; + + tangible.RefObject tempRef_nullableScope6 = + new tangible.RefObject(nullableScope); + assert Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(tupleScope.clone() + , row, tempRef_nullableScope6); + nullableScope = tempRef_nullableScope6.argValue; + tangible.RefObject tempRef_tupleScope6 = + new tangible.RefObject(tupleScope); + Nullable itemValue; + tangible.OutObject tempOut_itemValue = new tangible.OutObject(); + tangible.OutObject tempOut_nullableScope7 = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.ReadNullable(row, tempRef_tupleScope6, + tupleType.getTypeArgs().get(1).clone(), tempOut_itemValue, tempOut_nullableScope7)); + nullableScope = tempOut_nullableScope7.argValue; + itemValue = tempOut_itemValue.argValue; + tupleScope = tempRef_tupleScope6.argValue; + + tangible.RefObject tempRef_nullableScope7 = + new tangible.RefObject(nullableScope); + assert !Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(tupleScope.clone(), row, tempRef_nullableScope7); + nullableScope = tempRef_nullableScope7.argValue; + value.NullMap.put(itemKey != null ? itemKey : UUID.Empty, itemValue); + } + tupleScope = tempRef_tupleScope4.argValue; + } + + return value; + } + + // TODO: C# TO JAVA CONVERTER: The C# 'struct' constraint has no equivalent in Java: + //ORIGINAL LINE: private static Result WriteNullable(ref RowBuffer row, ref RowCursor scope, TypeArgument + // itemType, Nullable item, out RowCursor nullableScope) where TValue : struct + private static Result WriteNullable(tangible.RefObject row, + tangible.RefObject scope, TypeArgument itemType, + TValue item, tangible.OutObject nullableScope) { + return NullableUnitTests.WriteNullableImpl(row, scope, itemType.clone(), item != null, item != null ? item : + default,nullableScope.clone()) + } + + private static Result WriteNullable(tangible.RefObject row, + tangible.RefObject scope, TypeArgument itemType, + TValue item, tangible.OutObject nullableScope) { + return NullableUnitTests.WriteNullableImpl(row, scope, itemType.clone(), item != null, item, + nullableScope.clone()); + } + + private static Result WriteNullableImpl(tangible.RefObject row, + tangible.RefObject scope, TypeArgument itemType, + boolean hasValue, TValue item, + tangible.OutObject nullableScope) { + Result r = itemType.TypeAs().WriteScope(row, scope, itemType.getTypeArgs().clone(), hasValue, + nullableScope); + + if (r != Result.Success) { + return r; + } + + if (hasValue) { + r = itemType.getTypeArgs().get(0).getType().>TypeAs().WriteSparse(row, + nullableScope.clone(), item); + return r; + } + + return Result.Success; + } + + private void WriteNullables(tangible.RefObject row, tangible.RefObject root, + Nullables value) { + LayoutColumn c; + + if (value.NullBool != null) { + tangible.OutObject tempOut_c = + new tangible.OutObject(); + assert this.layout.TryFind("nullbool", tempOut_c); + c = tempOut_c.argValue; + RowCursor outerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out outerScope).Find(row, c.getPath()); + tangible.RefObject tempRef_outerScope = + new tangible.RefObject(outerScope); + tangible.OutObject tempOut_outerScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, tempRef_outerScope, + c.getTypeArgs().clone(), tempOut_outerScope)); + outerScope = tempOut_outerScope.argValue; + outerScope = tempRef_outerScope.argValue; + for (Boolean item : value.NullBool) { + tangible.RefObject tempRef_outerScope2 = + new tangible.RefObject(outerScope); + RowCursor innerScope; + tangible.OutObject tempOut_innerScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.WriteNullable(row, tempRef_outerScope2, + c.getTypeArgs().get(0).clone(), item, tempOut_innerScope)); + innerScope = tempOut_innerScope.argValue; + outerScope = tempRef_outerScope2.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert !outerScope.MoveNext(row, ref innerScope); + } + } + + if (value.NullArray != null) { + tangible.OutObject tempOut_c2 = + new tangible.OutObject(); + assert this.layout.TryFind("nullarray", tempOut_c2); + c = tempOut_c2.argValue; + RowCursor outerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out outerScope).Find(row, c.getPath()); + tangible.RefObject tempRef_outerScope3 = + new tangible.RefObject(outerScope); + tangible.OutObject tempOut_outerScope2 = + new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, tempRef_outerScope3, + c.getTypeArgs().clone(), tempOut_outerScope2)); + outerScope = tempOut_outerScope2.argValue; + outerScope = tempRef_outerScope3.argValue; + for (Float item : value.NullArray) { + tangible.RefObject tempRef_outerScope4 = + new tangible.RefObject(outerScope); + RowCursor innerScope; + tangible.OutObject tempOut_innerScope2 = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.WriteNullable(row, tempRef_outerScope4, + c.getTypeArgs().get(0).clone(), item, tempOut_innerScope2)); + innerScope = tempOut_innerScope2.argValue; + outerScope = tempRef_outerScope4.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert !outerScope.MoveNext(row, ref innerScope); + } + } + + if (value.NullSet != null) { + tangible.OutObject tempOut_c3 = + new tangible.OutObject(); + assert this.layout.TryFind("nullset", tempOut_c3); + c = tempOut_c3.argValue; + RowCursor outerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out outerScope).Find(row, c.getPath()); + tangible.RefObject tempRef_outerScope5 = + new tangible.RefObject(outerScope); + tangible.OutObject tempOut_outerScope3 = + new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, tempRef_outerScope5, + c.getTypeArgs().clone(), tempOut_outerScope3)); + outerScope = tempOut_outerScope3.argValue; + outerScope = tempRef_outerScope5.argValue; + for (String item : value.NullSet) { + RowCursor temp; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + RowCursor.CreateForAppend(row, out temp).Find(row, ""); + tangible.RefObject tempRef_temp = + new tangible.RefObject(temp); + RowCursor _; + tangible.OutObject tempOut__ = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.WriteNullable(row, tempRef_temp, + c.getTypeArgs().get(0).clone(), item, tempOut__)); + _ = tempOut__.argValue; + temp = tempRef_temp.argValue; + tangible.RefObject tempRef_outerScope6 = + new tangible.RefObject(outerScope); + tangible.RefObject tempRef_temp2 = + new tangible.RefObject(temp); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_outerScope6, tempRef_temp2)); + temp = tempRef_temp2.argValue; + outerScope = tempRef_outerScope6.argValue; + } + } + + if (value.NullTuple != null) { + tangible.OutObject tempOut_c4 = + new tangible.OutObject(); + assert this.layout.TryFind("nulltuple", tempOut_c4); + c = tempOut_c4.argValue; + RowCursor outerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out outerScope).Find(row, c.getPath()); + tangible.RefObject tempRef_outerScope7 = + new tangible.RefObject(outerScope); + tangible.OutObject tempOut_outerScope4 = + new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, tempRef_outerScope7, + c.getTypeArgs().clone(), tempOut_outerScope4)); + outerScope = tempOut_outerScope4.argValue; + outerScope = tempRef_outerScope7.argValue; + for ((Integer item1,Long item2) :value.NullTuple) + { + TypeArgument tupleType = c.getTypeArgs().get(0).clone(); + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(tupleType.TypeAs().WriteScope(row, ref outerScope, + tupleType.getTypeArgs().clone(), out tupleScope)); + + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + RowCursor nullableScope; + tangible.OutObject tempOut_nullableScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.WriteNullable(row, tempRef_tupleScope, + tupleType.getTypeArgs().get(0).clone(), item1, tempOut_nullableScope)); + nullableScope = tempOut_nullableScope.argValue; + tupleScope = tempRef_tupleScope.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert tupleScope.MoveNext(row, ref nullableScope); + tangible.RefObject tempRef_tupleScope2 = + new tangible.RefObject(tupleScope); + tangible.OutObject tempOut_nullableScope2 = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.WriteNullable(row, tempRef_tupleScope2, + tupleType.getTypeArgs().get(1).clone(), item2, tempOut_nullableScope2)); + nullableScope = tempOut_nullableScope2.argValue; + tupleScope = tempRef_tupleScope2.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert !tupleScope.MoveNext(row, ref nullableScope); + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert !outerScope.MoveNext(row, ref tupleScope); + } + } + + if (value.NullMap != null) { + tangible.OutObject tempOut_c5 = + new tangible.OutObject(); + assert this.layout.TryFind("nullmap", tempOut_c5); + c = tempOut_c5.argValue; + RowCursor outerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out outerScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref outerScope, + c.getTypeArgs().clone(), out outerScope)); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: foreach ((Guid key, Nullable itemValue) in value.NullMap) + for ((UUID key,Byte itemValue) :value.NullMap) + { + tangible.RefObject tempRef_outerScope8 = + new tangible.RefObject(outerScope); + TypeArgument tupleType = c.TypeAs().FieldType(tempRef_outerScope8).clone(); + outerScope = tempRef_outerScope8.argValue; + RowCursor temp; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + RowCursor.CreateForAppend(row, out temp).Find(row, ""); + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(tupleType.TypeAs().WriteScope(row, ref temp, + tupleType.getTypeArgs().clone(), out tupleScope)); + + UUID itemKey = key.equals(UUID.Empty) ? null : key; + tangible.RefObject tempRef_tupleScope3 = + new tangible.RefObject(tupleScope); + RowCursor nullableScope; + tangible.OutObject tempOut_nullableScope3 = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.WriteNullable(row, tempRef_tupleScope3, + tupleType.getTypeArgs().get(0).clone(), itemKey, tempOut_nullableScope3)); + nullableScope = tempOut_nullableScope3.argValue; + tupleScope = tempRef_tupleScope3.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert tupleScope.MoveNext(row, ref nullableScope); + tangible.RefObject tempRef_tupleScope4 = + new tangible.RefObject(tupleScope); + tangible.OutObject tempOut_nullableScope4 = + new tangible.OutObject(); + ResultAssert.IsSuccess(NullableUnitTests.WriteNullable(row, tempRef_tupleScope4, + tupleType.getTypeArgs().get(1).clone(), itemValue, tempOut_nullableScope4)); + nullableScope = tempOut_nullableScope4.argValue; + tupleScope = tempRef_tupleScope4.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert !tupleScope.MoveNext(row, ref nullableScope); + + tangible.RefObject tempRef_outerScope9 = + new tangible.RefObject(outerScope); + tangible.RefObject tempRef_temp3 = + new tangible.RefObject(temp); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_outerScope9, + tempRef_temp3)); + temp = tempRef_temp3.argValue; + outerScope = tempRef_outerScope9.argValue; + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test types.")] private sealed class Nullables + private final static class Nullables { + public ArrayList NullArray; + public ArrayList NullBool; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public Dictionary> NullMap; + public HashMap NullMap; + public ArrayList<(Integer,Long)>NullTuple + public ArrayList NullSet; + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof Nullables; + Nullables nullables = tempVar ? (Nullables)obj : null; + return tempVar && this.equals(nullables); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + int hashCode = 0; + hashCode = (hashCode * 397) ^ (this.NullBool == null ? null : this.NullBool.hashCode() != null ? this.NullBool.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.NullSet == null ? null : this.NullSet.hashCode() != null ? this.NullSet.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.NullArray == null ? null : this.NullArray.hashCode() != null ? this.NullArray.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.NullTuple == null ? null : this.NullTuple.hashCode() != null ? this.NullTuple.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.NullMap == null ? null : this.NullMap.hashCode() != null ? this.NullMap.hashCode() : 0); + return hashCode; + } + } + + private static boolean MapEquals(HashMap left, HashMap right) { + if (left.size() != right.size()) { + return false; + } + + for (Map.Entry item : left.entrySet()) { + TValue value; + if (!(right.containsKey(item.getKey()) && (value = right.get(item.getKey())) == value)) { + return false; + } + + if (!item.getValue().equals(value)) { + return false; + } + } + + return true; + } + + private boolean equals(Nullables other) { + //C# TO JAVA CONVERTER WARNING: Java AbstractList 'equals' is not always identical to LINQ 'SequenceEqual': + //ORIGINAL LINE: return (object.ReferenceEquals(this.NullBool, other.NullBool) || ((this.NullBool != null) && (other.NullBool != null) && this.NullBool.SequenceEqual(other.NullBool))) && (object.ReferenceEquals(this.NullSet, other.NullSet) || ((this.NullSet != null) && (other.NullSet != null) && this.NullSet.SequenceEqual(other.NullSet))) && (object.ReferenceEquals(this.NullArray, other.NullArray) || ((this.NullArray != null) && (other.NullArray != null) && this.NullArray.SequenceEqual(other.NullArray))) && (object.ReferenceEquals(this.NullTuple, other.NullTuple) || ((this.NullTuple != null) && (other.NullTuple != null) && this.NullTuple.SequenceEqual(other.NullTuple))) && (object.ReferenceEquals(this.NullMap, other.NullMap) || ((this.NullMap != null) && (other.NullMap != null) && Nullables.MapEquals(this.NullMap, other.NullMap))); + return (this.NullBool == other.NullBool || ((this.NullBool != null) && (other.NullBool != null) && this.NullBool.equals(other.NullBool))) && (this.NullSet == other.NullSet || ((this.NullSet != null) && (other.NullSet != null) && this.NullSet.equals(other.NullSet))) && (this.NullArray == other.NullArray || ((this.NullArray != null) && (other.NullArray != null) && this.NullArray.equals(other.NullArray))) && (this.NullTuple == other.NullTuple || ((this.NullTuple != null) && (other.NullTuple != null) && this.NullTuple.equals(other.NullTuple))) && (this.NullMap == other.NullMap || ((this.NullMap != null) && (other.NullMap != null) && Nullables.MapEquals(this.NullMap, other.NullMap))); + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/PermuteExtensions.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/PermuteExtensions.java new file mode 100644 index 0000000..8677a47 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/PermuteExtensions.java @@ -0,0 +1,34 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +/** + * Extension methods for computing permutations of . + */ +public final class PermuteExtensions { + /** + * Generate all permutations of a given enumerable. + */ + public static java.lang.Iterable> Permute(java.lang.Iterable list) { + int start = 0; + for (T element : list) { + int index = start; + T[] first = { element }; + java.lang.Iterable rest = list.Where((s, i) -> i != index); + if (!rest.Any()) { + // TODO: C# TO JAVA CONVERTER: Java does not have an equivalent to the C# 'yield' keyword: + yield return first; + } + + for (java.lang.Iterable sub : + Microsoft.Azure.Cosmos.Serialization.HybridRow.Tests.Unit.PermuteExtensions.Permute(rest)) { + // TODO: C# TO JAVA CONVERTER: Java does not have an equivalent to the C# 'yield' keyword: + yield return first.Concat(sub); + } + + start++; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RandomGeneratorUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RandomGeneratorUnitTests.java new file mode 100644 index 0000000..d38be9d --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RandomGeneratorUnitTests.java @@ -0,0 +1,78 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import java.util.Random; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass] public class RandomGeneratorUnitTests +public class RandomGeneratorUnitTests { + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void RangeTest() + public final void RangeTest() { + int seed = 42; + RandomGenerator rand = new RandomGenerator(new Random(seed)); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong l1 = rand.NextUInt64(); + long l1 = rand.NextUInt64(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong l2 = rand.NextUInt64(); + long l2 = rand.NextUInt64(); + assert l1 != l2; + + System.out.println("Check full range of min/max for ushort."); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: for (int min = 0; min <= ushort.MaxValue; min++) + for (int min = 0; min <= Short.MAX_VALUE; min++) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ushort i1 = rand.NextUInt16((ushort)min, ushort.MaxValue); + short i1 = rand.NextUInt16((short)min, Short.MAX_VALUE); + assert i1 >= min; + } + + System.out.println("Check ushort range of min/max for uint."); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: for (uint min = 0; min <= (uint)ushort.MaxValue; min++) + for (int min = 0; min <= (int)Short.MAX_VALUE; min++) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: uint i1 = rand.NextUInt32(min, (uint)ushort.MaxValue); + int i1 = rand.NextUInt32(min, (int)Short.MAX_VALUE); + assert i1 >= min; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Assert.IsTrue(i1 <= ushort.MaxValue); + assert i1 <= Short.MAX_VALUE; + } + + boolean seenMax = false; + boolean seenMin = false; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: const ushort maxUShortRange = 10; + final short maxUShortRange = 10; + System.out.println("Check inclusivity for ushort."); + while (!(seenMax && seenMin)) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ushort i1 = rand.NextUInt16(ushort.MinValue, maxUShortRange); + short i1 = rand.NextUInt16(Short.MIN_VALUE, maxUShortRange); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: seenMin = seenMin || i1 == ushort.MinValue; + seenMin = seenMin || i1 == Short.MIN_VALUE; + seenMax = seenMax || i1 == maxUShortRange; + assert i1 <= maxUShortRange; + } + + seenMax = false; + seenMin = false; + System.out.println("Check inclusivity for short."); + final short minShortRange = -10; + final short maxShortRange = 10; + while (!(seenMax && seenMin)) { + short i1 = rand.NextInt16(minShortRange, maxShortRange); + seenMin = seenMin || i1 == -10; + seenMax = seenMax || i1 == 10; + assert i1 >= minShortRange; + assert i1 <= maxShortRange; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ReadRowDispatcher.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ReadRowDispatcher.java new file mode 100644 index 0000000..4565a88 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ReadRowDispatcher.java @@ -0,0 +1,234 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.util.Collection; +import java.util.List; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: internal struct ReadRowDispatcher : IDispatcher +public final class ReadRowDispatcher implements IDispatcher { + + public , TValue> void Dispatch(tangible.RefObject dispatcher, tangible.RefObject root, LayoutColumn col, LayoutType t) { + Dispatch(dispatcher, root, col, t, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public void Dispatch(ref RowOperationDispatcher dispatcher, ref RowCursor root, + // LayoutColumn col, LayoutType t, TValue expected = default) where TLayout : LayoutType + public , TValue> void Dispatch(tangible.RefObject dispatcher, tangible.RefObject root, LayoutColumn col, LayoutType t, TValue expected) { + TValue value; + switch (col == null ? null : col.getStorage()) { + case Fixed: + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + tangible.OutObject tempOut_value = new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadFixed(tempRef_Row, root, col, tempOut_value)); + value = tempOut_value.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + break; + case Variable: + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + tangible.OutObject tempOut_value2 = new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadVariable(tempRef_Row2, root, col, tempOut_value2)); + value = tempOut_value2.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + break; + default: + tangible.RefObject tempRef_Row3 = + new tangible.RefObject(dispatcher.argValue.Row); + tangible.OutObject tempOut_value3 = new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadSparse(tempRef_Row3, root, tempOut_value3)); + value = tempOut_value3.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row3.argValue; + break; + } + + if (TValue.class.IsArray) { + CollectionAssert.AreEqual((Collection)expected, (Collection)value); + } else { + assert expected == value; + } + } + + public void DispatchArray(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 1); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor arrayScope; + tangible.OutObject tempOut_arrayScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadScope(tempRef_Row, scope, tempOut_arrayScope)); + arrayScope = tempOut_arrayScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + + int i = 0; + List items = (List)value; + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + while (arrayScope.MoveNext(tempRef_Row2)) { + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + dispatcher.argValue.LayoutCodeSwitch(ref arrayScope, null, typeArgs.get(0).getType(), + typeArgs.get(0).getTypeArgs().clone(), items.get(i++)); + } + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + } + + public void DispatchMap(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 2); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor mapScope; + tangible.OutObject tempOut_mapScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadScope(tempRef_Row, scope, tempOut_mapScope)); + mapScope = tempOut_mapScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + int i = 0; + List items = (List)value; + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + while (mapScope.MoveNext(tempRef_Row2)) { + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + dispatcher.argValue.LayoutCodeSwitch(ref mapScope, null, LayoutType.TypedTuple, typeArgs.clone(), + items.get(i++)); + } + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + } + + public void DispatchNullable(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 1); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor nullableScope; + tangible.OutObject tempOut_nullableScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadScope(tempRef_Row, scope, tempOut_nullableScope)); + nullableScope = tempOut_nullableScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + + if (value != null) { + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + tangible.RefObject tempRef_nullableScope = + new tangible.RefObject(nullableScope); + ResultAssert.IsSuccess(LayoutNullable.HasValue(tempRef_Row2, tempRef_nullableScope)); + nullableScope = tempRef_nullableScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + tangible.RefObject tempRef_Row3 = + new tangible.RefObject(dispatcher.argValue.Row); + nullableScope.MoveNext(tempRef_Row3); + dispatcher.argValue.argValue.Row = tempRef_Row3.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + dispatcher.argValue.LayoutCodeSwitch(ref nullableScope, null, typeArgs.get(0).getType(), + typeArgs.get(0).getTypeArgs().clone(), value); + } else { + tangible.RefObject tempRef_Row4 = + new tangible.RefObject(dispatcher.argValue.Row); + tangible.RefObject tempRef_nullableScope2 = + new tangible.RefObject(nullableScope); + ResultAssert.NotFound(LayoutNullable.HasValue(tempRef_Row4, tempRef_nullableScope2)); + nullableScope = tempRef_nullableScope2.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row4.argValue; + } + } + + public void DispatchObject(tangible.RefObject dispatcher, + tangible.RefObject scope) { + } + + public void DispatchSet(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 1); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor setScope; + tangible.OutObject tempOut_setScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadScope(tempRef_Row, scope, tempOut_setScope)); + setScope = tempOut_setScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + int i = 0; + List items = (List)value; + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + while (setScope.MoveNext(tempRef_Row2)) { + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + dispatcher.argValue.LayoutCodeSwitch(ref setScope, null, typeArgs.get(0).getType(), + typeArgs.get(0).getTypeArgs().clone(), items.get(i++)); + } + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + } + + public void DispatchTuple(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() >= 2); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor tupleScope; + tangible.OutObject tempOut_tupleScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadScope(tempRef_Row, scope, tempOut_tupleScope)); + tupleScope = tempOut_tupleScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + + for (int i = 0; i < typeArgs.getCount(); i++) { + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + tupleScope.MoveNext(tempRef_Row2); + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + PropertyInfo valueAccessor = value.getClass().GetProperty(String.format("Item%1$s", i + 1)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + dispatcher.argValue.LayoutCodeSwitch(ref tupleScope, null, typeArgs.get(i).getType(), + typeArgs.get(i).getTypeArgs().clone(), valueAccessor.GetValue(value)); + } + } + + public void DispatchUDT(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + tangible.RefObject tempRef_Row = new tangible.RefObject(dispatcher.argValue.Row); + RowCursor udtScope; + tangible.OutObject tempOut_udtScope = new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().ReadScope(tempRef_Row, scope, tempOut_udtScope)); + udtScope = tempOut_udtScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + IDispatchable valueDispatcher = value instanceof IDispatchable ? (IDispatchable)value : null; + assert valueDispatcher != null; + tangible.RefObject tempRef_udtScope = new tangible.RefObject(udtScope); + valueDispatcher.Dispatch(dispatcher, tempRef_udtScope); + udtScope = tempRef_udtScope.argValue; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RecordIOUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RecordIOUnitTests.java new file mode 100644 index 0000000..2189058 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RecordIOUnitTests.java @@ -0,0 +1,237 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.MemorySpanResizer; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; + +import java.nio.file.Files; +import java.util.ArrayList; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Fields should be private + + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][DeploymentItem(RecordIOUnitTests.SchemaFile, "TestData")] public class RecordIOUnitTests +public class RecordIOUnitTests { + private static final int InitialRowSize = 0; + private static final String SchemaFile = "TestData\\CustomerSchema.json"; + private Layout addressLayout; + private Namespace ns; + private LayoutResolver resolver; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void LoadSchema() + public final void LoadSchema() { + LayoutResolver systemResolver = SystemSchema.LayoutResolver; + Layout segmentLayout = systemResolver.Resolve(SystemSchema.SegmentSchemaId); + assert segmentLayout.getName().equals("Segment"); + assert segmentLayout.getSchemaId().clone() == SystemSchema.SegmentSchemaId; + + Layout recordLayout = systemResolver.Resolve(SystemSchema.RecordSchemaId); + assert recordLayout.getName().equals("Record"); + assert recordLayout.getSchemaId().clone() == SystemSchema.RecordSchemaId; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public final void ParseNamespaceExample() { + String json = Files.readString(RecordIOUnitTests.SchemaFile); + this.ns = Namespace.Parse(json); + this.resolver = new LayoutResolverNamespace(this.ns); + this.addressLayout = this.resolver.Resolve(tangible.ListHelper.find(this.ns.getSchemas(), x -> x.Name.equals( + "Address")).SchemaId); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public async Task RoundTripAsync() + // TODO: C# TO JAVA CONVERTER: There is no equivalent in Java to the 'async' keyword: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public async Task RoundTripAsync() + public final Task RoundTripAsync() { + Address tempVar = new Address(); + tempVar.setStreet("300B Chocolate Hole"); + tempVar.setCity("Great Cruz Bay"); + tempVar.setState("VI"); + PostalCode tempVar2 = new PostalCode(); + tempVar2.setZip(00830); + tempVar2.setPlus4(0001); + tempVar.setPostalCode(tempVar2); + Address tempVar3 = new Address(); + tempVar3.setStreet("1 Microsoft Way"); + tempVar3.setCity("Redmond"); + tempVar3.setState("WA"); + PostalCode tempVar4 = new PostalCode(); + tempVar4.setZip(98052); + tempVar3.setPostalCode(tempVar4); + Address[] addresses = { tempVar, tempVar3 }; + + String sampleComment = "hello there"; + String sampleSDL = "some SDL"; + + try (Stream stm = new MemoryStream()) { + // Create a reusable, resizable buffer. + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MemorySpanResizer resizer = new MemorySpanResizer(RecordIOUnitTests + // .InitialRowSize); + MemorySpanResizer resizer = new MemorySpanResizer(RecordIOUnitTests.InitialRowSize); + + // Write a RecordIO stream. + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'out' keyword - these are + // not converted by C# to Java Converter: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: Result r = await stm.WriteRecordIOAsync(new Segment(sampleComment, sampleSDL), (long + // index, out ReadOnlyMemory body) => + Result r = await + Microsoft.Azure.Cosmos.Serialization.HybridRow.RecordIO.RecordIOStream.WriteRecordIOAsync(stm, + new Segment(sampleComment, sampleSDL), (long index, out ReadOnlyMemorybody) -> + { + body = null; + if (index >= addresses.length) { + return Result.Success; + } + + tangible.OutObject> tempOut_body = new tangible.OutObject>(); + Task tempVar5 = this.WriteAddress(resizer, addresses[index], tempOut_body); + body = tempOut_body.argValue; + return tempVar5; + }); + + // Read a RecordIO stream. + ArrayList
addressesRead = new ArrayList
(); + stm.Position = 0; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: resizer = new MemorySpanResizer(1); + resizer = new MemorySpanResizer(1); + // TODO: C# TO JAVA CONVERTER: There is no equivalent to 'await' in Java: + r = await + Microsoft.Azure.Cosmos.Serialization.HybridRow.RecordIO.RecordIOStream.ReadRecordIOAsync(stm, record -> + { + assert !record.IsEmpty; + + Address obj; + tangible.OutObject tempOut_obj = new tangible.OutObject(); + r = this.ReadAddress(record, tempOut_obj); + obj = tempOut_obj.argValue; + ResultAssert.IsSuccess(r); + addressesRead.add(obj); + return Result.Success; + }, segment -> + { + assert !segment.IsEmpty; + + Segment obj; + tangible.OutObject tempOut_obj = + new tangible.OutObject(); + r = this.ReadSegment(segment, tempOut_obj); + obj = tempOut_obj.argValue; + ResultAssert.IsSuccess(r); + assert obj.Comment == sampleComment; + assert obj.SDL == sampleSDL; + return Result.Success; + }, resizer); + + ResultAssert.IsSuccess(r); + + // Check that the values all round-tripped. + assert addresses.length == addressesRead.size(); + for (int i = 0; i < addresses.length; i++) { + assert addresses[i] == addressesRead.get(i); + } + } + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private Result ReadAddress(Memory buffer, out Address obj) + private Result ReadAddress(Memory buffer, tangible.OutObject
obj) { + RowBuffer row = new RowBuffer(buffer.Span, HybridRowVersion.V1, this.resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row); + row = tempRef_row.argValue; + + // Use the reader to dump to the screen. + tangible.RefObject tempRef_reader = + new tangible.RefObject(reader); + String str; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = DiagnosticConverter.ReaderToString(tempRef_reader, out str); + reader = tempRef_reader.argValue; + if (r != Result.Success) { + obj.argValue = null; + return r; + } + + System.out.println(str); + + // Reset the reader and materialize the object. + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + reader = new RowReader(tempRef_row2); + row = tempRef_row2.argValue; + tangible.RefObject tempRef_reader2 = + new tangible.RefObject(reader); + Result tempVar = AddressSerializer.Read(tempRef_reader2, obj); + reader = tempRef_reader2.argValue; + return tempVar; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private Result ReadSegment(Memory buffer, out Segment obj) + private Result ReadSegment(Memory buffer, tangible.OutObject obj) { + RowBuffer row = new RowBuffer(buffer.Span, HybridRowVersion.V1, SystemSchema.LayoutResolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row); + row = tempRef_row.argValue; + + // Use the reader to dump to the screen. + tangible.RefObject tempRef_reader = + new tangible.RefObject(reader); + String str; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = DiagnosticConverter.ReaderToString(tempRef_reader, out str); + reader = tempRef_reader.argValue; + if (r != Result.Success) { + obj.argValue = null; + return r; + } + + System.out.println(str); + + // Reset the reader and materialize the object. + tangible.RefObject tempRef_row2 = new tangible.RefObject(row); + reader = new RowReader(tempRef_row2); + row = tempRef_row2.argValue; + tangible.RefObject tempRef_reader2 = new tangible.RefObject(reader); + Result tempVar = SegmentSerializer.Read(tempRef_reader2, obj.clone()); + reader = tempRef_reader2.argValue; + return tempVar; + } + + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private Result WriteAddress(MemorySpanResizer resizer, Address obj, out + // ReadOnlyMemory buffer) + private Result WriteAddress(MemorySpanResizer resizer, Address obj, + tangible.OutObject> buffer) { + RowBuffer row = new RowBuffer(RecordIOUnitTests.InitialRowSize, resizer); + row.InitLayout(HybridRowVersion.V1, this.addressLayout, this.resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + Result r = RowWriter.WriteBuffer(tempRef_row, obj, AddressSerializer.Write); + row = tempRef_row.argValue; + if (r != Result.Success) { + buffer.argValue = null; + return r; + } + + buffer.argValue = resizer.getMemory().Slice(0, row.getLength()); + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ResultAssert.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ResultAssert.java new file mode 100644 index 0000000..89f28fd --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/ResultAssert.java @@ -0,0 +1,81 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.Result; + +public final class ResultAssert { + public static void Exists(Result actual) { + assert Result.Exists == actual; + } + + public static void Exists(Result actual, String message) { + Assert.AreEqual(Result.Exists, actual, message); + } + + public static void Exists(Result actual, String message, Object... parameters) { + Assert.AreEqual(Result.Exists, actual, message, parameters); + } + + public static void InsufficientPermissions(Result actual) { + assert Result.InsufficientPermissions == actual; + } + + public static void InsufficientPermissions(Result actual, String message) { + Assert.AreEqual(Result.InsufficientPermissions, actual, message); + } + + public static void InsufficientPermissions(Result actual, String message, Object... parameters) { + Assert.AreEqual(Result.InsufficientPermissions, actual, message, parameters); + } + + public static void IsSuccess(Result actual) { + assert Result.Success == actual; + } + + public static void IsSuccess(Result actual, String message) { + Assert.AreEqual(Result.Success, actual, message); + } + + public static void IsSuccess(Result actual, String message, Object... parameters) { + Assert.AreEqual(Result.Success, actual, message, parameters); + } + + public static void NotFound(Result actual) { + assert Result.NotFound == actual; + } + + public static void NotFound(Result actual, String message) { + Assert.AreEqual(Result.NotFound, actual, message); + } + + public static void NotFound(Result actual, String message, Object... parameters) { + Assert.AreEqual(Result.NotFound, actual, message, parameters); + } + + public static void TypeConstraint(Result actual) { + assert Result.TypeConstraint == actual; + } + + public static void TypeConstraint(Result actual, String message) { + Assert.AreEqual(Result.TypeConstraint, actual, message); + } + + public static void TypeConstraint(Result actual, String message, Object... parameters) { + Assert.AreEqual(Result.TypeConstraint, actual, message, parameters); + } + + public static void TypeMismatch(Result actual) { + assert Result.TypeMismatch == actual; + } + + public static void TypeMismatch(Result actual, String message) { + Assert.AreEqual(Result.TypeMismatch, actual, message); + } + + public static void TypeMismatch(Result actual, String message, Object... parameters) { + Assert.AreEqual(Result.TypeMismatch, actual, message, parameters); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowBufferUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowBufferUnitTests.java new file mode 100644 index 0000000..6f4f343 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowBufferUnitTests.java @@ -0,0 +1,71 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.RowBuffer; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass] public class RowBufferUnitTests +public class RowBufferUnitTests { + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][SuppressMessage("StyleCop.CSharp.ReadabilityRules", + // "SA1139:UseLiteralsSuffixNotationInsteadOfCasting", Justification = "Explicit")] public void VarIntTest() + public final void VarIntTest() { + // Brute force test all signed 16-bit values. + for (int i = Short.MIN_VALUE; i <= Short.MAX_VALUE; i++) { + short s = (short)i; + this.RoundTripVarInt(s); + } + + // Test boundary conditions for larger values. + this.RoundTripVarInt(0); + this.RoundTripVarInt(Integer.MIN_VALUE); + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.RoundTripVarInt(unchecked((int)0x80000000ul)); + this.RoundTripVarInt(0x80000000); + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.RoundTripVarInt(unchecked((int)0x7FFFFFFFul)); + this.RoundTripVarInt(0x7FFFFFFF); + this.RoundTripVarInt(Integer.MAX_VALUE); + this.RoundTripVarInt(Long.MIN_VALUE); + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.RoundTripVarInt(unchecked((long)0x8000000000000000ul)); + this.RoundTripVarInt((long)0x8000000000000000); + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: this.RoundTripVarInt(unchecked((long)0x7FFFFFFFFFFFFFFFul)); + this.RoundTripVarInt((long)0x7FFFFFFFFFFFFFFF); + this.RoundTripVarInt(Long.MAX_VALUE); + } + + private void RoundTripVarInt(short s) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong encoded = RowBuffer.RotateSignToLsb(s); + long encoded = RowBuffer.RotateSignToLsb(s); + long decoded = RowBuffer.RotateSignToMsb(encoded); + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: short t = unchecked((short)decoded); + short t = (short)decoded; + Assert.AreEqual(s, t, "Value: {0}", s); + } + + private void RoundTripVarInt(int s) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong encoded = RowBuffer.RotateSignToLsb(s); + long encoded = RowBuffer.RotateSignToLsb(s); + long decoded = RowBuffer.RotateSignToMsb(encoded); + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to 'unchecked' in this context: + //ORIGINAL LINE: int t = unchecked((int)decoded); + int t = (int)decoded; + Assert.AreEqual(s, t, "Value: {0}", s); + } + + private void RoundTripVarInt(long s) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ulong encoded = RowBuffer.RotateSignToLsb(s); + long encoded = RowBuffer.RotateSignToLsb(s); + long decoded = RowBuffer.RotateSignToMsb(encoded); + Assert.AreEqual(s, decoded, "Value: {0}", s); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowOperationDispatcher.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowOperationDispatcher.java new file mode 100644 index 0000000..97902dc --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowOperationDispatcher.java @@ -0,0 +1,406 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.NullValue; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.UUID; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1402 // FileMayOnlyContainASingleType +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1201 // OrderingRules +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Public Fields + + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: internal ref struct RowOperationDispatcher +//C# TO JAVA CONVERTER WARNING: Java has no equivalent to the C# ref struct: +public final class RowOperationDispatcher { + private static final int InitialRowSize = 2 * 1024 * 1024; + public LayoutResolver Resolver; + public RowBuffer Row = new RowBuffer(); + private IDispatcher dispatcher; + + public RowOperationDispatcher() { + } + + private RowOperationDispatcher(IDispatcher dispatcher, Layout layout, LayoutResolver resolver) { + this.dispatcher = dispatcher; + this.Row = new RowBuffer(RowOperationDispatcher.InitialRowSize); + this.Resolver = resolver; + this.Row.InitLayout(HybridRowVersion.V1, layout, this.Resolver); + } + + private RowOperationDispatcher(IDispatcher dispatcher, LayoutResolver resolver, String expected) { + this.dispatcher = dispatcher; + this.Row = new RowBuffer(RowOperationDispatcher.InitialRowSize); + this.Resolver = resolver; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: byte[] bytes = ByteConverter.ToBytes(expected); + byte[] bytes = ByteConverter.ToBytes(expected); + this.Row.ReadFrom(bytes, HybridRowVersion.V1, this.Resolver); + } + + // TODO: C# TO JAVA CONVERTER: The C# 'struct' constraint has no equivalent in Java: + //ORIGINAL LINE: public static RowOperationDispatcher Create(Layout layout, LayoutResolver resolver) + // where TDispatcher : struct, IDispatcher + public static RowOperationDispatcher Create(Layout layout, + LayoutResolver resolver) { + return new RowOperationDispatcher(null, layout, resolver); + } + + public RowReader GetReader() { + tangible.RefObject tempRef_Row = + new tangible.RefObject(this.Row); + // TODO: C# TO JAVA CONVERTER: The following line could not be converted: + return new RowReader(ref this.Row) + this.Row = tempRef_Row.argValue; + return tempVar; + } + + public void LayoutCodeSwitch(String path, LayoutType type, TypeArgumentList typeArgs) { + LayoutCodeSwitch(path, type, typeArgs, null); + } + + public void LayoutCodeSwitch(String path, LayoutType type) { + LayoutCodeSwitch(path, type, null, null); + } + + public void LayoutCodeSwitch(String path) { + LayoutCodeSwitch(path, null, null, null); + } + + public void LayoutCodeSwitch() { + LayoutCodeSwitch(null, null, null, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public void LayoutCodeSwitch(string path = null, LayoutType type = null, TypeArgumentList + // typeArgs = default, object value = null) + public void LayoutCodeSwitch(String path, LayoutType type, TypeArgumentList typeArgs, Object value) { + tangible.RefObject tempRef_Row = + new tangible.RefObject(this.Row); + RowCursor root = RowCursor.Create(tempRef_Row); + this.Row = tempRef_Row.argValue; + tangible.RefObject tempRef_root = + new tangible.RefObject(root); + this.LayoutCodeSwitch(tempRef_root, path, type, typeArgs.clone(), value); + root = tempRef_root.argValue; + } + + public void LayoutCodeSwitch(tangible.RefObject scope, String path, LayoutType type, + TypeArgumentList typeArgs) { + LayoutCodeSwitch(scope, path, type, typeArgs, null); + } + + public void LayoutCodeSwitch(tangible.RefObject scope, String path, LayoutType type) { + LayoutCodeSwitch(scope, path, type, null, null); + } + + public void LayoutCodeSwitch(tangible.RefObject scope, String path) { + LayoutCodeSwitch(scope, path, null, null, null); + } + + public void LayoutCodeSwitch(tangible.RefObject scope) { + LayoutCodeSwitch(scope, null, null, null, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public void LayoutCodeSwitch(ref RowCursor scope, string path = null, LayoutType type = null, + // TypeArgumentList typeArgs = default, object value = null) + public void LayoutCodeSwitch(tangible.RefObject scope, String path, LayoutType type, + TypeArgumentList typeArgs, Object value) { + LayoutColumn col = null; + if (type == null) { + assert path != null; + tangible.OutObject tempOut_col = + new tangible.OutObject(); + assert scope.argValue.getLayout().TryFind(path, tempOut_col); + col = tempOut_col.argValue; + assert col != null; + type = col.getType(); + typeArgs = col.getTypeArgs().clone(); + } + + if ((path != null) && (col == null || col.getStorage() == StorageKind.Sparse)) { + tangible.RefObject tempRef_Row = + new tangible.RefObject(this.Row); + scope.argValue.Find(tempRef_Row, path); + this.Row = tempRef_Row.argValue; + } + + switch (type.LayoutCode) { + case Null: + tangible.RefObject tempRef_this = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this, scope, col, type, NullValue.Default); + this = tempRef_this.argValue; + break; + case Boolean: + tangible.RefObject tempRef_this2 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this2, scope, col, type, + value != null ? value : + default) + this = tempRef_this2.argValue; + + break; + case Int8: + tangible.RefObject tempRef_this3 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this3, scope, col, type, value != null ? + value : + default) + this = tempRef_this3.argValue; + + break; + case Int16: + tangible.RefObject tempRef_this4 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this4, scope, col, type, value != null ? + value : + default) + this = tempRef_this4.argValue; + + break; + case Int32: + tangible.RefObject tempRef_this5 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this5, scope, col, type, + value != null ? value : + default) + this = tempRef_this5.argValue; + break; + case Int64: + tangible.RefObject tempRef_this6 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this6, scope, col, type, value != null ? + value : + default) + this = tempRef_this6.argValue; + break; + case UInt8: + tangible.RefObject tempRef_this7 = new tangible.RefObject(this); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.dispatcher.Dispatch(tempRef_this7, scope, col, type, + // (Nullable)value != null ? value : default); + this.dispatcher.Dispatch(tempRef_this7, scope, col, type, value != null ? + value : + default) + this = tempRef_this7.argValue; + break; + case UInt16: + tangible.RefObject tempRef_this8 = new tangible.RefObject(this); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.dispatcher.Dispatch(tempRef_this8, scope, col, type, + // (Nullable)value != null ? value : default); + this.dispatcher.Dispatch(tempRef_this8, scope, col, type, value != null ? + value : + default) + this = tempRef_this8.argValue; + + break; + case UInt32: + tangible.RefObject tempRef_this9 = new tangible.RefObject(this); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.dispatcher.Dispatch(tempRef_this9, scope, col, type, + // (Nullable)value != null ? value : default); + this.dispatcher.Dispatch(tempRef_this9, scope, col, type, + value != null ? value : + default) + this = tempRef_this9.argValue; + break; + case UInt64: + tangible.RefObject tempRef_this10 = new tangible.RefObject(this); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.dispatcher.Dispatch(tempRef_this10, scope, col, type, + // (Nullable)value != null ? value : default); + this.dispatcher.Dispatch(tempRef_this10, scope, col, type, value != null ? + value : + default) + this = tempRef_this10.argValue; + + break; + case VarInt: + tangible.RefObject tempRef_this11 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this11, scope, col, type, value != null ? + value : + default) + this = tempRef_this11.argValue; + break; + case VarUInt: + tangible.RefObject tempRef_this12 = new tangible.RefObject(this); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.dispatcher.Dispatch(tempRef_this12, scope, col, type, + // (Nullable)value != null ? value : default); + this.dispatcher.Dispatch(tempRef_this12, scope, col, type, value != null ? + value : + default) + this = tempRef_this12.argValue; + + break; + case Float32: + tangible.RefObject tempRef_this13 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this13, scope, col, type, + value != null ? value : + default) + this = tempRef_this13.argValue; + + break; + case Float64: + tangible.RefObject tempRef_this14 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this14, scope, col, type, + value != null ? value : + default) + this = tempRef_this14.argValue; + + break; + case Float128: + tangible.RefObject tempRef_this15 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this15, scope, col, type, + value != null ? value : + default) + this = tempRef_this15.argValue; + + break; + case Decimal: + tangible.RefObject tempRef_this16 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this16, scope, col, type, + value != null ? value : + default) + this = tempRef_this16.argValue; + + break; + case DateTime: + tangible.RefObject tempRef_this17 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this17, scope, col, type, + value != null ? value : + default) + this = tempRef_this17.argValue; + + break; + case UnixDateTime: + tangible.RefObject tempRef_this18 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this18, scope, col, type, + value != null ? value : + default) + this = tempRef_this18.argValue; + + break; + case Guid: + tangible.RefObject tempRef_this19 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this19, scope, col, type, value != null ? + value : + default) + this = tempRef_this19.argValue; + break; + case MongoDbObjectId: + tangible.RefObject tempRef_this20 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this20, scope, col, type, + value != null ? value : + default) + this = tempRef_this20.argValue; + + break; + case Utf8: + tangible.RefObject tempRef_this21 = new tangible.RefObject(this); + this.dispatcher.Dispatch(tempRef_this21, scope, col, type, (String)value); + this = tempRef_this21.argValue; + + break; + case Binary: + tangible.RefObject tempRef_this22 = new tangible.RefObject(this); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: this.dispatcher.Dispatch(ref this, ref scope, col, type, + // (byte[])value); + this.dispatcher.Dispatch(tempRef_this22, scope, col, type, (byte[])value); + this = tempRef_this22.argValue; + + break; + case ObjectScope: + case ImmutableObjectScope: + tangible.RefObject tempRef_this23 = new tangible.RefObject(this); + this.dispatcher.DispatchObject(tempRef_this23, scope); + this = tempRef_this23.argValue; + break; + case TypedArrayScope: + case ImmutableTypedArrayScope: + tangible.RefObject tempRef_this24 = new tangible.RefObject(this); + this.dispatcher.DispatchArray(tempRef_this24, scope, type, typeArgs.clone(), value); + this = tempRef_this24.argValue; + break; + case TypedSetScope: + case ImmutableTypedSetScope: + tangible.RefObject tempRef_this25 = new tangible.RefObject(this); + this.dispatcher.DispatchSet(tempRef_this25, scope, type, typeArgs.clone(), value); + this = tempRef_this25.argValue; + break; + case TypedMapScope: + case ImmutableTypedMapScope: + tangible.RefObject tempRef_this26 = new tangible.RefObject(this); + this.dispatcher.DispatchMap(tempRef_this26, scope, type, typeArgs.clone(), value); + this = tempRef_this26.argValue; + break; + case TupleScope: + case ImmutableTupleScope: + case TypedTupleScope: + case ImmutableTypedTupleScope: + case TaggedScope: + case ImmutableTaggedScope: + case Tagged2Scope: + case ImmutableTagged2Scope: + tangible.RefObject tempRef_this27 = new tangible.RefObject(this); + this.dispatcher.DispatchTuple(tempRef_this27, scope, type, typeArgs.clone(), value); + this = tempRef_this27.argValue; + break; + case NullableScope: + tangible.RefObject tempRef_this28 = new tangible.RefObject(this); + this.dispatcher.DispatchNullable(tempRef_this28, scope, type, typeArgs.clone(), value); + this = tempRef_this28.argValue; + break; + case Schema: + case ImmutableSchema: + tangible.RefObject tempRef_this29 = new tangible.RefObject(this); + this.dispatcher.DispatchUDT(tempRef_this29, scope, type, typeArgs.clone(), value); + this = tempRef_this29.argValue; + break; + default: + Contract.Assert(false, String.format("Unknown type will be ignored: %1$s", type.LayoutCode)); + break; + } + } + + // TODO: C# TO JAVA CONVERTER: The C# 'struct' constraint has no equivalent in Java: + //ORIGINAL LINE: public static RowOperationDispatcher ReadFrom(LayoutResolver resolver, string + // expected) where TDispatcher : struct, IDispatcher + public static RowOperationDispatcher ReadFrom(LayoutResolver resolver, + String expected) { + return new RowOperationDispatcher(null, resolver, expected); + } + + public String RowToHex() { + try (MemoryStream stm = new MemoryStream()) { + this.Row.WriteTo(stm); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ReadOnlyMemory bytes = stm.GetBuffer().AsMemory(0, (int)stm.Position); + ReadOnlyMemory bytes = stm.GetBuffer().AsMemory(0, (int)stm.Position); + return ByteConverter.ToHex(bytes.Span); + } + } + + public RowOperationDispatcher clone() { + RowOperationDispatcher varCopy = new RowOperationDispatcher(); + + varCopy.Resolver = this.Resolver; + varCopy.Row = this.Row.clone(); + varCopy.dispatcher = this.dispatcher; + + return varCopy; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowReaderUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowReaderUnitTests.java new file mode 100644 index 0000000..e8b5a56 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowReaderUnitTests.java @@ -0,0 +1,424 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.MemorySpanResizer; +import azure.data.cosmos.serialization.hybridrow.NullValue; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; + +import java.nio.file.Files; +import java.time.LocalDateTime; +import java.util.UUID; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][SuppressMessage("StyleCop.CSharp.ReadabilityRules", +// "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Test code.")][DeploymentItem(RowReaderUnitTests +// .SchemaFile, "TestData")] public sealed class RowReaderUnitTests +public final class RowReaderUnitTests { + private static final LocalDateTime SampleDateTime = LocalDateTime.parse("2018-08-14 02:05:00.0000000"); + private static final Float128 SampleFloat128 = new Float128(0, 42); + private static final UUID SampleGuid = UUID.fromString("{2A9C25B9-922E-4611-BB0A-244A9496503C}"); + private static final MongoDbObjectId SampleMongoDbObjectId = new MongoDbObjectId(0, 42); + private static final UnixDateTime SampleUnixDateTime = new UnixDateTime(42); + private static final String SchemaFile = "TestData\\ReaderSchema.json"; + private LayoutResolver resolver; + private Namespace schema; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public void ParseNamespaceExample() { + String json = Files.readString(RowReaderUnitTests.SchemaFile); + this.schema = Namespace.Parse(json); + this.resolver = new LayoutResolverNamespace(this.schema); + } + + public static void PrintReader(tangible.RefObject reader, int indent) { + String str; + tangible.OutObject tempOut_str = new tangible.OutObject(); + ResultAssert.IsSuccess(DiagnosticConverter.ReaderToString(reader, tempOut_str)); + str = tempOut_str.argValue; + System.out.println(str); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ReadMixed() + public void ReadMixed() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Mixed")).SchemaId); + assert layout != null; + + RowOperationDispatcher d = RowOperationDispatcher.Create(layout, this.resolver); + d.LayoutCodeSwitch("null"); + d.LayoutCodeSwitch("bool", value:true) + d.LayoutCodeSwitch("int8", value:(byte)-86) + d.LayoutCodeSwitch("int16", value:(short)-21846) + d.LayoutCodeSwitch("int32", value:-1431655766) + d.LayoutCodeSwitch("int64", value:-6148914691236517206L) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint8", value: (byte)0xAA); + d.LayoutCodeSwitch("uint8", value:(byte)0xAA) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("uint16", value: (ushort)0xAAAA); + d.LayoutCodeSwitch("uint16", value:(short)0xAAAA) + d.LayoutCodeSwitch("uint32", value:0xAAAAAAAA) + d.LayoutCodeSwitch("uint64", value:0xAAAAAAAAAAAAAAAAL) + d.LayoutCodeSwitch("float32", value:1.0F / 3.0F) + d.LayoutCodeSwitch("float64", value:1.0 / 3.0) + d.LayoutCodeSwitch("float128", value:RowReaderUnitTests.SampleFloat128) + d.LayoutCodeSwitch("decimal", value:java.math.BigDecimal.ONE / 3.0) + d.LayoutCodeSwitch("datetime", value:RowReaderUnitTests.SampleDateTime) + d.LayoutCodeSwitch("unixdatetime", value:RowReaderUnitTests.SampleUnixDateTime) + d.LayoutCodeSwitch("guid", value:RowReaderUnitTests.SampleGuid) + d.LayoutCodeSwitch("mongodbobjectid", value:RowReaderUnitTests.SampleMongoDbObjectId) + d.LayoutCodeSwitch("utf8", value:"abc") + d.LayoutCodeSwitch("utf8_span", value:"abc") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("binary", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("binary", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("binary_span", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("binary_span", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + d.LayoutCodeSwitch("var_varint", value:-6148914691236517206L) + d.LayoutCodeSwitch("var_varuint", value:0xAAAAAAAAAAAAAAAAL) + d.LayoutCodeSwitch("var_utf8", value:"abc") + d.LayoutCodeSwitch("var_utf8_span", value:"abc") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("var_binary", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("var_binary", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("var_binary_span", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("var_binary_span", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + d.LayoutCodeSwitch("sparse_null"); + d.LayoutCodeSwitch("sparse_bool", value:true) + d.LayoutCodeSwitch("sparse_int8", value:(byte)-86) + d.LayoutCodeSwitch("sparse_int16", value:(short)-21846) + d.LayoutCodeSwitch("sparse_int32", value:-1431655766) + d.LayoutCodeSwitch("sparse_int64", value:-6148914691236517206L) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("sparse_uint8", value: (byte)0xAA); + d.LayoutCodeSwitch("sparse_uint8", value:(byte)0xAA) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("sparse_uint16", value: (ushort)0xAAAA); + d.LayoutCodeSwitch("sparse_uint16", value:(short)0xAAAA) + d.LayoutCodeSwitch("sparse_uint32", value:0xAAAAAAAA) + d.LayoutCodeSwitch("sparse_uint64", value:0xAAAAAAAAAAAAAAAAL) + d.LayoutCodeSwitch("sparse_float32", value:1.0F / 3.0F) + d.LayoutCodeSwitch("sparse_float64", value:1.0 / 3.0) + d.LayoutCodeSwitch("sparse_float128", value:RowReaderUnitTests.SampleFloat128) + d.LayoutCodeSwitch("sparse_decimal", value:java.math.BigDecimal.ONE / 3.0) + d.LayoutCodeSwitch("sparse_datetime", value:RowReaderUnitTests.SampleDateTime) + d.LayoutCodeSwitch("sparse_unixdatetime", value:RowReaderUnitTests.SampleUnixDateTime) + d.LayoutCodeSwitch("sparse_guid", value:RowReaderUnitTests.SampleGuid) + d.LayoutCodeSwitch("sparse_mongodbobjectid", value:RowReaderUnitTests.SampleMongoDbObjectId) + d.LayoutCodeSwitch("sparse_utf8", value:"abc") + d.LayoutCodeSwitch("sparse_utf8_span", value:"abc") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("sparse_binary", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("sparse_binary", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("sparse_binary_span", value: new[] { (byte)0, (byte)1, (byte)2 }); + d.LayoutCodeSwitch("sparse_binary_span", value:new byte[] { (byte)0, (byte)1, (byte)2 }) + d.LayoutCodeSwitch("array_t", value:new byte[] { -86, -86, -86 }) + d.LayoutCodeSwitch("array_t>", value:new float[][] + { + new float[] { 1, 2, 3 }, + new float[] { 1, 2, 3 } + }) + d.LayoutCodeSwitch("array_t", value:new String[] { "abc", "def", "hij" }) + d.LayoutCodeSwitch("tuple", value:Tuple.Create(-6148914691236517206L, -6148914691236517206L)) + d.LayoutCodeSwitch("tuple>", value: + Tuple.Create(NullValue.Default, Tuple.Create((byte)-86, (byte)-86))) + d.LayoutCodeSwitch("tuple", value:Tuple.Create(false, new Point(1, 2))) + d.LayoutCodeSwitch("nullable", value:Tuple.Create(null, (Long)123L)) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("tagged", value: Tuple.Create((byte)3, "hello")); + d.LayoutCodeSwitch("tagged", value:Tuple.Create((byte)3, "hello")) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: d.LayoutCodeSwitch("tagged", value: Tuple.Create((byte)5, true, "bye")); + d.LayoutCodeSwitch("tagged", value:Tuple.Create((byte)5, true, "bye")) + d.LayoutCodeSwitch("set_t", value:new String[] { "abc", "efg", "xzy" }) + d.LayoutCodeSwitch("set_t>", value:new byte[][] + { + new byte[] { 1, 2, 3 }, + new byte[] { 4, 5, 6 }, + new byte[] { 7, 8, 9 } + }) + d.LayoutCodeSwitch("set_t>", value:new int[][] + { + new int[] { 1, 2, 3 }, + new int[] { 4, 5, 6 }, + new int[] { 7, 8, 9 } + }) + d.LayoutCodeSwitch("set_t", value:new Point[] + { + new Point(1, 2), + new Point(3, 4), + new Point(5, 6) + }) + d.LayoutCodeSwitch("map_t", value: + new System.Tuple[] { Tuple.Create("Mark", "Luke"), Tuple.Create("Harrison", "Han") }) + d.LayoutCodeSwitch("map_t>", value: + new System.Tuple[] { Tuple.Create((byte)1, new byte[] { 1, 2, 3 }), Tuple.Create((byte)2, + new byte[] { 4, 5, 6 }) }) + + d.LayoutCodeSwitch("map_t>", value: + new System.Tuple[] { Tuple.Create((short)1, new System.Tuple[] { Tuple.Create(1, 2), + Tuple.Create(3, 4) }), Tuple.Create((short)2, new System.Tuple[] { Tuple.Create(5, 6), + Tuple.Create(7, 8) }) }) + + d.LayoutCodeSwitch("map_t", value: + new System.Tuple[] { Tuple.Create(1.0, new Point(1, 2)), Tuple.Create(2.0, new Point(3, 4)), + Tuple.Create(3.0, new Point(5, 6)) }) + + RowReader reader = d.GetReader().clone(); + assert reader.getLength() == d.Row.getLength(); + tangible.RefObject tempRef_reader = + new tangible.RefObject(reader); + RowReaderUnitTests.PrintReader(tempRef_reader, 0); + reader = tempRef_reader.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ReadScopes() + public void ReadScopes() { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: MemorySpanResizer resizer = new MemorySpanResizer(0); + MemorySpanResizer resizer = new MemorySpanResizer(0); + RowBuffer row = new RowBuffer(0, resizer); + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Mixed")).SchemaId); + row.InitLayout(HybridRowVersion.V1, layout, this.resolver); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + ResultAssert.IsSuccess(RowWriter.WriteBuffer(tempRef_row, 2, RowReaderUnitTests.WriteNestedDocument)); + row = tempRef_row.argValue; + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowReader rowReader = new RowReader(tempRef_row2); + row = tempRef_row2.argValue; + + tangible.RefObject tempRef_rowReader = + new tangible.RefObject(rowReader); + ResultAssert.IsSuccess(RowReaderUnitTests.ReadNestedDocumentDelegate(tempRef_rowReader, 0)); + rowReader = tempRef_rowReader.argValue; + + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + rowReader = new RowReader(tempRef_row3); + row = tempRef_row3.argValue; + tangible.RefObject tempRef_rowReader2 = + new tangible.RefObject(rowReader); + ResultAssert.IsSuccess(RowReaderUnitTests.ReadNestedDocumentNonDelegate(tempRef_rowReader2, 0)); + rowReader = tempRef_rowReader2.argValue; + + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + rowReader = new RowReader(tempRef_row4); + row = tempRef_row4.argValue; + tangible.RefObject tempRef_rowReader3 = + new tangible.RefObject(rowReader); + ResultAssert.IsSuccess(RowReaderUnitTests.ReadNestedDocumentNonDelegateWithSkipScope(tempRef_rowReader3, 0)); + rowReader = tempRef_rowReader3.argValue; + + // SkipScope not okay after advancing parent + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + rowReader = new RowReader(tempRef_row5); + row = tempRef_row5.argValue; + assert rowReader.Read(); + assert rowReader.getType().LayoutCode == LayoutCode.ObjectScope; + RowReader nestedScope = rowReader.ReadScope().clone(); + tangible.RefObject tempRef_nestedScope = + new tangible.RefObject(nestedScope); + ResultAssert.IsSuccess(RowReaderUnitTests.ReadNestedDocumentDelegate(tempRef_nestedScope, 0)); + nestedScope = tempRef_nestedScope.argValue; + assert rowReader.Read(); + tangible.RefObject tempRef_nestedScope2 = + new tangible.RefObject(nestedScope); + Result result = rowReader.SkipScope(tempRef_nestedScope2); + nestedScope = tempRef_nestedScope2.argValue; + assert Result.Success != result; + } + + private static Result ReadNestedDocumentDelegate(tangible.RefObject reader, int context) { + while (reader.argValue.Read()) { + switch (reader.argValue.getType().LayoutCode) { + case TupleScope: { + ResultAssert.IsSuccess(reader.argValue.ReadScope(0, RowReaderUnitTests.ReadTuplePartial)); + break; + } + + case ObjectScope: { + ResultAssert.IsSuccess(reader.argValue.ReadScope(0, RowReaderUnitTests.ReadNestedDocumentDelegate)); + break; + } + } + } + + return Result.Success; + } + + private static Result ReadNestedDocumentNonDelegate(tangible.RefObject reader, int context) { + while (reader.argValue.Read()) { + switch (reader.argValue.getType().LayoutCode) { + case TupleScope: { + RowReader nested = reader.argValue.ReadScope().clone(); + tangible.RefObject tempRef_nested = + new tangible.RefObject(nested); + ResultAssert.IsSuccess(RowReaderUnitTests.ReadTuplePartial(tempRef_nested, 0)); + nested = tempRef_nested.argValue; + break; + } + + case ObjectScope: { + RowReader nested = reader.argValue.ReadScope().clone(); + tangible.RefObject tempRef_nested2 = + new tangible.RefObject(nested); + ResultAssert.IsSuccess(RowReaderUnitTests.ReadNestedDocumentNonDelegate(tempRef_nested2, 0)); + nested = tempRef_nested2.argValue; + ResultAssert.IsSuccess(reader.argValue.ReadScope(0, RowReaderUnitTests.ReadNestedDocumentDelegate)); + break; + } + } + } + + return Result.Success; + } + + private static Result ReadNestedDocumentNonDelegateWithSkipScope(tangible.RefObject reader, + int context) { + while (reader.argValue.Read()) { + switch (reader.argValue.getType().LayoutCode) { + case TupleScope: { + RowReader nested = reader.argValue.ReadScope().clone(); + tangible.RefObject tempRef_nested = + new tangible.RefObject(nested); + ResultAssert.IsSuccess(RowReaderUnitTests.ReadTuplePartial(tempRef_nested, 0)); + nested = tempRef_nested.argValue; + tangible.RefObject tempRef_nested2 = + new tangible.RefObject(nested); + ResultAssert.IsSuccess(reader.argValue.SkipScope(tempRef_nested2)); + nested = tempRef_nested2.argValue; + break; + } + + case ObjectScope: { + RowReader nested = reader.argValue.ReadScope().clone(); + tangible.RefObject tempRef_nested3 = + new tangible.RefObject(nested); + ResultAssert.IsSuccess(RowReaderUnitTests.ReadNestedDocumentNonDelegate(tempRef_nested3, 0)); + nested = tempRef_nested3.argValue; + ResultAssert.IsSuccess(reader.argValue.ReadScope(0, RowReaderUnitTests.ReadNestedDocumentDelegate)); + tangible.RefObject tempRef_nested4 = new tangible.RefObject(nested); + ResultAssert.IsSuccess(reader.argValue.SkipScope(tempRef_nested4)); + nested = tempRef_nested4.argValue; + break; + } + } + } + + return Result.Success; + } + + private static Result ReadTuplePartial(tangible.RefObject reader, int unused) { + // Read only part of our tuple + assert reader.argValue.Read(); + assert reader.argValue.Read(); + return Result.Success; + } + + private static Result WriteNestedDocument(tangible.RefObject writer, TypeArgument typeArgument, + int level) { + TypeArgument tupleArgument = new TypeArgument(LayoutType.Tuple, new TypeArgumentList(new TypeArgument[] + { + new TypeArgument(LayoutType.Int32), + new TypeArgument(LayoutType.Int32), + new TypeArgument(LayoutType.Int32) + })); + + // TODO: C# TO JAVA CONVERTER: Local functions are not converted by C# to Java Converter: + // Result WriteTuple(ref RowWriter tupleWriter, TypeArgument tupleTypeArgument, int unused) + // { + // ResultAssert.IsSuccess(tupleWriter.WriteInt32(null, 1)); + // ResultAssert.IsSuccess(tupleWriter.WriteInt32(null, 2)); + // ResultAssert.IsSuccess(tupleWriter.WriteInt32(null, 3)); + // return Result.Success; + // } + + if (level == 0) { + ResultAssert.IsSuccess(writer.argValue.WriteScope("x", tupleArgument.clone(), 0, WriteTuple)); + return Result.Success; + } + + ResultAssert.IsSuccess(writer.argValue.WriteScope("a", new TypeArgument(LayoutType.Object), level - 1, + RowReaderUnitTests.WriteNestedDocument)); + ResultAssert.IsSuccess(writer.argValue.WriteScope("x", tupleArgument.clone(), 0, WriteTuple)); + ResultAssert.IsSuccess(writer.argValue.WriteScope("b", new TypeArgument(LayoutType.Object), level - 1, + RowReaderUnitTests.WriteNestedDocument)); + ResultAssert.IsSuccess(writer.argValue.WriteScope("y", tupleArgument.clone(), 0, WriteTuple)); + ResultAssert.IsSuccess(writer.argValue.WriteScope("c", new TypeArgument(LayoutType.Object), level - 1, + RowReaderUnitTests.WriteNestedDocument)); + + return Result.Success; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test types.")] internal sealed class Point : IDispatchable, IRowSerializable + public final static class Point implements IDispatchable, IRowSerializable { + public int X; + public int Y; + + public Point(int x, int y) { + this.X = x; + this.Y = y; + } + + public void Dispatch(tangible.RefObject dispatcher, tangible.RefObject scope) { + dispatcher.argValue.LayoutCodeSwitch(scope, "x", value:this.X) + dispatcher.argValue.LayoutCodeSwitch(scope, "y", value:this.Y) + } + + public Result Write(tangible.RefObject writer, TypeArgument typeArg) { + Result result = writer.argValue.WriteInt32("x", this.X); + if (result != Result.Success) { + return result; + } + + return writer.argValue.WriteInt32("y", this.Y); + } + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + return obj instanceof Point && this.equals((Point)obj); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + return ((new Integer(this.X)).hashCode() * 397) ^ (new Integer(this.Y)).hashCode(); + } + } + + private boolean equals(Point other) { + return this.X == other.X && this.Y == other.Y; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowWriterUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowWriterUnitTests.java new file mode 100644 index 0000000..c6d53d6 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/RowWriterUnitTests.java @@ -0,0 +1,505 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.Float128; +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.NullValue; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.UnixDateTime; + +import java.nio.file.Files; +import java.time.LocalDateTime; +import java.util.UUID; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][SuppressMessage("StyleCop.CSharp.ReadabilityRules", +// "SA1118:ParameterMustNotSpanMultipleLines", Justification = "Test code.")][DeploymentItem(RowWriterUnitTests +// .SchemaFile, "TestData")] public sealed class RowWriterUnitTests +public final class RowWriterUnitTests { + private static final int InitialRowSize = 2 * 1024 * 1024; + private static final LocalDateTime SampleDateTime = LocalDateTime.parse("2018-08-14 02:05:00.0000000"); + private static final Float128 SampleFloat128 = new Float128(0, 42); + private static final UUID SampleGuid = UUID.fromString("{2A9C25B9-922E-4611-BB0A-244A9496503C}"); + private static final MongoDbObjectId SampleMongoDbObjectId = new MongoDbObjectId(0, 42); + private static final UnixDateTime SampleUnixDateTime = new UnixDateTime(42); + private static final String SchemaFile = "TestData\\ReaderSchema.json"; + private LayoutResolver resolver; + private Namespace schema; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void TestInitialize() + public void TestInitialize() { + String json = Files.readString(RowWriterUnitTests.SchemaFile); + this.schema = Namespace.Parse(json); + this.resolver = new LayoutResolverNamespace(this.schema); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void WriteMixed() + public void WriteMixed() { + Layout layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "Mixed")).SchemaId); + assert layout != null; + + RowBuffer row = new RowBuffer(RowWriterUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, layout, this.resolver); + + int writerLength = 0; + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + ResultAssert.IsSuccess(RowWriter.WriteBuffer(tempRef_row, null, (ref RowWriter writer, + TypeArgument rootTypeArg, Object ignored) -> + { + ResultAssert.IsSuccess(writer.WriteNull("null")); + ResultAssert.IsSuccess(writer.WriteBool("bool", true)); + ResultAssert.IsSuccess(writer.WriteInt8("int8", (byte)-86)); + ResultAssert.IsSuccess(writer.WriteInt16("int16", (short)-21846)); + ResultAssert.IsSuccess(writer.WriteInt32("int32", -1431655766)); + ResultAssert.IsSuccess(writer.WriteInt64("int64", -6148914691236517206L)); + ResultAssert.IsSuccess(writer.WriteUInt8("uint8", (byte)0xAA)); + ResultAssert.IsSuccess(writer.WriteUInt16("uint16", (short)0xAAAA)); + ResultAssert.IsSuccess(writer.WriteUInt32("uint32", 0xAAAAAAAA)); + ResultAssert.IsSuccess(writer.WriteUInt64("uint64", 0xAAAAAAAAAAAAAAAAL)); + ResultAssert.IsSuccess(writer.WriteFloat32("float32", 1.0F / 3.0F)); + ResultAssert.IsSuccess(writer.WriteFloat64("float64", 1.0 / 3.0)); + ResultAssert.IsSuccess(writer.WriteFloat128("float128", RowWriterUnitTests.SampleFloat128)); + ResultAssert.IsSuccess(writer.WriteDecimal("decimal", java.math.BigDecimal.ONE / 3.0)); + ResultAssert.IsSuccess(writer.WriteDateTime("datetime", RowWriterUnitTests.SampleDateTime)); + ResultAssert.IsSuccess(writer.WriteUnixDateTime("unixdatetime", RowWriterUnitTests.SampleUnixDateTime)); + ResultAssert.IsSuccess(writer.WriteGuid("guid", RowWriterUnitTests.SampleGuid)); + ResultAssert.IsSuccess(writer.WriteMongoDbObjectId("mongodbobjectid", + RowWriterUnitTests.SampleMongoDbObjectId)); + ResultAssert.IsSuccess(writer.WriteString("utf8", "abc")); + ResultAssert.IsSuccess(writer.WriteString("utf8_span", Utf8Span.TranscodeUtf16("abc"))); + ResultAssert.IsSuccess(writer.WriteBinary("binary", new byte[] { (byte)0, (byte)1, (byte)2 })); + ResultAssert.IsSuccess(writer.WriteBinary("binary_span", + new byte[] { (byte)0, (byte)1, (byte)2 }.AsSpan())); + ResultAssert.IsSuccess(writer.WriteBinary("binary_sequence", + new ReadOnlySequence(new byte[] { (byte)0, (byte)1, (byte)2 }))); + + ResultAssert.IsSuccess(writer.WriteVarInt("var_varint", -6148914691236517206L)); + ResultAssert.IsSuccess(writer.WriteVarUInt("var_varuint", 0xAAAAAAAAAAAAAAAAL)); + ResultAssert.IsSuccess(writer.WriteString("var_utf8", "abc")); + ResultAssert.IsSuccess(writer.WriteString("var_utf8_span", Utf8Span.TranscodeUtf16("abc"))); + ResultAssert.IsSuccess(writer.WriteBinary("var_binary", new byte[] { (byte)0, (byte)1, (byte)2 })); + ResultAssert.IsSuccess(writer.WriteBinary("var_binary_span", + new byte[] { (byte)0, (byte)1, (byte)2 }.AsSpan())); + ResultAssert.IsSuccess(writer.WriteBinary("var_binary_sequence", + new ReadOnlySequence(new byte[] { (byte)0, (byte)1, (byte)2 }))); + + ResultAssert.IsSuccess(writer.WriteNull("sparse_null")); + ResultAssert.IsSuccess(writer.WriteBool("sparse_bool", true)); + ResultAssert.IsSuccess(writer.WriteInt8("sparse_int8", (byte)-86)); + ResultAssert.IsSuccess(writer.WriteInt16("sparse_int16", (short)-21846)); + ResultAssert.IsSuccess(writer.WriteInt32("sparse_int32", -1431655766)); + ResultAssert.IsSuccess(writer.WriteInt64("sparse_int64", -6148914691236517206L)); + ResultAssert.IsSuccess(writer.WriteUInt8("sparse_uint8", (byte)0xAA)); + ResultAssert.IsSuccess(writer.WriteUInt16("sparse_uint16", (short)0xAAAA)); + ResultAssert.IsSuccess(writer.WriteUInt32("sparse_uint32", 0xAAAAAAAA)); + ResultAssert.IsSuccess(writer.WriteUInt64("sparse_uint64", 0xAAAAAAAAAAAAAAAAL)); + ResultAssert.IsSuccess(writer.WriteFloat32("sparse_float32", 1.0F / 3.0F)); + ResultAssert.IsSuccess(writer.WriteFloat64("sparse_float64", 1.0 / 3.0)); + ResultAssert.IsSuccess(writer.WriteFloat128("sparse_float128", RowWriterUnitTests.SampleFloat128)); + ResultAssert.IsSuccess(writer.WriteDecimal("sparse_decimal", java.math.BigDecimal.ONE / 3.0)); + ResultAssert.IsSuccess(writer.WriteDateTime("sparse_datetime", RowWriterUnitTests.SampleDateTime)); + ResultAssert.IsSuccess(writer.WriteUnixDateTime("sparse_unixdatetime", + RowWriterUnitTests.SampleUnixDateTime)); + ResultAssert.IsSuccess(writer.WriteGuid("sparse_guid", RowWriterUnitTests.SampleGuid)); + ResultAssert.IsSuccess(writer.WriteMongoDbObjectId("sparse_mongodbobjectid", + RowWriterUnitTests.SampleMongoDbObjectId)); + ResultAssert.IsSuccess(writer.WriteString("sparse_utf8", "abc")); + ResultAssert.IsSuccess(writer.WriteString("sparse_utf8_span", Utf8Span.TranscodeUtf16("abc"))); + ResultAssert.IsSuccess(writer.WriteBinary("sparse_binary", new byte[] { (byte)0, (byte)1, (byte)2 })); + ResultAssert.IsSuccess(writer.WriteBinary("sparse_binary_span", + new byte[] { (byte)0, (byte)1, (byte)2 }.AsSpan())); + ResultAssert.IsSuccess(writer.WriteBinary("sparse_binary_sequence", + new ReadOnlySequence(new byte[] { (byte)0, (byte)1, (byte)2 }))); + + LayoutColumn col; + tangible.OutObject tempOut_col = + new tangible.OutObject(); + assert layout.TryFind("array_t", tempOut_col); + col = tempOut_col.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), new byte[] { -86, -87, + -88 }, (ref RowWriter writer2, TypeArgument typeArg, byte[] values) -> + { + for (byte value : values) { + ResultAssert.IsSuccess(writer2.WriteInt8(null, value)); + } + + return Result.Success; + })); + + tangible.OutObject tempOut_col2 = + new tangible.OutObject(); + assert layout.TryFind("array_t>", tempOut_col2); + col = tempOut_col2.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), new float[][] + { + new float[] { 1, 2, 3 }, + new float[] { 1, 2, 3 } + }, (ref RowWriter writer2, TypeArgument typeArg, float[][] values) -> + { + for (float[] value : values) { + ResultAssert.IsSuccess(writer2.WriteScope(null, typeArg.getTypeArgs().get(0).clone(), value, + (ref RowWriter writer3, TypeArgument typeArg2, float[] values2) -> + { + for (float value2 : values2) { + ResultAssert.IsSuccess(writer3.WriteFloat32(null, value2)); + } + + return Result.Success; + })); + } + + return Result.Success; + })); + + tangible.OutObject tempOut_col3 = + new tangible.OutObject(); + assert layout.TryFind("array_t", tempOut_col3); + col = tempOut_col3.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), new String[] { "abc", + "def", "hij" }, (ref RowWriter writer2, TypeArgument typeArg, String[] values) -> + { + for (String value : values) { + ResultAssert.IsSuccess(writer2.WriteString(null, value)); + } + + return Result.Success; + })); + + tangible.OutObject tempOut_col4 = + new tangible.OutObject(); + assert layout.TryFind("tuple", tempOut_col4); + col = tempOut_col4.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), + Tuple.Create(-6148914691236517206L, -6148914691236517206L), (ref RowWriter writer2, + TypeArgument typeArg, + Tuple values) -> + { + ResultAssert.IsSuccess(writer2.WriteVarInt(null, values.Item1)); + ResultAssert.IsSuccess(writer2.WriteInt64(null, values.Item2)); + return Result.Success; + })); + + tangible.OutObject tempOut_col5 = + new tangible.OutObject(); + assert layout.TryFind("tuple>", tempOut_col5); + col = tempOut_col5.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), + Tuple.Create(NullValue.Default, Tuple.Create((byte)-86, (byte)-86)), (ref RowWriter writer2, + TypeArgument typeArg, + Tuple> values) -> + { + ResultAssert.IsSuccess(writer2.WriteNull(null)); + ResultAssert.IsSuccess(writer2.WriteScope(null, typeArg.getTypeArgs().get(1).clone(), values.Item2, + (ref RowWriter writer3, TypeArgument typeArg2, Tuple values2) -> + { + ResultAssert.IsSuccess(writer3.WriteInt8(null, values2.Item1)); + ResultAssert.IsSuccess(writer3.WriteInt8(null, values2.Item2)); + return Result.Success; + })); + + return Result.Success; + })); + + tangible.OutObject tempOut_col6 = + new tangible.OutObject(); + assert layout.TryFind("tuple", tempOut_col6); + col = tempOut_col6.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), Tuple.Create(false, + new RowReaderUnitTests.Point(1, 2)), (ref RowWriter writer2, TypeArgument typeArg, Tuple values) -> + { + ResultAssert.IsSuccess(writer2.WriteBool(null, values.Item1)); + tangible.RefObject tempRef_writer3 = + new tangible.RefObject(writer3); + ResultAssert.IsSuccess(writer2.WriteScope(null, typeArg.getTypeArgs().get(1).clone(), values.Item2, + (ref RowWriter writer3, TypeArgument typeArg2, IRowSerializable values2) -> values2.Write(tempRef_writer3, typeArg2.clone()))); + writer3 = tempRef_writer3.argValue; + + return Result.Success; + })); + + tangible.OutObject tempOut_col7 = + new tangible.OutObject(); + assert layout.TryFind("nullable", tempOut_col7); + col = tempOut_col7.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), Tuple.Create(null, + (Long)123L), (ref RowWriter writer2, TypeArgument typeArg, Tuple values) -> + { + RowWriter.WriterFunc f0 = (tangible.RefObject writer, TypeArgument typeArg, + Integer context) -> null.invoke(writer, typeArg.clone(), context); + if (values.Item1 != null) { + f0 = (ref RowWriter writer3, TypeArgument typeArg2, Integer value) -> writer3.WriteInt32(null, + value.intValue()); + } + + ResultAssert.IsSuccess(writer2.WriteScope(null, typeArg.getTypeArgs().get(0).clone(), values.Item1, + f0)); + + RowWriter.WriterFunc f1 = (tangible.RefObject writer, TypeArgument typeArg, + Long context) -> null.invoke(writer, typeArg.clone(), context); + if (values.Item2 != null) { + f1 = (ref RowWriter writer3, TypeArgument typeArg2, Long value) -> writer3.WriteInt64(null, + value.longValue()); + } + + ResultAssert.IsSuccess(writer2.WriteScope(null, typeArg.getTypeArgs().get(1).clone(), values.Item2, + f1)); + return Result.Success; + })); + + tangible.OutObject tempOut_col8 = + new tangible.OutObject(); + assert layout.TryFind("tagged", tempOut_col8); + col = tempOut_col8.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), Tuple.Create((byte)3, + "hello"), (ref RowWriter writer2, TypeArgument typeArg, Tuple values) -> + { + ResultAssert.IsSuccess(writer2.WriteUInt8(null, values.Item1)); + ResultAssert.IsSuccess(writer2.WriteString(null, values.Item2)); + return Result.Success; + })); + + tangible.OutObject tempOut_col9 = + new tangible.OutObject(); + assert layout.TryFind("tagged", tempOut_col9); + col = tempOut_col9.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), Tuple.Create((byte)5, + true, "bye"), (ref RowWriter writer2, TypeArgument typeArg, Tuple values) -> + { + ResultAssert.IsSuccess(writer2.WriteUInt8(null, values.Item1)); + ResultAssert.IsSuccess(writer2.WriteBool(null, values.Item2)); + ResultAssert.IsSuccess(writer2.WriteString(null, values.Item3)); + return Result.Success; + })); + + tangible.OutObject tempOut_col10 = + new tangible.OutObject(); + assert layout.TryFind("set_t", tempOut_col10); + col = tempOut_col10.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), new String[] { "abc", + "xzy", "efg" }, (ref RowWriter writer2, TypeArgument typeArg, String[] values) -> + { + for (String value : values) { + ResultAssert.IsSuccess(writer2.WriteString(null, value)); + } + + return Result.Success; + })); + + tangible.OutObject tempOut_col11 = + new tangible.OutObject(); + assert layout.TryFind("set_t>", tempOut_col11); + col = tempOut_col11.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), new byte[][] + { + new byte[] { 7, 8, 9 }, + new byte[] { 4, 5, 6 }, + new byte[] { 1, 2, 3 } + }, (ref RowWriter writer2, TypeArgument typeArg, byte[][] values) -> + { + for (byte[] value : values) { + ResultAssert.IsSuccess(writer2.WriteScope(null, typeArg.getTypeArgs().get(0).clone(), value, + (ref RowWriter writer3, TypeArgument typeArg2, byte[] values2) -> + { + for (byte value2 : values2) { + ResultAssert.IsSuccess(writer3.WriteInt8(null, value2)); + } + + return Result.Success; + })); + } + + return Result.Success; + })); + + tangible.OutObject tempOut_col12 = + new tangible.OutObject(); + assert layout.TryFind("set_t>", tempOut_col12); + col = tempOut_col12.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), new int[][] + { + new int[] { 4, 5, 6 }, + new int[] { 7, 8, 9 }, + new int[] { 1, 2, 3 } + }, (ref RowWriter writer2, TypeArgument typeArg, int[][] values) -> + { + for (int[] value : values) { + ResultAssert.IsSuccess(writer2.WriteScope(null, typeArg.getTypeArgs().get(0).clone(), value, + (ref RowWriter writer3, TypeArgument typeArg2, int[] values2) -> + { + for (int value2 : values2) { + ResultAssert.IsSuccess(writer3.WriteInt32(null, value2)); + } + + return Result.Success; + })); + } + + return Result.Success; + })); + + tangible.OutObject tempOut_col13 = + new tangible.OutObject(); + assert layout.TryFind("set_t", tempOut_col13); + col = tempOut_col13.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), + new RowReaderUnitTests.Point[] + { + new RowReaderUnitTests.Point(1, 2), + new RowReaderUnitTests.Point(3, 4), + new RowReaderUnitTests.Point(5, 6) + }, (ref RowWriter writer2, TypeArgument typeArg, RowReaderUnitTests.Point[] values) -> + { + for (RowReaderUnitTests.Point value : values) { + tangible.RefObject tempRef_writer3 = + new tangible.RefObject(writer3); + ResultAssert.IsSuccess(writer2.WriteScope(null, typeArg.getTypeArgs().get(0).clone(), value, + (ref RowWriter writer3, TypeArgument typeArg2, IRowSerializable values2) -> values2.Write(tempRef_writer3, typeArg2.clone()))); + writer3 = tempRef_writer3.argValue; + } + + return Result.Success; + })); + + tangible.OutObject tempOut_col14 = + new tangible.OutObject(); + assert layout.TryFind("map_t", tempOut_col14); + col = tempOut_col14.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), new System.Tuple[] { Tuple.Create("Harrison", "Han"), Tuple.Create("Mark", "Luke") }, (ref RowWriter writer2, + TypeArgument typeArg, + Tuple[] values) -> + { + for (Tuple value : values) { + ResultAssert.IsSuccess(writer2.WriteScope(null, new TypeArgument(LayoutType.TypedTuple, + typeArg.getTypeArgs().clone()), value, (ref RowWriter writer3, TypeArgument typeArg2, + Tuple values2) -> + { + ResultAssert.IsSuccess(writer3.WriteString(null, values2.Item1)); + ResultAssert.IsSuccess(writer3.WriteString(null, values2.Item2)); + return Result.Success; + })); + } + + return Result.Success; + })); + + tangible.OutObject tempOut_col15 = + new tangible.OutObject(); + assert layout.TryFind("map_t>", tempOut_col15); + col = tempOut_col15.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), new System.Tuple[] { Tuple.Create((byte)2, new byte[] { 4, 5, 6 }), + Tuple.Create((byte)1, new byte[] { 1, 2, 3 }) }, (ref RowWriter writer2, TypeArgument typeArg, + Tuple[] values) -> + { + for (Tuple value : values) { + ResultAssert.IsSuccess(writer2.WriteScope(null, new TypeArgument(LayoutType.TypedTuple, + typeArg.getTypeArgs().clone()), value, (ref RowWriter writer3, TypeArgument typeArg2, + Tuple values2) -> + { + ResultAssert.IsSuccess(writer3.WriteInt8(null, values2.Item1)); + ResultAssert.IsSuccess(writer3.WriteScope(null, typeArg2.getTypeArgs().get(1).clone(), + values2.Item2, (ref RowWriter writer4, TypeArgument typeArg3, byte[] values3) -> + { + for (byte value3 : values3) { + ResultAssert.IsSuccess(writer4.WriteInt8(null, value3)); + } + + return Result.Success; + })); + + return Result.Success; + })); + } + + return Result.Success; + })); + + tangible.OutObject tempOut_col16 = + new tangible.OutObject(); + assert layout.TryFind("map_t>", tempOut_col16); + col = tempOut_col16.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), new System.Tuple[] { Tuple.Create((short)2, new System.Tuple[] { Tuple.Create(7, 8), Tuple.Create(5, 6) }) + , Tuple.Create((short)1, new System.Tuple[] { Tuple.Create(3, 4), Tuple.Create(1, 2) }) }, + (ref RowWriter writer2, TypeArgument typeArg, Tuple[]>[] values) -> + { + for (Tuple[]> value : values) { + ResultAssert.IsSuccess(writer2.WriteScope(null, new TypeArgument(LayoutType.TypedTuple, + typeArg.getTypeArgs().clone()), value, (ref RowWriter writer3, TypeArgument typeArg2, + Tuple[]> values2) -> + { + ResultAssert.IsSuccess(writer3.WriteInt16(null, values2.Item1)); + ResultAssert.IsSuccess(writer3.WriteScope(null, typeArg2.getTypeArgs().get(1).clone(), + values2.Item2, (ref RowWriter writer4, TypeArgument typeArg3, + Tuple[] values3) -> + { + for (Tuple value3 : values3) { + ResultAssert.IsSuccess(writer4.WriteScope(null, + new TypeArgument(LayoutType.TypedTuple, typeArg3.getTypeArgs().clone()), value3, + (ref RowWriter writer5, TypeArgument typeArg4, Tuple values4) -> + { + ResultAssert.IsSuccess(writer5.WriteInt32(null, values4.Item1)); + ResultAssert.IsSuccess(writer5.WriteInt32(null, values4.Item2)); + return Result.Success; + })); + } + + return Result.Success; + })); + + return Result.Success; + })); + } + + return Result.Success; + })); + + tangible.OutObject tempOut_col17 = + new tangible.OutObject(); + assert layout.TryFind("map_t", tempOut_col17); + col = tempOut_col17.argValue; + ResultAssert.IsSuccess(writer.WriteScope(col.getPath(), col.getTypeArg().clone(), new System.Tuple[] { Tuple.Create(1.0, new RowReaderUnitTests.Point(1, 2)), Tuple.Create(2.0, new RowReaderUnitTests.Point(3, 4)), Tuple.Create(3.0, new RowReaderUnitTests.Point(5, 6)) }, (ref RowWriter writer2, TypeArgument typeArg, Tuple[] values) -> + { + for (Tuple value : values) { + ResultAssert.IsSuccess(writer2.WriteScope(null, new TypeArgument(LayoutType.TypedTuple, typeArg.getTypeArgs().clone()), value, (ref RowWriter writer3, TypeArgument typeArg2, Tuple values2) -> + { + ResultAssert.IsSuccess(writer3.WriteFloat64(null, values2.Item1)); + tangible.RefObject tempRef_writer4 = new tangible.RefObject(writer4); + ResultAssert.IsSuccess(writer3.WriteScope(null, typeArg2.getTypeArgs().get(1).clone(), values2.Item2, (ref RowWriter writer4, TypeArgument typeArg3, IRowSerializable values3) -> values3.Write(tempRef_writer4, typeArg3.clone()))); + writer4 = tempRef_writer4.argValue; + + return Result.Success; + })); + } + + return Result.Success; + })); + + // Save the RowWriter length after everything is written for later comparison. + writerLength = writer.Length; + return Result.Success; + })); + row = tempRef_row.argValue; + + tangible.RefObject tempRef_row2 = new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row2); + row = tempRef_row2.argValue; + assert reader.getLength() == writerLength; + tangible.RefObject tempRef_reader = new tangible.RefObject(reader); + RowReaderUnitTests.PrintReader(tempRef_reader, 0); + reader = tempRef_reader.argValue; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaHashUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaHashUnitTests.java new file mode 100644 index 0000000..ac7beda --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaHashUnitTests.java @@ -0,0 +1,272 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import Newtonsoft.Json.*; +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +import java.nio.file.Files; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][DeploymentItem(SchemaHashUnitTests.SchemaFile, "TestData")] public class +// SchemaHashUnitTests +public class SchemaHashUnitTests { + private static final String SchemaFile = "TestData\\SchemaHashCoverageSchema.json"; + private Namespace ns; + private Schema tableSchema; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void InitializeSuite() + public final void InitializeSuite() { + String json = Files.readString(SchemaHashUnitTests.SchemaFile); + this.ns = Namespace.Parse(json); + this.tableSchema = tangible.ListHelper.find(this.ns.getSchemas(), s -> s.Name.equals("Table")); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void SchemaHashCompileTest() + public final void SchemaHashCompileTest() { + Layout layout = this.tableSchema.Compile(this.ns); + assert layout != null; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void SchemaHashTest() + public final void SchemaHashTest() { + // TODO: C# TO JAVA CONVERTER: Tuple variables are not converted by C# to Java Converter: + ( long low, long high)hash = SchemaHash.ComputeHash(this.ns, this.tableSchema); + assert (0,0) !=hash; + // TODO: C# TO JAVA CONVERTER: Tuple variables are not converted by C# to Java Converter: + ( long low, long high)hash2 = SchemaHash.ComputeHash(this.ns, this.tableSchema, (1, 1)) + assert hash != hash2; + + // Test clone are the same. + Schema clone = SchemaHashUnitTests.Clone(this.tableSchema); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash == hash2; + + // Test Schema changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.setName("something else"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash == hash2; // Name not part of the hash + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.setComment("something else"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash == hash2; // Comment not part of the hash + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.setVersion(SchemaLanguageVersion.forValue((byte)1)); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash == hash2; // Encoding version not part of the hash + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.setSchemaId(new SchemaId(42)); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.setType(TypeKind.Int8); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Options changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getOptions().setEnablePropertyLevelTimestamp(!clone.getOptions().getEnablePropertyLevelTimestamp()); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getOptions().setDisallowUnschematized(!clone.getOptions().getDisallowUnschematized()); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Partition Keys changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getPartitionKeys().get(0).setPath("something else"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Primary Sort Keys changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getPrimarySortKeys().get(0).setPath("something else"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getPrimarySortKeys().get(0).setDirection(SortDirection.Descending); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Static Keys changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getStaticKeys().get(0).setPath("something else"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Properties changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getProperties().get(0).setComment("something else"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash == hash2; // Comment not part of the hash + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getProperties().get(0).setPath("something else"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Property Type changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getProperties().get(0).getPropertyType().setApiType("something else"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getProperties().get(0).getPropertyType().setType(TypeKind.Binary); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + clone.getProperties().get(0).getPropertyType().setNullable(!clone.getProperties().get(0).getPropertyType().getNullable()); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Primitive Property Type changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar = + clone.getProperties().get(0).getPropertyType(); + (tempVar instanceof PrimitivePropertyType ? (PrimitivePropertyType)tempVar : null).setLength(42); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar2 = + clone.getProperties().get(0).getPropertyType(); + (tempVar2 instanceof PrimitivePropertyType ? (PrimitivePropertyType)tempVar2 : null).setStorage(StorageKind.Variable); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Scope Property Type changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar3 = + clone.getProperties().get(1).getPropertyType(); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar4 = + clone.getProperties().get(1).getPropertyType(); + (tempVar3 instanceof ScopePropertyType ? (ScopePropertyType)tempVar3 : null).setImmutable(!(tempVar4 instanceof ScopePropertyType ? (ScopePropertyType)tempVar4 : null).getImmutable()); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Array Property Type changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar5 = + clone.getProperties().get(1).getPropertyType(); + (tempVar5 instanceof ArrayPropertyType ? (ArrayPropertyType)tempVar5 : null).setItems(clone.getProperties().get(0).getPropertyType()); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Object Property Type changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar6 = + clone.getProperties().get(2).getPropertyType(); + (tempVar6 instanceof ObjectPropertyType ? (ObjectPropertyType)tempVar6 : null).getProperties().set(0, + clone.getProperties().get(0)); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Map Property Type changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar7 = + clone.getProperties().get(3).getPropertyType(); + (tempVar7 instanceof MapPropertyType ? (MapPropertyType)tempVar7 : null).setKeys(clone.getProperties().get(0).getPropertyType()); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar8 = + clone.getProperties().get(3).getPropertyType(); + (tempVar8 instanceof MapPropertyType ? (MapPropertyType)tempVar8 : null).setValues(clone.getProperties().get(0).getPropertyType()); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Set Property Type changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar9 = + clone.getProperties().get(4).getPropertyType(); + (tempVar9 instanceof SetPropertyType ? (SetPropertyType)tempVar9 : null).setItems(clone.getProperties().get(0).getPropertyType()); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Tagged Property Type changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar10 = + clone.getProperties().get(5).getPropertyType(); + (tempVar10 instanceof TaggedPropertyType ? (TaggedPropertyType)tempVar10 : null).getItems().set(0, + clone.getProperties().get(0).getPropertyType()); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test Tuple Property Type changes + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar11 = + clone.getProperties().get(6).getPropertyType(); + (tempVar11 instanceof TuplePropertyType ? (TuplePropertyType)tempVar11 : null).getItems().set(0, + clone.getProperties().get(0).getPropertyType()); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Test UDT Property Type changes + try { + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar12 = + clone.getProperties().get(7).getPropertyType(); + (tempVar12 instanceof UdtPropertyType ? (UdtPropertyType)tempVar12 : null).setName("some non-existing UDT" + + " name"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + Assert.Fail("Should have thrown an exception."); + } catch (RuntimeException ex) { + assert ex != null; + } + + try { + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar13 = + clone.getProperties().get(7).getPropertyType(); + (tempVar13 instanceof UdtPropertyType ? (UdtPropertyType)tempVar13 : null).setName("Table"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + Assert.Fail("Should have thrown an exception."); + } catch (RuntimeException ex) { + assert ex != null; + } + + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar14 = + clone.getProperties().get(7).getPropertyType(); + (tempVar14 instanceof UdtPropertyType ? (UdtPropertyType)tempVar14 : null).setName("Table"); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar15 = + clone.getProperties().get(7).getPropertyType(); + (tempVar15 instanceof UdtPropertyType ? (UdtPropertyType)tempVar15 : null).setSchemaId(new SchemaId(2)); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash != hash2; + + // Renaming an UDT is not a breaking change as long as the SchemaId has not changed. + this.ns.getSchemas().get(0).setName("RenameActualUDT"); + clone = SchemaHashUnitTests.Clone(this.tableSchema); + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.PropertyType tempVar16 = clone.getProperties().get(7).getPropertyType(); + (tempVar16 instanceof UdtPropertyType ? (UdtPropertyType)tempVar16 : null).setName("RenameActualUDT"); + hash2 = SchemaHash.ComputeHash(this.ns, clone); + assert hash == hash2; + } + + private static Schema Clone(Schema s) { + JsonSerializerSettings settings = new JsonSerializerSettings(); + settings.NullValueHandling = NullValueHandling.Ignore; + settings.Formatting = Formatting.Indented; + settings.CheckAdditionalContent = true; + + String json = JsonConvert.SerializeObject(s, settings); + return JsonConvert.DeserializeObject(json, settings); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaIdUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaIdUnitTests.java new file mode 100644 index 0000000..e99a825 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaIdUnitTests.java @@ -0,0 +1,45 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import Newtonsoft.Json.*; +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass] public class SchemaIdUnitTests +public class SchemaIdUnitTests { + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void SchemaIdTest() + public final void SchemaIdTest() { + SchemaId a = new SchemaId(1); + SchemaId b = new SchemaId(2); + SchemaId c = new SchemaId(); + + assert 1 == a.getId(); + assert 2 == b.getId(); + assert SchemaId.Invalid == c.clone(); + assert 2 != a.getId(); + assert a.clone() != b.clone(); + assert azure.data.cosmos.serialization.hybridrow.SchemaId.opEquals(a.clone(), a.clone()); + assert azure.data.cosmos.serialization.hybridrow.SchemaId.opNotEquals(a.clone(), b.clone()); + assert !a.equals(null); + assert a.hashCode() == (new SchemaId(1)).hashCode(); + assert a.hashCode() != (new SchemaId(-1)).hashCode(); + + String json = JsonConvert.SerializeObject(a.clone()); + assert "1" == json; + assert "1" == a.toString(); + + assert a.clone() == JsonConvert.DeserializeObject(json); + json = JsonConvert.SerializeObject(b.clone()); + assert "2" == json; + assert "2" == b.toString(); + assert b.clone() == JsonConvert.DeserializeObject(json); + json = JsonConvert.SerializeObject(c.clone()); + assert "0" == json; + assert "0" == c.toString(); + assert c.clone() == JsonConvert.DeserializeObject(json); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaUnitTests.java new file mode 100644 index 0000000..5ed5381 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SchemaUnitTests.java @@ -0,0 +1,992 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import Newtonsoft.Json.*; +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +import java.nio.file.Files; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][SuppressMessage("Naming", "DontUseVarForVariableTypes", Justification = "The types here +// are anonymous.")] public class SchemaUnitTests +public class SchemaUnitTests { + PrimitivePropertyType sp = (PrimitivePropertyType)p.getPropertyType(); + String tableSchema = String.format("{'name': 'table', 'id': -1, 'type': 'schema', 'properties': [%1$s]}", + columnSchema); + Schema s = Schema.Parse(tableSchema);) + Property p = s.getProperties().get(0); + + { + case Utf8: + case Binary: + switch (sp.getStorage()) { + case Fixed: + case Variable: + case Sparse: + Assert.AreEqual(expected.Len, sp.getLength(), "Json: {0}", expected.Json); + break; + default: + Assert.Fail("Json: {0}", expected.Json); + break; + } + + break; + } + Assert.AreEqual(1,s.getProperties(). + + getType(), "Json: {0}",expected.Json) + + getType() + Assert.AreEqual(expected.Type,p.getPropertyType(). + + size(), "Json: {0}",expected.Json) + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseNamespace() + public final void ParseNamespace() { + { + // Test empty schemas. + String[] emptyNamespaceJsonInput = { "{ }", "{'schemas': [ ] }", "{'name': null }", "{'name': null, " + + "'schemas': null }", "{'version': 'v1', 'name': null, 'schemas': null }" }; + + for (String json : emptyNamespaceJsonInput) { + Namespace n1 = Namespace.Parse(json); + Assert.IsNull(n1.getName(), "Got: {0}, Json: {1}", n1.getName(), json); + Assert.IsNotNull(n1.getSchemas(), "Json: {0}", json); + Assert.AreEqual(0, n1.getSchemas().size(), "Got: {0}, Json: {1}", n1.getSchemas(), json); + assert SchemaLanguageVersion.V1 == n1.getVersion(); + } + } + + { + // Test simple schemas and schema options. + String json = "{'name': 'myschema', 'schemas': null }"; + Namespace n1 = Namespace.Parse(json); + Assert.AreEqual("myschema", n1.getName(), "Json: {0}", json); + Assert.IsNotNull(n1.getSchemas(), "Json: {0}", json); + + // Version defaults propertly when NOT specified. + assert SchemaLanguageVersion.V1 == n1.getVersion(); + } + + { + String json = "{'name': 'myschema', 'schemas': [" + "\r\n" + + " {'version': 'v1', 'name': 'emptyTable', 'id': -1, 'type': 'schema', " + "\r\n" + + " 'options': { 'disallowUnschematized': true }, 'properties': null } ] }"; + + Namespace n1 = Namespace.Parse(json); + Assert.AreEqual("myschema", n1.getName(), "Json: {0}", json); + Assert.AreEqual(1, n1.getSchemas().size(), "Json: {0}", json); + Assert.AreEqual("emptyTable", n1.getSchemas().get(0).getName(), "Json: {0}", json); + Assert.AreEqual(new SchemaId(-1), n1.getSchemas().get(0).getSchemaId().clone(), "Json: {0}", json); + Assert.AreEqual(TypeKind.Schema, n1.getSchemas().get(0).getType(), "Json: {0}", json); + Assert.AreEqual(true, n1.getSchemas().get(0).getOptions().getDisallowUnschematized(), "Json: {0}", json); + Assert.IsNotNull(n1.getSchemas().get(0).getProperties().size(), "Json: {0}", json); + Assert.AreEqual(0, n1.getSchemas().get(0).getProperties().size(), "Json: {0}", json); + assert SchemaLanguageVersion.V1 == n1.getVersion(); + } + + { + // Test basic schema with primitive columns. + String json = "{'name': 'myschema', 'schemas': [" + "\r\n" + + " {'name': 'myUDT', 'id': 1, 'type': 'schema', 'options': { " + + "'disallowUnschematized': false }, " + "\r\n" + + " 'properties': [ " + "\r\n" + + " { 'path': 'a', 'type': { 'type': 'int8', 'storage': 'fixed' }}, " + "\r\n" + + " { 'path': 'b', 'type': { 'type': 'utf8', 'storage': 'variable' }} " + "\r\n" + + " ] }" + "\r\n" + + " ] }"; + + Namespace n1 = Namespace.Parse(json); + Assert.AreEqual(1, n1.getSchemas().size(), "Json: {0}", json); + Assert.AreEqual("myUDT", n1.getSchemas().get(0).getName(), "Json: {0}", json); + Assert.AreEqual(new SchemaId(1), n1.getSchemas().get(0).getSchemaId().clone(), "Json: {0}", json); + Assert.AreEqual(TypeKind.Schema, n1.getSchemas().get(0).getType(), "Json: {0}", json); + Assert.AreEqual(false, n1.getSchemas().get(0).getOptions().getDisallowUnschematized(), "Json: {0}", json); + Assert.AreEqual(2, n1.getSchemas().get(0).getProperties().size(), "Json: {0}", json); + + class AnonymousType { + public String Path; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.StorageKind Storage; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType(String _Path, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.StorageKind _Storage) { + Path = _Path; + Type = _Type; + Storage = _Storage; + } + } + class AnonymousType2 { + public String Path; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.StorageKind Storage; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType2(String _Path, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.StorageKind _Storage) { + Path = _Path; + Type = _Type; + Storage = _Storage; + } + } + Object[] expectedProps = new Object[] { AnonymousType("a", TypeKind.Int8, StorageKind.Fixed), + AnonymousType2("b", TypeKind.Utf8, StorageKind.Variable) }; + + for (int i = 0; i < n1.getSchemas().get(0).getProperties().size(); i++) { + Property p = n1.getSchemas().get(0).getProperties().get(i); + Assert.AreEqual(expectedProps[i].Path, p.getPath(), "Json: {0}", json); + Assert.AreEqual(expectedProps[i].Type, p.getPropertyType().getType(), "Json: {0}", json); + PrimitivePropertyType sp = (PrimitivePropertyType)p.getPropertyType(); + Assert.AreEqual(expectedProps[i].Storage, sp.getStorage(), "Json: {0}", json); + } + } + } + switch(p.getPropertyType(). + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")][DeploymentItem("TestData\\CoverageSchema.json", "TestData")] + // public void ParseNamespaceExample() + public final void ParseNamespaceExample() { + String json = Files.readString("TestData\\CoverageSchema.json"); + Namespace n1 = Namespace.Parse(json); + JsonSerializerSettings settings = new JsonSerializerSettings(); + settings.NullValueHandling = NullValueHandling.Ignore; + settings.Formatting = Formatting.Indented; + + String json2 = JsonConvert.SerializeObject(n1, settings); + Namespace n2 = Namespace.Parse(json2); + String json3 = JsonConvert.SerializeObject(n2, settings); + assert json2 == json3; + }) + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaPrimitives() + public final void ParseSchemaPrimitives() { + // Test all primitive column types. + class AnonymousType { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType10 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType10(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType11 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType11(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType12 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType12(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType13 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType13(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType14 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType14(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType15 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType15(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType16 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType16(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType17 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType17(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType18 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType18(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType19 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType19(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType2 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType2(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType20 { + public String Json; + public int Len; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType20(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type, int _Len) { + Json = _Json; + Type = _Type; + Len = _Len; + } + } + + class AnonymousType21 { + public String Json; + public int Len; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType21(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type, int _Len) { + Json = _Json; + Type = _Type; + Len = _Len; + } + } + + class AnonymousType22 { + public String Json; + public int Len; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType22(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type, int _Len) { + Json = _Json; + Type = _Type; + Len = _Len; + } + } + + class AnonymousType23 { + public String Json; + public int Len; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType23(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type, int _Len) { + Json = _Json; + Type = _Type; + Len = _Len; + } + } + + class AnonymousType24 { + public String Json; + public int Len; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType24(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type, int _Len) { + Json = _Json; + Type = _Type; + Len = _Len; + } + } + + class AnonymousType25 { + public String Json; + public int Len; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType25(String _Json, + Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type, int _Len) { + Json = _Json; + Type = _Type; + Len = _Len; + } + } + + class AnonymousType3 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType3(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType4 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType4(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType5 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType5(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType6 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType6(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType7 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType7(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType8 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType8(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + + class AnonymousType9 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType9(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } + } + // TODO: C# TO JAVA CONVERTER: There is no Java equivalent to the C# 'dynamic' keyword: + dynamic[] expectedSchemas = { AnonymousType("{'type': 'bool', 'storage': 'fixed'}", TypeKind.Boolean), + AnonymousType2("{'type': 'int8', 'storage': 'fixed'}", TypeKind.Int8), AnonymousType3("{'type': 'int16', " + + "'storage': 'fixed'}", TypeKind.Int16), AnonymousType4("{'type': 'int32', 'storage': 'fixed'}", + TypeKind.Int32), AnonymousType5("{'type': 'int64', 'storage': 'fixed'}", TypeKind.Int64), AnonymousType6( + "{'type': 'uint8', 'storage': 'fixed'}", TypeKind.UInt8), AnonymousType7("{'type': 'uint16', " + + "'storage': 'fixed'}", TypeKind.UInt16), AnonymousType8("{'type': 'uint32', 'storage': 'fixed'}", + TypeKind.UInt32), AnonymousType9("{'type': 'uint64', 'storage': 'fixed'}", TypeKind.UInt64), + AnonymousType10("{'type': 'float32', 'storage': 'fixed'}", TypeKind.Float32), AnonymousType11("{'type': " + + "'float64', 'storage': 'fixed'}", TypeKind.Float64), AnonymousType12("{'type': 'float128', 'storage': " + + "'fixed'}", TypeKind.Float128), AnonymousType13("{'type': 'decimal', 'storage': 'fixed'}", + TypeKind.Decimal), AnonymousType14("{'type': 'datetime', 'storage': 'fixed'}", TypeKind.DateTime), + AnonymousType15("{'type': 'unixdatetime', 'storage': 'fixed'}", TypeKind.UnixDateTime), AnonymousType16( + "{'type': 'guid', 'storage': 'fixed'}", TypeKind.Guid), AnonymousType17("{'type': 'mongodbobjectid', " + + "'storage': 'fixed'}", TypeKind.MongoDbObjectId), AnonymousType18("{'type': 'varint', 'storage': " + + "'variable'}", TypeKind.VarInt), AnonymousType19("{'type': 'varuint', 'storage': 'variable'}", + TypeKind.VarUInt), AnonymousType20("{'type': 'utf8', 'storage': 'fixed', 'length': 2}", TypeKind.Utf8, 2) + , AnonymousType21("{'type': 'binary', 'storage': 'fixed', 'length': 2}", TypeKind.Binary, 2), + AnonymousType22("{'type': 'utf8', 'storage': 'variable', 'length': 100}", TypeKind.Utf8, 100), + AnonymousType23("{'type': 'binary', 'storage': 'variable', 'length': 100}", TypeKind.Binary, 100), + AnonymousType24("{'type': 'utf8', 'sparse': 'variable', 'length': 1000}", TypeKind.Utf8, 1000), + AnonymousType25("{'type': 'binary', 'sparse': 'variable', 'length': 1000}", TypeKind.Binary, 1000) }; + + for (dynamic expected : expectedSchemas) { + String columnSchema = String.format("{'path': 'a', 'type': %1$s", expected.Json + } + } +} + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaArray() +public final void ParseSchemaArray() + { + +// Test array types include nested arrays. +class AnonymousType { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } +} + +class AnonymousType2 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType2(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } +} + +class AnonymousType3 { + public String Json; + public int Len; + + public AnonymousType3(String _Json, int _Len) { + Json = _Json; + Len = _Len; + } +} + +class AnonymousType4 { + public String Json; + public String Name; +// TODO: C# TO JAVA CONVERTER: There is no Java equivalent to the C# 'dynamic' keyword: + dynamic[] expectedSchemas = { AnonymousType("{'type': 'int8' }", TypeKind.Int8), AnonymousType2("{'type': " + + "'array', 'items': {'type': 'int32'}}", TypeKind.Int32), AnonymousType3("{'type': 'object', 'properties': " + + "null}", 0), AnonymousType4("{'type': 'schema', 'name': 'myUDT'}", "myUDT") }; + + public AnonymousType4(String _Json, String _Name) { + Json = _Json; + Name = _Name; + } +} + for(dynamic expected:expectedSchemas) + { + String arrayColumnSchema=String.format("{'path': 'a', 'type': {'type': 'array', 'items': %1$s } }", + expected.Json); + String tableSchema=String.format("{'name': 'table', 'id': -1, 'type': 'schema', 'properties': [%1$s] }", + arrayColumnSchema); + Schema s=Schema.Parse(tableSchema); + Assert.AreEqual(1,s.getProperties().size(),"Json: {0}",expected.Json); + Property p=s.getProperties().get(0); + Assert.AreEqual(TypeKind.Array,p.getPropertyType().getType(),"Json: {0}",expected.Json); + ArrayPropertyType pt=(ArrayPropertyType)p.getPropertyType(); + Assert.IsNotNull(pt.getItems(),"Json: {0}",expected.Json); + switch(pt.getItems().getType()) + { + case Array: + ArrayPropertyType subArray=(ArrayPropertyType)pt.getItems(); + Assert.AreEqual(expected.Type,subArray.getItems().getType(),"Json: {0}",expected.Json); + break; + case Object: + ObjectPropertyType subObj=(ObjectPropertyType)pt.getItems(); + Assert.AreEqual(expected.Len,subObj.getProperties().size(),"Json: {0}",expected.Json); + break; + case Schema: + UdtPropertyType subRow=(UdtPropertyType)pt.getItems(); + Assert.AreEqual(expected.Name,subRow.getName(),"Json: {0}",expected.Json); + break; +default: + Assert.AreEqual(expected.Type,pt.getItems().getType(),"Json: {0}",expected.Json); + break; + } + } + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaObject() +public final void ParseSchemaObject() + { + +// Test object types include nested objects. +class AnonymousType { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } +} + +class AnonymousType2 { + public String Json; + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind Type; + + public AnonymousType2(String _Json, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.TypeKind _Type) { + Json = _Json; + Type = _Type; + } +} + +class AnonymousType3 { + public String Json; + public int Len; + + public AnonymousType3(String _Json, int _Len) { + Json = _Json; + Len = _Len; + } +} + +class AnonymousType4 { + public String Json; + public String Name; + + publ TO JAVA CONVERTER TODO TASK: There is no Java equivalent to the C# 'dynamic' keyword: + dynamic[] expectedSchemas = { AnonymousType("{'path': 'b', 'type': {'type': 'int8', 'storage': 'fixed'}}", + TypeKind.Int8), AnonymousType2("{'path': 'b', 'type': {'type': 'array', 'items': {'type': 'int32'}}}", + TypeKind.Int32), AnonymousType3("{'path': 'b', 'type': {'type': 'object', 'properties': [{'path': 'c', " + + "'type': {'type': 'bool'}}]}}", 1), AnonymousType4("{'path': 'b', 'type': {'type': 'schema', 'name': " + + "'myUDT'}}", "myUDT") }; + + for(/C#ic AnonymousType4(String _Json, String _Name) { + Json = _Json; + Name = _Name; + } +} + /dynamic expected:expectedSchemas) + { + String objectColumnSchema=String.format("{'path': 'a', 'type': {'type': 'object', 'properties': [%1$s] } " + + "}",expected.Json); + String tableSchema=String.format("{'name': 'table', 'id': -2, 'type': 'schema', 'properties': [%1$s] }", + objectColumnSchema); + try + { + Schema s=Schema.Parse(tableSchema); + Assert.AreEqual(1,s.getProperties().size(),"Json: {0}",expected.Json); + Property pa=s.getProperties().get(0); + Assert.AreEqual(TypeKind.Object,pa.getPropertyType().getType(),"Json: {0}",expected.Json); + ObjectPropertyType pt=(ObjectPropertyType)pa.getPropertyType(); + Assert.AreEqual(1,pt.getProperties().size(),"Json: {0}",expected.Json); + Property pb=pt.getProperties().get(0); + switch(pb.getPropertyType().getType()) + { + case Array: + ArrayPropertyType subArray=(ArrayPropertyType)pb.getPropertyType(); + Assert.AreEqual(expected.Type,subArray.getItems().getType(),"Json: {0}",expected.Json); + break; + case Object: + ObjectPropertyType subObj=(ObjectPropertyType)pb.getPropertyType(); + Assert.AreEqual(expected.Len,subObj.getProperties().size(),"Json: {0}",expected.Json); + break; + case Schema: + UdtPropertyType subRow=(UdtPropertyType)pb.getPropertyType(); + Assert.AreEqual(expected.Name,subRow.getName(),"Json: {0}",expected.Json); + break; +default: + Assert.AreEqual(expected.Type,pb.getPropertyType().getType(),"Json: {0}",expected.Json); + break; + } + } + catch(RuntimeException ex) + { + Assert.Fail("Exception: {0}, Json: {1}",ex,expected.Json); + } + } + } + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void ParseSchemaPartitionPrimaryKeys() +public final void ParseSchemaPartitionPrimaryKeys() + { + +// Test parsing both partition and primary sort keys. +class AnonymousType { + public Object[] CK; + + pulic String JsonCK + public String JsonPK; + public String[] PK; + pubblic AnonymousType(String _JsonPK, String _JsonCK, String[] _PK, Object[] _CK) { + JsonPK = _JsonPK; + JsonCK = _JsonCK; + PK = _PK; + CK = _CK; + } +} + +class AnonymousType2 { + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.SortDirection Dir; + + pulic String Path + + pubblic AnonymousType2(String _Path, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.SortDirection _Dir) { + Path = _Path; + Dir = _Dir; + } +} + +class AnonymousType3 { + public Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.SortDirection Dir; + + pulic String Path + pubblct[] expectedSchemas = new Object[] { AnonymousType("{'path': 'a'}", "{'path': 'b', 'direction': 'desc'}, " + + "{'path': 'c'}", new String[] { "a" }, new Object[] { AnonymousType2("b", SortDirection.Descending), + AnonymousType3("c", SortDirection.Ascending) }) }; + + for(bjeic AnonymousType3(String _Path, Microsoft.Azure.Cosmos.Serialization.HybridRow.Schemas.SortDirection _Dir) { + Path = _Path; + Dir = _Dir; + } +} + OObject expected:expectedSchemas) + { + String tableSchema=String.format("{{"+"\r\n"+ + " 'name': 'table', "+"\r\n"+ + " 'id': -3,"+"\r\n"+ + " 'type': 'schema', "+"\r\n"+ + " 'properties': ["+"\r\n"+ + " {{'path': 'a', 'type': {{'type': 'int8', 'storage': 'fixed'}}}},")+"\r\n"+ + " {{'path': 'b', 'type': {{'type': 'utf8', 'storage': 'variable', 'length': 2}}}}," + +"\r\n"+ + " {{'path': 'c', 'type': {{'type': 'datetime', 'storage': 'fixed'}}}},"+"\r\n"+ + " ],"+"\r\n"+ + " 'partitionkeys': [{expected.JsonPK}],"+"\r\n"+ + " 'primarykeys': [{expected.JsonCK}]"+"\r\n"+ + " }}"; + + try + { + Schema s=Schema.Parse(tableSchema); + Assert.AreEqual(3,s.getProperties().size(),"PK: {0}, CK: {1}",expected.JsonPK,expected.JsonCK); + for(int i=0;iThrowsException(()->Namespace.Parse(t.getJson())); + } + } + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ from the original: +//ORIGINAL LINE: private struct NamespaceParserTest +private final static class NamespaceParserTest { + private String Name; + + publblivate String Json + + publ +ic String getName() { + return Name; + } + + puic String getJson() { + return Json; + } + + publ +ic void setName(String value) { + Name = value; + } + + pric void setJson(String value) { + Json = value; + } +} +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SerializerUnitTest.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SerializerUnitTest.java new file mode 100644 index 0000000..a344c76 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/SerializerUnitTest.java @@ -0,0 +1,313 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.SchemaId; + +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Fields should be private +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1201 // Elements should appear in the correct order +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1204 // Elements should appear in the correct order +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1034 // Nested types should not be visible +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable CA1051 // Do not declare visible instance fields + + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][DeploymentItem(SerializerUnitTest.SchemaFile, "TestData")] public sealed class +// SerializerUnitTest +public final class SerializerUnitTest { + private static final int InitialRowSize = 2 * 1024 * 1024; + private static final String SchemaFile = "TestData\\BatchApiSchema.json"; + private Layout layout; + private LayoutResolver resolver; + private Namespace schema; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateBatchRequest() + public void CreateBatchRequest() { + BatchRequest request = new BatchRequest(); + BatchOperation tempVar = new BatchOperation(); + tempVar.OperationType = 3; + tempVar.Headers = new BatchRequestHeaders(); + tempVar.Headers.SampleRequestHeader = 12345L; + tempVar.ResourceType = 1; + tempVar.ResourcePath = "/some/url/path"; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar.ResourceBody = new byte[] { 1, 2, 3 }; + tempVar.ResourceBody = new byte[] { 1, 2, 3 }; + BatchOperation tempVar2 = new BatchOperation(); + tempVar2.OperationType = 2; + tempVar2.Headers = new BatchRequestHeaders(); + tempVar2.Headers.SampleRequestHeader = 98746L; + tempVar2.ResourceType = 2; + tempVar2.ResourcePath = "/some/other/url/path"; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: tempVar2.ResourceBody = new byte[] { 3, 2, 1 }; + tempVar2.ResourceBody = new byte[] { 3, 2, 1 }; + request.Operations = new ArrayList(Arrays.asList(tempVar, tempVar2)); + + // Write the request by serializing it to a row. + RowBuffer row = new RowBuffer(SerializerUnitTest.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + Result r = RowWriter.WriteBuffer(tempRef_row, request, BatchRequestSerializer.Write); + row = tempRef_row.argValue; + assert Result.Success == r; + System.out.printf("Length of serialized row: %1$s" + "\r\n", row.getLength()); + + // Read the row back again. + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowReader reader = new RowReader(tempRef_row2); + row = tempRef_row2.argValue; + tangible.RefObject tempRef_reader = + new tangible.RefObject(reader); + BatchRequest _; + tangible.OutObject tempOut__ = new tangible.OutObject(); + r = BatchRequestSerializer.Read(tempRef_reader, tempOut__); + _ = tempOut__.argValue; + reader = tempRef_reader.argValue; + assert Result.Success == r; + + // Dump the materialized request to the console. + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + reader = new RowReader(tempRef_row3); + row = tempRef_row3.argValue; + tangible.RefObject tempRef_reader2 = + new tangible.RefObject(reader); + String dumpStr; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + r = DiagnosticConverter.ReaderToString(tempRef_reader2, out dumpStr); + reader = tempRef_reader2.argValue; + assert Result.Success == r; + System.out.println(dumpStr); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void InitTestSuite() + public void InitTestSuite() { + String json = Files.readString(SerializerUnitTest.SchemaFile); + this.schema = Namespace.Parse(json); + this.resolver = new LayoutResolverNamespace(this.schema); + this.layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "BatchRequest")).SchemaId); + } + + public final static class BatchOperation { + public BatchRequestHeaders Headers; + public int OperationType; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public byte[] ResourceBody; + public byte[] ResourceBody; + public String ResourcePath; + public int ResourceType; + } + + public final static class BatchOperationResponse { + public BatchResponseHeaders Headers; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public byte[] ResourceBody; + public byte[] ResourceBody; + public int StatusCode; + } + + public static class BatchOperationSerializer { + public static final TypeArgument TypeArg = new TypeArgument(LayoutType.UDT, + new TypeArgumentList(new SchemaId(2))); + + public static Result Read(tangible.RefObject reader, tangible.OutObject operation) { + BatchOperation retval = new BatchOperation(); + operation.argValue = null; + while (reader.argValue.Read()) { + Result r; + switch (reader.argValue.getPath()) { + case "operationType": + tangible.OutObject tempOut_OperationType = new tangible.OutObject(); + r = reader.argValue.ReadInt32(tempOut_OperationType); + retval.OperationType = tempOut_OperationType.argValue; + if (r != Result.Success) { + return r; + } + + break; + case "headers": + tangible.RefObject tempRef_child = new tangible.RefObject(child); + tangible.OutObject tempOut_Headers = new tangible.OutObject(); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword + // - these are not converted by C# to Java Converter: + r = reader.argValue.ReadScope(retval, + (ref RowReader child, BatchOperation parent) -> BatchRequestHeadersSerializer.Read(tempRef_child, tempOut_Headers)); + parent.Headers = tempOut_Headers.argValue; + child = tempRef_child.argValue; + if (r != Result.Success) { + return r; + } + + break; + case "resourceType": + tangible.OutObject tempOut_ResourceType = new tangible.OutObject(); + r = reader.argValue.ReadInt32(tempOut_ResourceType); + retval.ResourceType = tempOut_ResourceType.argValue; + if (r != Result.Success) { + return r; + } + + break; + case "resourcePath": + tangible.OutObject tempOut_ResourcePath = new tangible.OutObject(); + r = reader.argValue.ReadString(tempOut_ResourcePath); + retval.ResourcePath = tempOut_ResourcePath.argValue; + if (r != Result.Success) { + return r; + } + + break; + case "resourceBody": + tangible.OutObject tempOut_ResourceBody = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: r = reader.ReadBinary(out retval.ResourceBody); + r = reader.argValue.ReadBinary(tempOut_ResourceBody); + retval.ResourceBody = tempOut_ResourceBody.argValue; + if (r != Result.Success) { + return r; + } + + break; + } + } + + operation.argValue = retval; + return Result.Success; + } + + public static Result Write(tangible.RefObject writer, TypeArgument typeArg, + BatchOperation operation) { + Result r = writer.argValue.WriteInt32("operationType", operation.OperationType); + if (r != Result.Success) { + return r; + } + + r = writer.argValue.WriteScope("headers", BatchRequestHeadersSerializer.TypeArg, operation.Headers, + BatchRequestHeadersSerializer.Write); + if (r != Result.Success) { + return r; + } + + r = writer.argValue.WriteInt32("resourceType", operation.ResourceType); + if (r != Result.Success) { + return r; + } + + r = writer.argValue.WriteString("resourcePath", operation.ResourcePath); + if (r != Result.Success) { + return r; + } + + r = writer.argValue.WriteBinary("resourceBody", operation.ResourceBody); + return r; + } + } + + public final static class BatchRequest { + public ArrayList Operations; + } + + public final static class BatchRequestHeaders { + public long SampleRequestHeader; + } + + public static class BatchRequestHeadersSerializer { + public static final TypeArgument TypeArg = new TypeArgument(LayoutType.UDT, + new TypeArgumentList(new SchemaId(1))); + + public static Result Read(tangible.RefObject reader, + tangible.OutObject header) { + BatchRequestHeaders retval = new BatchRequestHeaders(); + header.argValue = null; + while (reader.argValue.Read()) { + switch (reader.argValue.getPath()) { + case "sampleRequestHeader": + tangible.OutObject tempOut_SampleRequestHeader = new tangible.OutObject(); + Result r = reader.argValue.ReadInt64(tempOut_SampleRequestHeader); + retval.SampleRequestHeader = tempOut_SampleRequestHeader.argValue; + if (r != Result.Success) { + return r; + } + + break; + } + } + + header.argValue = retval; + return Result.Success; + } + + public static Result Write(tangible.RefObject writer, TypeArgument typeArg, + BatchRequestHeaders header) { + Result r = writer.argValue.WriteInt64("sampleRequestHeader", header.SampleRequestHeader); + return r; + } + } + + public static class BatchRequestSerializer { + public static final TypeArgument OperationsTypeArg = new TypeArgument(LayoutType.TypedArray, new TypeArgumentList(new azure.data.cosmos.serialization.hybridrow.layouts.TypeArgument[] { BatchOperationSerializer.TypeArg })); + + public static Result Read(tangible.RefObject reader, tangible.OutObject request) { + assert reader.argValue.Read(); + Contract.Assert(reader.argValue.getPath().equals("operations")); + + java.util.ArrayList operations; + tangible.OutObject> tempOut_operations = new tangible.OutObject>(); + Result r = azure.data.cosmos.serialization.hybridrow.io.RowReaderExtensions.ReadList(reader.argValue.clone(), BatchOperationSerializer.Read, tempOut_operations); + operations = tempOut_operations.argValue; + if (r != Result.Success) { + request.argValue = null; + return r; + } + + request.argValue = new BatchRequest(); + request.argValue.Operations = operations; + + return Result.Success; + } + + public static Result Write(tangible.RefObject writer, TypeArgument typeArg, BatchRequest request) { + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not converted by C# to Java Converter: + return writer.argValue.WriteScope("operations", BatchRequestSerializer.OperationsTypeArg, request.Operations, (ref RowWriter writer2, TypeArgument typeArg2, ArrayList operations) -> + { + for (BatchOperation operation : operations) { + Result r = writer2.WriteScope(null, BatchOperationSerializer.TypeArg, operation, BatchOperationSerializer.Write); + if (r != Result.Success) { + return r; + } + } + + return Result.Success; + }); + } + } + + public final static class BatchResponse { + public ArrayList Operations; + } + + public final static class BatchResponseHeaders { + public String SampleResponseHeader; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TaggedUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TaggedUnitTests.java new file mode 100644 index 0000000..a68877d --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TaggedUnitTests.java @@ -0,0 +1,256 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.nio.file.Files; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][DeploymentItem(TaggedUnitTests.SchemaFile, "TestData")] public sealed class TaggedUnitTests +public final class TaggedUnitTests { + private static final int InitialRowSize = 2 * 1024 * 1024; + private static final String SchemaFile = "TestData\\TaggedApiSchema.json"; + private Layout layout; + private LayoutResolver resolver; + private Namespace schema; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateTaggedApi() + public void CreateTaggedApi() { + RowBuffer row = new RowBuffer(TaggedUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + + TaggedApi c1 = new TaggedApi(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: c1.Tag1 = ((byte)1, "hello"); + c1.Tag1 = ((byte)1, "hello") + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: c1.Tag2 = ((byte)2, 28, 1974L); + c1.Tag2 = ((byte)2, 28, 1974L) + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteTaggedApi(tempRef_row, RowCursor.Create(tempRef_row2, out _), c1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + TaggedApi c2 = this.ReadTaggedApi(tempRef_row3, RowCursor.Create(tempRef_row4, out _)); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + assert c1 == c2; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public void ParseNamespaceExample() { + String json = Files.readString(TaggedUnitTests.SchemaFile); + this.schema = Namespace.Parse(json); + this.resolver = new LayoutResolverNamespace(this.schema); + this.layout = this.resolver.Resolve(tangible.ListHelper.find(this.schema.getSchemas(), x -> x.Name.equals( + "TaggedApi")).SchemaId); + } + + private TaggedApi ReadTaggedApi(tangible.RefObject row, tangible.RefObject root) { + TaggedApi pc = new TaggedApi(); + + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("tag1", out c); + assert c.Type.Immutable; + RowCursor tag1Scope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out tag1Scope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref tag1Scope, out tag1Scope) == Result.Success) { + assert tag1Scope.Immutable; + assert tag1Scope.MoveNext(row); + byte apiCode; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(ref row, ref + // tag1Scope, out byte apiCode)); + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref tag1Scope, + out apiCode)); + assert tag1Scope.MoveNext(row); + String str; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[1].Type.TypeAs().ReadSparse(row, ref tag1Scope, out str)); + pc.Tag1 = (apiCode, str) + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("tag2", out c); + assert !c.Type.Immutable; + RowCursor tag2Scope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out tag2Scope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref tag2Scope, out tag2Scope) == Result.Success) { + assert !tag2Scope.Immutable; + assert tag2Scope.MoveNext(row); + byte apiCode; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(ref row, ref + // tag2Scope, out byte apiCode)); + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref tag2Scope, + out apiCode)); + assert tag2Scope.MoveNext(row); + int val1; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[1].Type.TypeAs().ReadSparse(row, ref tag2Scope, out val1)); + assert tag2Scope.MoveNext(row); + long val2; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[2].Type.TypeAs().ReadSparse(row, ref tag2Scope, out val2)); + pc.Tag2 = (apiCode, val1, val2) + } + + return pc; + } + + private void WriteTaggedApi(tangible.RefObject row, tangible.RefObject root, TaggedApi pc) { + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("tag1", out c); + RowCursor tag1Scope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out tag1Scope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref tag1Scope, c.TypeArgs, + out tag1Scope)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref tag1Scope, pc.Tag1.Item1)); + assert tag1Scope.MoveNext(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[1].Type.TypeAs().WriteSparse(row, ref tag1Scope, pc.Tag1.Item2)); + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("tag2", out c); + RowCursor tag2Scope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out tag2Scope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref tag2Scope, c.TypeArgs, + out tag2Scope)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref tag2Scope, pc.Tag2.Item1)); + assert tag2Scope.MoveNext(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[1].Type.TypeAs().WriteSparse(row, ref tag2Scope, pc.Tag2.Item2)); + assert tag2Scope.MoveNext(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[2].Type.TypeAs().WriteSparse(row, ref tag2Scope, pc.Tag2.Item3)); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test + // types.")] private sealed class TaggedApi + private final static class TaggedApi { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public (byte, string) Tag1; + public (byte,String)Tag1 + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public (byte, int, long) Tag2; + public (byte,int,long)Tag2 + + // ReSharper disable once MemberCanBePrivate.Local + public boolean equals(TaggedApi other) { + return this.Tag1.equals(other.Tag1) && this.Tag2.equals(other.Tag2); + } + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof TaggedApi; + TaggedApi taggedApi = tempVar ? (TaggedApi)obj : null; + return tempVar && this.equals(taggedApi); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + int hashCode = 0; + hashCode = (hashCode * 397) ^ this.Tag1.hashCode(); + hashCode = (hashCode * 397) ^ this.Tag2.hashCode(); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TupleUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TupleUnitTests.java new file mode 100644 index 0000000..553519e --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TupleUnitTests.java @@ -0,0 +1,1099 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.nio.file.Files; +import java.time.LocalDateTime; + +// ReSharper disable once StringLiteralTypo +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][SuppressMessage("Naming", "DontUseVarForVariableTypes", Justification = "The types here +// are anonymous.")][DeploymentItem("TestData\\PerfCounterSchema.json", "TestData")] public sealed class TupleUnitTests +public final class TupleUnitTests { + private static final int InitialRowSize = 2 * 1024 * 1024; + + private final PerfCounter counterExample = new PerfCounter() { + Name ="RowInserts",Value =Tuple.Create("units",12046L) + }; + + private Namespace counterSchema; + private Layout countersLayout; + private LayoutResolver countersResolver; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateCoordCounter() + public void CreateCoordCounter() { + RowBuffer row = new RowBuffer(TupleUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.countersLayout, this.countersResolver); + + PerfCounter c1 = new PerfCounter(); + c1.Name = "CoordInserts"; + Coord tempVar = new Coord(); + tempVar.Lat = 12L; + tempVar.Lng = 40L; + c1.Coord = Tuple.Create("units", tempVar); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteCounter(tempRef_row, RowCursor.Create(tempRef_row2, out _), c1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + PerfCounter c2 = this.ReadCounter(tempRef_row3, RowCursor.Create(tempRef_row4, out _)); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + assert c1 == c2; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateCounter() + public void CreateCounter() { + RowBuffer row = new RowBuffer(TupleUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.countersLayout, this.countersResolver); + + PerfCounter c1 = this.counterExample; + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteCounter(tempRef_row, RowCursor.Create(tempRef_row2, out _), c1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + PerfCounter c2 = this.ReadCounter(tempRef_row3, RowCursor.Create(tempRef_row4, out _)); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + assert c1 == c2; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateMinMeanMaxCounter() + public void CreateMinMeanMaxCounter() { + RowBuffer row = new RowBuffer(TupleUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.countersLayout, this.countersResolver); + + PerfCounter c1 = new PerfCounter(); + c1.Name = "RowInserts"; + c1.MinMaxValue = Tuple.Create("units", Tuple.Create(12L, 542L, 12046L)); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteCounter(tempRef_row, RowCursor.Create(tempRef_row2, out _), c1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + PerfCounter c2 = this.ReadCounter(tempRef_row3, RowCursor.Create(tempRef_row4, out _)); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + assert c1 == c2; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void DownwardDelegateWriteScope() + public void DownwardDelegateWriteScope() { + RowBuffer row = new RowBuffer(TupleUnitTests.InitialRowSize); + Layout layout = this.countersResolver.Resolve(tangible.ListHelper.find(this.counterSchema.getSchemas(), + x -> x.Name.equals("CounterSet")).SchemaId); + row.InitLayout(HybridRowVersion.V1, layout, this.countersResolver); + + LayoutColumn col; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert layout.TryFind("history", out col); + StringToken historyToken; + tangible.OutObject tempOut_historyToken = + new tangible.OutObject(); + assert layout.getTokenizer().TryFindToken(col.Path, tempOut_historyToken); + historyToken = tempOut_historyToken.argValue; + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor history; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row, out history).Find(tempRef_row2, historyToken); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + int ctx = 1; // ignored + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_history = + new tangible.RefObject(history); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not + // converted by C# to Java Converter: + ResultAssert.IsSuccess(LayoutType.TypedArray.WriteScope(tempRef_row3, tempRef_history, col.TypeArgs, ctx, + (ref RowBuffer row2, ref RowCursor arrCur, int ctx2) -> + { + for (int i = 0; i < 5; i++) { + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row2); + tangible.RefObject tempRef_arrCur = + new tangible.RefObject(arrCur); + ResultAssert.IsSuccess(LayoutType.UDT.WriteScope(tempRef_row2, tempRef_arrCur, + arrCur.ScopeTypeArgs[0].TypeArgs, i, (ref RowBuffer row3, ref RowCursor udtCur, int ctx3) -> + { + LayoutColumn col3; + assert udtCur.Layout.TryFind("minmeanmax", out col3); + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row3); + tangible.RefObjecttempRef_row32 = new tangible.RefObject (row3); + ResultAssert.IsSuccess(LayoutType.TypedTuple.WriteScope(tempRef_row3, udtCur.Find(tempRef_row32, + col3.Path), col3.TypeArgs, ctx3, (ref RowBuffer row4, ref RowCursor tupCur, int ctx4) -> + { + if (ctx4 > 0) { + tangible.RefObjecttempRef_row4 = new tangible.RefObject (row4); + tangible.RefObjecttempRef_tupCur = new tangible.RefObject (tupCur); + ResultAssert.IsSuccess(LayoutType.Utf8.WriteSparse(tempRef_row4, tempRef_tupCur, "abc")); + tupCur = tempRef_tupCur.argValue; + row4 = tempRef_row4.argValue; + } + + if (ctx4 > 1) { + tangible.RefObjecttempRef_row42 = new tangible.RefObject (row4); + assert tupCur.MoveNext(tempRef_row42); + row4 = tempRef_row42.argValue; + tangible.RefObject tempRef_row43 = new tangible.RefObject(row4); + tangible.RefObject tempRef_tupCur2 = new tangible.RefObject(tupCur); + ResultAssert.IsSuccess(LayoutType.TypedTuple.WriteScope(tempRef_row43, tempRef_tupCur2, + tupCur.ScopeTypeArgs[1].TypeArgs, ctx4, (ref RowBuffer row5, ref RowCursor tupCur2, + int ctx5) -> + { + if (ctx5 > 1) { + tangible.RefObject tempRef_row5 = new tangible.RefObject(row5); + tangible.RefObject tempRef_tupCur2 = new tangible.RefObject(tupCur2); + ResultAssert.IsSuccess(LayoutType.Int64.WriteSparse(tempRef_row5, tempRef_tupCur2 + , ctx5)); + tupCur2 = tempRef_tupCur2.argValue; + row5 = tempRef_row5.argValue; + } + + if (ctx5 > 2) { + tangible.RefObjecttempRef_row52 = new tangible.RefObject (row5); + assert tupCur2.MoveNext(tempRef_row52); + row5 = tempRef_row52.argValue; + tangible.RefObject tempRef_row53 = new tangible.RefObject(row5); + tangible.RefObject tempRef_tupCur22 = new tangible.RefObject(tupCur2); + ResultAssert.IsSuccess(LayoutType.Int64.WriteSparse(tempRef_row53, + tempRef_tupCur22, ctx5)); + tupCur2 = tempRef_tupCur22.argValue; + row5 = tempRef_row53.argValue; + } + + if (ctx5 > 3) { + tangible.RefObjecttempRef_row54 = new tangible.RefObject (row5); + assert tupCur2.MoveNext(tempRef_row54); + row5 = tempRef_row54.argValue; + tangible.RefObject tempRef_row55 = new tangible.RefObject(row5); + tangible.RefObject tempRef_tupCur23 = new tangible.RefObject(tupCur2); + ResultAssert.IsSuccess(LayoutType.Int64.WriteSparse(tempRef_row55, + tempRef_tupCur23, ctx5)); + tupCur2 = tempRef_tupCur23.argValue; + row5 = tempRef_row55.argValue; + } + + return Result.Success; + })); + tupCur = tempRef_tupCur2.argValue; + row4 = tempRef_row43.argValue; + } + + return Result.Success; + })); + row3 = tempRef_row32.argValue; + row3 = tempRef_row3.argValue; + + return Result.Success; + })); + arrCur = tempRef_arrCur.argValue; + row2 = tempRef_row2.argValue; + + tangible.RefObjecttempRef_row22 = new tangible.RefObject (row2); + assert !arrCur.MoveNext(tempRef_row22); + row2 = tempRef_row22.argValue; + } + + return Result.Success; + })); + history = tempRef_history.argValue; + row = tempRef_row3.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public void ParseNamespaceExample() { + String json = Files.readString("TestData\\PerfCounterSchema.json"); + this.counterSchema = Namespace.Parse(json); + this.countersResolver = new LayoutResolverNamespace(this.counterSchema); + this.countersLayout = this.countersResolver.Resolve(tangible.ListHelper.find(this.counterSchema.getSchemas(), + x -> x.Name.equals("Counters")).SchemaId); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void PreventInsertsAndDeletesInFixedArityCounter() + public void PreventInsertsAndDeletesInFixedArityCounter() { + RowBuffer row = new RowBuffer(TupleUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.countersLayout, this.countersResolver); + + PerfCounter c1 = this.counterExample; + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteCounter(tempRef_row, RowCursor.Create(tempRef_row2, out _), c1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.countersLayout.TryFind("value", out c); + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor valueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row3, out valueScope).Find(tempRef_row4, c.Path); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(tempRef_row5, ref valueScope, c.TypeArgs, + out valueScope)); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + RowCursor valueScope2; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row6, out valueScope2).Find(tempRef_row7, c.Path); + row = tempRef_row7.argValue; + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row8, ref valueScope2, + out valueScope2)); + row = tempRef_row8.argValue; + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert valueScope.AsReadOnly(out _).ScopeType == valueScope2.ScopeType; + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert valueScope.AsReadOnly(out _).start == valueScope2.start; + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert valueScope.AsReadOnly(out _).Immutable == valueScope2.Immutable; + + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.TypeConstraint(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row9, ref valueScope, + "millis", UpdateOptions.InsertAt)); + row = tempRef_row9.argValue; + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.TypeConstraint(c.TypeArgs[0].Type.TypeAs().DeleteSparse(tempRef_row10, + ref valueScope)); + row = tempRef_row10.argValue; + tangible.RefObject tempRef_row11 = + new tangible.RefObject(row); + assert !valueScope.MoveTo(tempRef_row11, 2); + row = tempRef_row11.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void VerifyTypeConstraintsCoordCounter() + public void VerifyTypeConstraintsCoordCounter() { + RowBuffer row = new RowBuffer(TupleUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.countersLayout, this.countersResolver); + + PerfCounter c1 = new PerfCounter(); + c1.Name = "RowInserts"; + Coord tempVar = new Coord(); + tempVar.Lat = 12L; + tempVar.Lng = 40L; + c1.Coord = Tuple.Create("units", tempVar); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteCounter(tempRef_row, RowCursor.Create(tempRef_row2, out _), c1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.countersLayout.TryFind("coord", out c); + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor valueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row3, out valueScope).Find(tempRef_row4, c.Path); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(tempRef_row5, ref valueScope, c.TypeArgs, + out valueScope)); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + tangible.RefObject tempRef_valueScope = + new tangible.RefObject(valueScope); + ResultAssert.TypeConstraint(LayoutType.DateTime.WriteSparse(tempRef_row6, tempRef_valueScope, + LocalDateTime.now())); + valueScope = tempRef_valueScope.argValue; + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row7, ref valueScope, + "mins")); + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + assert valueScope.MoveNext(tempRef_row8); + row = tempRef_row8.argValue; + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + tangible.RefObject tempRef_valueScope2 = + new tangible.RefObject(valueScope); + ResultAssert.TypeConstraint(LayoutType.Int8.WriteSparse(tempRef_row9, tempRef_valueScope2, (byte)42)); + valueScope = tempRef_valueScope2.argValue; + row = tempRef_row9.argValue; + + TypeArgument coordType = c.TypeArgs[1]; + + // Invalid because is a UDT but the wrong type. + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + tangible.RefObject tempRef_valueScope3 = + new tangible.RefObject(valueScope); + RowCursor _; + tangible.OutObject tempOut__ = + new tangible.OutObject(); + ResultAssert.TypeConstraint(coordType.getType().TypeAs().WriteScope(tempRef_row10, + tempRef_valueScope3, new TypeArgumentList(this.countersLayout.getSchemaId().clone()), tempOut__)); + _ = tempOut__.argValue; + valueScope = tempRef_valueScope3.argValue; + row = tempRef_row10.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void VerifyTypeConstraintsCounter() + public void VerifyTypeConstraintsCounter() { + RowBuffer row = new RowBuffer(TupleUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.countersLayout, this.countersResolver); + + PerfCounter c1 = this.counterExample; + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteCounter(tempRef_row, RowCursor.Create(tempRef_row2, out _), c1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.countersLayout.TryFind("value", out c); + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor valueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row3, out valueScope).Find(tempRef_row4, c.Path); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(tempRef_row5, ref valueScope, c.TypeArgs, + out valueScope)); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + tangible.RefObject tempRef_valueScope = + new tangible.RefObject(valueScope); + ResultAssert.TypeConstraint(LayoutType.Boolean.WriteSparse(tempRef_row6, tempRef_valueScope, true)); + valueScope = tempRef_valueScope.argValue; + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row7, ref valueScope, + "millis")); + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + assert valueScope.MoveNext(tempRef_row8); + row = tempRef_row8.argValue; + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + tangible.RefObject tempRef_valueScope2 = + new tangible.RefObject(valueScope); + ResultAssert.TypeConstraint(LayoutType.Float32.WriteSparse(tempRef_row9, tempRef_valueScope2, 0.1F)); + valueScope = tempRef_valueScope2.argValue; + row = tempRef_row9.argValue; + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[1].Type.TypeAs().WriteSparse(tempRef_row10, ref valueScope, + 100L)); + row = tempRef_row10.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void VerifyTypeConstraintsMinMeanMaxCounter() + public void VerifyTypeConstraintsMinMeanMaxCounter() { + RowBuffer row = new RowBuffer(TupleUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.countersLayout, this.countersResolver); + + PerfCounter c1 = new PerfCounter(); + c1.Name = "RowInserts"; + c1.MinMaxValue = Tuple.Create("units", Tuple.Create(12L, 542L, 12046L)); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteCounter(tempRef_row, RowCursor.Create(tempRef_row2, out _), c1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + + // ReSharper disable once StringLiteralTypo + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.countersLayout.TryFind("minmeanmax", out c); + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor valueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row3, out valueScope).Find(tempRef_row4, c.Path); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(tempRef_row5, ref valueScope, c.TypeArgs, + out valueScope)); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + tangible.RefObject tempRef_valueScope = + new tangible.RefObject(valueScope); + ResultAssert.TypeConstraint(LayoutType.DateTime.WriteSparse(tempRef_row6, tempRef_valueScope, + LocalDateTime.now())); + valueScope = tempRef_valueScope.argValue; + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row7, ref valueScope, + "secs")); + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + assert valueScope.MoveNext(tempRef_row8); + row = tempRef_row8.argValue; + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + tangible.RefObject tempRef_valueScope2 = + new tangible.RefObject(valueScope); + ResultAssert.TypeConstraint(LayoutType.Decimal.WriteSparse(tempRef_row9, tempRef_valueScope2, 12)); + valueScope = tempRef_valueScope2.argValue; + row = tempRef_row9.argValue; + + TypeArgument mmmType = c.TypeArgs[1]; + + // Invalid because not a tuple type. + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + RowCursor mmmScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.TypeConstraint(mmmType.getType().TypeAs().WriteScope(tempRef_row10, + ref valueScope, TypeArgumentList.Empty, out mmmScope)); + row = tempRef_row10.argValue; + + // Invalid because is a tuple type but with the wrong parameters. + tangible.RefObject tempRef_row11 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.TypeConstraint(mmmType.getType().TypeAs().WriteScope(tempRef_row11, + ref valueScope, new TypeArgumentList(new TypeArgument[] + { + new TypeArgument(LayoutType.Boolean), + new TypeArgument(LayoutType.Int64) + }), out mmmScope)); + row = tempRef_row11.argValue; + + // Invalid because is a tuple type but with the wrong arity. + tangible.RefObject tempRef_row12 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.TypeConstraint(mmmType.getType().TypeAs().WriteScope(tempRef_row12, + ref valueScope, new TypeArgumentList(new TypeArgument[] { new TypeArgument(LayoutType.Utf8) }), + out mmmScope)); + row = tempRef_row12.argValue; + + tangible.RefObject tempRef_row13 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(mmmType.getType().TypeAs().WriteScope(tempRef_row13, + ref valueScope, mmmType.getTypeArgs().clone(), out mmmScope)); + row = tempRef_row13.argValue; + tangible.RefObject tempRef_row14 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ResultAssert.TypeConstraint(LayoutType.Binary.WriteSparse(ref row, ref valueScope, new + // byte[] { 1, 2, 3 })); + ResultAssert.TypeConstraint(LayoutType.Binary.WriteSparse(tempRef_row14, ref valueScope, new byte[] { 1, 2, + 3 })); + row = tempRef_row14.argValue; + tangible.RefObject tempRef_row15 = + new tangible.RefObject(row); + tangible.RefObject tempRef_mmmScope = + new tangible.RefObject(mmmScope); + ResultAssert.IsSuccess(mmmType.getTypeArgs().get(0).getType().TypeAs().WriteSparse(tempRef_row15 + , tempRef_mmmScope, 1L)); + mmmScope = tempRef_mmmScope.argValue; + row = tempRef_row15.argValue; + tangible.RefObject tempRef_row16 = + new tangible.RefObject(row); + assert mmmScope.MoveNext(tempRef_row16); + row = tempRef_row16.argValue; + tangible.RefObject tempRef_row17 = + new tangible.RefObject(row); + tangible.RefObject tempRef_mmmScope2 = + new tangible.RefObject(mmmScope); + ResultAssert.IsSuccess(mmmType.getTypeArgs().get(1).getType().TypeAs().WriteSparse(tempRef_row17 + , tempRef_mmmScope2, 2L)); + mmmScope = tempRef_mmmScope2.argValue; + row = tempRef_row17.argValue; + tangible.RefObject tempRef_row18 = + new tangible.RefObject(row); + assert mmmScope.MoveNext(tempRef_row18); + row = tempRef_row18.argValue; + tangible.RefObject tempRef_row19 = + new tangible.RefObject(row); + tangible.RefObject tempRef_mmmScope3 = + new tangible.RefObject(mmmScope); + ResultAssert.IsSuccess(mmmType.getTypeArgs().get(2).getType().TypeAs().WriteSparse(tempRef_row19 + , tempRef_mmmScope3, 3L)); + mmmScope = tempRef_mmmScope3.argValue; + row = tempRef_row19.argValue; + } + + private static Coord ReadCoord(tangible.RefObject row, tangible.RefObject coordScope) { + Layout coordLayout = coordScope.argValue.getLayout(); + Coord cd = new Coord(); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert coordLayout.TryFind("lat", out c); + tangible.OutObject tempOut_Lat = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadFixed(row, coordScope, c, tempOut_Lat)); + cd.Lat = tempOut_Lat.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert coordLayout.TryFind("lng", out c); + tangible.OutObject tempOut_Lng = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadFixed(row, coordScope, c, tempOut_Lng)); + cd.Lng = tempOut_Lng.argValue; + + return cd; + } + + private PerfCounter ReadCounter(tangible.RefObject row, tangible.RefObject root) { + PerfCounter pc = new PerfCounter(); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.countersLayout.TryFind("name", out c); + tangible.OutObject tempOut_Name = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, root, c, tempOut_Name)); + pc.Name = tempOut_Name.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.countersLayout.TryFind("value", out c); + assert c.Type.Immutable; + RowCursor valueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out valueScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref valueScope, out valueScope) == Result.Success) { + assert valueScope.Immutable; + assert valueScope.MoveNext(row); + String units; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref valueScope, out units)); + assert valueScope.MoveNext(row); + long metric; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[1].Type.TypeAs().ReadSparse(row, ref valueScope, + out metric)); + pc.Value = Tuple.Create(units, metric); + } + + // ReSharper disable once StringLiteralTypo + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.countersLayout.TryFind("minmeanmax", out c); + assert c.Type.Immutable; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out valueScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref valueScope, out valueScope) == Result.Success) { + assert valueScope.Immutable; + assert valueScope.MoveNext(row); + String units; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref valueScope, out units)); + + assert valueScope.MoveNext(row); + TypeArgument mmmType = c.TypeArgs[1]; + tangible.RefObject tempRef_valueScope = + new tangible.RefObject(valueScope); + RowCursor mmmScope; + tangible.OutObject tempOut_mmmScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(mmmType.getType().TypeAs().ReadScope(row, tempRef_valueScope, + tempOut_mmmScope)); + mmmScope = tempOut_mmmScope.argValue; + valueScope = tempRef_valueScope.argValue; + + assert mmmScope.Immutable; + assert mmmScope.MoveNext(row); + tangible.RefObject tempRef_mmmScope = + new tangible.RefObject(mmmScope); + long min; + tangible.OutObject tempOut_min = new tangible.OutObject(); + ResultAssert.IsSuccess(mmmType.getTypeArgs().get(0).getType().TypeAs().ReadSparse(row, + tempRef_mmmScope, tempOut_min)); + min = tempOut_min.argValue; + mmmScope = tempRef_mmmScope.argValue; + assert mmmScope.MoveNext(row); + tangible.RefObject tempRef_mmmScope2 = + new tangible.RefObject(mmmScope); + long mean; + tangible.OutObject tempOut_mean = new tangible.OutObject(); + ResultAssert.IsSuccess(mmmType.getTypeArgs().get(1).getType().TypeAs().ReadSparse(row, + tempRef_mmmScope2, tempOut_mean)); + mean = tempOut_mean.argValue; + mmmScope = tempRef_mmmScope2.argValue; + assert mmmScope.MoveNext(row); + tangible.RefObject tempRef_mmmScope3 = + new tangible.RefObject(mmmScope); + long max; + tangible.OutObject tempOut_max = new tangible.OutObject(); + ResultAssert.IsSuccess(mmmType.getTypeArgs().get(2).getType().TypeAs().ReadSparse(row, + tempRef_mmmScope3, tempOut_max)); + max = tempOut_max.argValue; + mmmScope = tempRef_mmmScope3.argValue; + + pc.MinMaxValue = Tuple.Create(units, Tuple.Create(min, mean, max)); + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.countersLayout.TryFind("coord", out c); + assert c.Type.Immutable; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out valueScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref valueScope, out valueScope) == Result.Success) { + assert valueScope.Immutable; + assert valueScope.MoveNext(row); + String units; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref valueScope, out units)); + + assert valueScope.MoveNext(row); + RowCursor coordScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[1].Type.TypeAs().ReadScope(row, ref valueScope, + out coordScope)); + tangible.RefObject tempRef_coordScope = new tangible.RefObject(coordScope); + pc.Coord = Tuple.Create(units, TupleUnitTests.ReadCoord(row, tempRef_coordScope)); + coordScope = tempRef_coordScope.argValue; + } + + return pc; + } + + private static void WriteCoord(tangible.RefObject row, tangible.RefObject coordScope, TypeArgumentList typeArgs, Coord cd) { + Layout coordLayout = row.argValue.getResolver().Resolve(typeArgs.getSchemaId().clone()); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert coordLayout.TryFind("lat", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteFixed(row, coordScope, c, cd.Lat)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert coordLayout.TryFind("lng", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteFixed(row, coordScope, c, cd.Lng)); + } + + private void WriteCounter(tangible.RefObject row, tangible.RefObject root, PerfCounter pc) { + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.countersLayout.TryFind("name", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, root, c, pc.Name)); + + if (pc.Value != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.countersLayout.TryFind("value", out c); + RowCursor valueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out valueScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref valueScope, c.TypeArgs, + out valueScope)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref valueScope, + pc.Value.Item1)); + assert valueScope.MoveNext(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[1].Type.TypeAs().WriteSparse(row, ref valueScope, + pc.Value.Item2)); + } + + if (pc.MinMaxValue != null) { + // ReSharper disable once StringLiteralTypo + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.countersLayout.TryFind("minmeanmax", out c); + RowCursor valueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out valueScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref valueScope, c.TypeArgs, + out valueScope)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref valueScope, + pc.MinMaxValue.Item1)); + + assert valueScope.MoveNext(row); + TypeArgument mmmType = c.TypeArgs[1]; + RowCursor mmmScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(mmmType.getType().TypeAs().WriteScope(row, ref valueScope, + mmmType.getTypeArgs().clone(), out mmmScope)); + + tangible.RefObject tempRef_mmmScope = + new tangible.RefObject(mmmScope); + ResultAssert.IsSuccess(mmmType.getTypeArgs().get(0).getType().TypeAs().WriteSparse(row, + tempRef_mmmScope, pc.MinMaxValue.Item2.Item1)); + mmmScope = tempRef_mmmScope.argValue; + + assert mmmScope.MoveNext(row); + tangible.RefObject tempRef_mmmScope2 = + new tangible.RefObject(mmmScope); + ResultAssert.IsSuccess(mmmType.getTypeArgs().get(1).getType().TypeAs().WriteSparse(row, + tempRef_mmmScope2, pc.MinMaxValue.Item2.Item2)); + mmmScope = tempRef_mmmScope2.argValue; + + assert mmmScope.MoveNext(row); + tangible.RefObject tempRef_mmmScope3 = + new tangible.RefObject(mmmScope); + ResultAssert.IsSuccess(mmmType.getTypeArgs().get(2).getType().TypeAs().WriteSparse(row, + tempRef_mmmScope3, pc.MinMaxValue.Item2.Item3)); + mmmScope = tempRef_mmmScope3.argValue; + } + + if (pc.Coord != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.countersLayout.TryFind("coord", out c); + RowCursor valueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out valueScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref valueScope, c.TypeArgs, + out valueScope)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref valueScope, + pc.Coord.Item1)); + + assert valueScope.MoveNext(row); + TypeArgument mmmType = c.TypeArgs[1]; + tangible.RefObject tempRef_valueScope = + new tangible.RefObject(valueScope); + RowCursor coordScope; + tangible.OutObject tempOut_coordScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(mmmType.getType().TypeAs().WriteScope(row, tempRef_valueScope, + mmmType.getTypeArgs().clone(), tempOut_coordScope)); + coordScope = tempOut_coordScope.argValue; + valueScope = tempRef_valueScope.argValue; + tangible.RefObject tempRef_coordScope = + new tangible.RefObject(coordScope); + TupleUnitTests.WriteCoord(row, tempRef_coordScope, mmmType.getTypeArgs().clone(), pc.Coord.Item2); + coordScope = tempRef_coordScope.argValue; + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test types.")] private sealed class Coord + private final static class Coord { + public long Lat; + public long Lng; + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof Coord; + Coord coord = tempVar ? (Coord)obj : null; + return tempVar && this.equals(coord); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + return ((new Long(this.Lat)).hashCode() * 397) ^ (new Long(this.Lng)).hashCode(); + } + } + + private boolean equals(Coord other) { + return this.Lat == other.Lat && this.Lng == other.Lng; + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test types.")] private sealed class PerfCounter + private final static class PerfCounter { + // ReSharper disable once MemberHidesStaticFromOuterClass + public Tuple Coord; + public Tuple> MinMaxValue; + public String Name; + public Tuple Value; + + // ReSharper disable once MemberCanBePrivate.Local + public boolean equals(PerfCounter other) { + return this.Name.equals(other.Name) && this.Value.equals(other.Value) && this.MinMaxValue.equals(other.MinMaxValue) && this.Coord.equals(other.Coord); + } + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof PerfCounter; + PerfCounter counter = tempVar ? (PerfCounter)obj : null; + return tempVar && this.equals(counter); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + int hashCode = this.Name == null ? null : this.Name.hashCode() != null ? this.Name.hashCode() : 0; + hashCode = (hashCode * 397) ^ (this.Value == null ? null : this.Value.hashCode() != null ? this.Value.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.MinMaxValue == null ? null : this.MinMaxValue.hashCode() != null ? this.MinMaxValue.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Coord == null ? null : this.Coord.hashCode() != null ? this.Coord.hashCode() : 0); + return hashCode; + } + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedArrayUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedArrayUnitTests.java new file mode 100644 index 0000000..7df9892 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedArrayUnitTests.java @@ -0,0 +1,661 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; + +// ReSharper disable StringLiteralTypo +// ReSharper disable IdentifierTypo + + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][DeploymentItem(TypedArrayUnitTests.SchemaFile, "TestData")] public sealed class +// TypedArrayUnitTests +public final class TypedArrayUnitTests { + private static final int InitialRowSize = 2 * 1024 * 1024; + private static final String SchemaFile = "TestData\\TagSchema.json"; + private Namespace counterSchema; + private Layout layout; + private LayoutResolver resolver; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateTags() + public void CreateTags() { + RowBuffer row = new RowBuffer(TypedArrayUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + + Tagged t1 = new Tagged(); + t1.Title = "Thriller"; + t1.Tags = new ArrayList(Arrays.asList("classic", "Post-disco", "funk")); + t1.Options = new ArrayList(Arrays.asList(8, null, 9)); + t1.Ratings = new ArrayList>(Arrays.asList(new ArrayList(Arrays.asList(1.2, 3.0)), + new ArrayList(Arrays.asList(4.1, 5.7)), new ArrayList(Arrays.asList(7.3, 8.12, 9.14)))); + SimilarMatch tempVar = new SimilarMatch(); + tempVar.Thumbprint = "TRABACN128F425B784"; + tempVar.Score = 0.87173699999999998; + SimilarMatch tempVar2 = new SimilarMatch(); + tempVar2.Thumbprint = "TRJYGLF12903CB4952"; + tempVar2.Score = 0.75105200000000005; + SimilarMatch tempVar3 = new SimilarMatch(); + tempVar3.Thumbprint = "TRWJMMB128F429D550"; + tempVar3.Score = 0.50866100000000003; + t1.Similars = new ArrayList(Arrays.asList(tempVar, tempVar2, tempVar3)); + t1.Priority = new ArrayList>(Arrays.asList(Tuple.Create("80's", 100L), Tuple.Create( + "classics", 100L), Tuple.Create("pop", 50L))); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteTagged(tempRef_row, RowCursor.Create(tempRef_row2, out _), t1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Tagged t2 = this.ReadTagged(tempRef_row3, RowCursor.Create(tempRef_row4, out _)); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + assert t1 == t2; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public void ParseNamespaceExample() { + String json = Files.readString(TypedArrayUnitTests.SchemaFile); + this.counterSchema = Namespace.Parse(json); + this.resolver = new LayoutResolverNamespace(this.counterSchema); + this.layout = this.resolver.Resolve(tangible.ListHelper.find(this.counterSchema.getSchemas(), + x -> x.Name.equals("Tagged")).SchemaId); + } + + private static SimilarMatch ReadSimilarMatch(tangible.RefObject row, + tangible.RefObject matchScope) { + Layout matchLayout = matchScope.argValue.getLayout(); + SimilarMatch m = new SimilarMatch(); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert matchLayout.TryFind("thumbprint", out c); + tangible.OutObject tempOut_Thumbprint = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadFixed(row, matchScope, c, tempOut_Thumbprint)); + m.Thumbprint = tempOut_Thumbprint.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert matchLayout.TryFind("score", out c); + tangible.OutObject tempOut_Score = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadFixed(row, matchScope, c, tempOut_Score)); + m.Score = tempOut_Score.argValue; + return m; + } + + private Tagged ReadTagged(tangible.RefObject row, tangible.RefObject root) { + Tagged value = new Tagged(); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("title", out c); + tangible.OutObject tempOut_Title = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, root, c, tempOut_Title)); + value.Title = tempOut_Title.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("tags", out c); + RowCursor tagsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out tagsScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref tagsScope, out tagsScope) == Result.Success) { + value.Tags = new ArrayList(); + while (tagsScope.MoveNext(row)) { + String item; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref tagsScope, + out item)); + value.Tags.add(item); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("options", out c); + RowCursor optionsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out optionsScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref optionsScope, out optionsScope) == Result.Success) { + value.Options = new ArrayList(); + while (optionsScope.MoveNext(row)) { + TypeArgument itemType = c.TypeArgs[0]; + tangible.RefObject tempRef_optionsScope = + new tangible.RefObject(optionsScope); + RowCursor nullableScope; + tangible.OutObject tempOut_nullableScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(itemType.getType().TypeAs().ReadScope(row, + tempRef_optionsScope, tempOut_nullableScope)); + nullableScope = tempOut_nullableScope.argValue; + optionsScope = tempRef_optionsScope.argValue; + + if (nullableScope.MoveNext(row)) { + tangible.RefObject tempRef_nullableScope = new tangible.RefObject(nullableScope); + ResultAssert.IsSuccess(LayoutNullable.HasValue(row, tempRef_nullableScope)); + nullableScope = tempRef_nullableScope.argValue; + + tangible.RefObject tempRef_nullableScope2 = new tangible.RefObject(nullableScope); + int itemValue; + tangible.OutObject tempOut_itemValue = new tangible.OutObject(); + ResultAssert.IsSuccess(itemType.getTypeArgs().get(0).getType().TypeAs().ReadSparse(row, tempRef_nullableScope2, tempOut_itemValue)); + itemValue = tempOut_itemValue.argValue; + nullableScope = tempRef_nullableScope2.argValue; + + value.Options.add(itemValue); + } else { + tangible.RefObject tempRef_nullableScope3 = new tangible.RefObject(nullableScope); + ResultAssert.NotFound(LayoutNullable.HasValue(row, tempRef_nullableScope3)); + nullableScope = tempRef_nullableScope3.argValue; + + value.Options.add(null); + } + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("ratings", out c); + RowCursor ratingsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out ratingsScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref ratingsScope, out ratingsScope) == Result.Success) { + value.Ratings = new ArrayList>(); + TypeArgument innerType = c.TypeArgs[0]; + LayoutTypedArray innerLayout = innerType.getType().TypeAs(); + RowCursor innerScope = null; + tangible.RefObject tempRef_innerScope = + new tangible.RefObject(innerScope); + while (ratingsScope.MoveNext(row, tempRef_innerScope)) { + innerScope = tempRef_innerScope.argValue; + ArrayList item = new ArrayList(); + tangible.RefObject tempRef_ratingsScope = + new tangible.RefObject(ratingsScope); + tangible.OutObject tempOut_innerScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(innerLayout.ReadScope(row, tempRef_ratingsScope, tempOut_innerScope)); + innerScope = tempOut_innerScope.argValue; + ratingsScope = tempRef_ratingsScope.argValue; + while (Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(innerScope.clone() + , row)) { + LayoutFloat64 itemLayout = innerType.getTypeArgs().get(0).getType().TypeAs(); + tangible.RefObject tempRef_innerScope2 + = new tangible.RefObject(innerScope); + double innerItem; + tangible.OutObject tempOut_innerItem = new tangible.OutObject(); + ResultAssert.IsSuccess(itemLayout.ReadSparse(row, tempRef_innerScope2, tempOut_innerItem)); + innerItem = tempOut_innerItem.argValue; + innerScope = tempRef_innerScope2.argValue; + item.add(innerItem); + } + + value.Ratings.add(item); + } + innerScope = tempRef_innerScope.argValue; + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("similars", out c); + RowCursor similarsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out similarsScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref similarsScope, out similarsScope) == Result.Success) { + value.Similars = new ArrayList(); + while (similarsScope.MoveNext(row)) { + TypeArgument innerType = c.TypeArgs[0]; + LayoutUDT innerLayout = innerType.getType().TypeAs(); + tangible.RefObject tempRef_similarsScope = + new tangible.RefObject(similarsScope); + RowCursor matchScope; + tangible.OutObject tempOut_matchScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(innerLayout.ReadScope(row, tempRef_similarsScope, tempOut_matchScope)); + matchScope = tempOut_matchScope.argValue; + similarsScope = tempRef_similarsScope.argValue; + tangible.RefObject tempRef_matchScope = + new tangible.RefObject(matchScope); + SimilarMatch item = TypedArrayUnitTests.ReadSimilarMatch(row, tempRef_matchScope); + matchScope = tempRef_matchScope.argValue; + value.Similars.add(item); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("priority", out c); + RowCursor priorityScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out priorityScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref priorityScope, out priorityScope) == Result.Success) { + value.Priority = new ArrayList>(); + RowCursor tupleScope = null; + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + while (priorityScope.MoveNext(row, tempRef_tupleScope)) { + tupleScope = tempRef_tupleScope.argValue; + TypeArgument innerType = c.TypeArgs[0]; + LayoutIndexedScope innerLayout = innerType.getType().TypeAs(); + + tangible.RefObject tempRef_priorityScope = + new tangible.RefObject(priorityScope); + tangible.OutObject tempOut_tupleScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(innerLayout.ReadScope(row, tempRef_priorityScope, tempOut_tupleScope)); + tupleScope = tempOut_tupleScope.argValue; + priorityScope = tempRef_priorityScope.argValue; + assert Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(tupleScope.clone() + , row); + tangible.RefObject tempRef_tupleScope2 = + new tangible.RefObject(tupleScope); + String item1; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(innerType.getTypeArgs().get(0).getType().TypeAs().ReadSparse(row, + tempRef_tupleScope2, out item1)); + tupleScope = tempRef_tupleScope2.argValue; + + assert Microsoft.Azure.Cosmos.Serialization.HybridRow.RowCursorExtensions.MoveNext(tupleScope.clone() + , row); + tangible.RefObject tempRef_tupleScope3 = + new tangible.RefObject(tupleScope); + long item2; + tangible.OutObject tempOut_item2 = new tangible.OutObject(); + ResultAssert.IsSuccess(innerType.getTypeArgs().get(1).getType().TypeAs().ReadSparse(row, + tempRef_tupleScope3, tempOut_item2)); + item2 = tempOut_item2.argValue; + tupleScope = tempRef_tupleScope3.argValue; + + value.Priority.add(Tuple.Create(item1, item2)); + } + tupleScope = tempRef_tupleScope.argValue; + } + + return value; + } + + private static void WriteSimilarMatch(tangible.RefObject row, tangible.RefObject matchScope + , TypeArgumentList typeArgs, SimilarMatch m) { + Layout matchLayout = row.argValue.getResolver().Resolve(typeArgs.getSchemaId().clone()); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert matchLayout.TryFind("thumbprint", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteFixed(row, matchScope, c, m.Thumbprint)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert matchLayout.TryFind("score", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteFixed(row, matchScope, c, m.Score)); + } + + private void WriteTagged(tangible.RefObject row, tangible.RefObject root, Tagged value) { + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("title", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, root, c, value.Title)); + + if (value.Tags != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.layout.TryFind("tags", out c); + RowCursor tagsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out tagsScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref tagsScope, c.TypeArgs, + out tagsScope)); + for (String item : value.Tags) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(row, ref tagsScope, item)); + assert !tagsScope.MoveNext(row); + } + } + + if (value.Options != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.layout.TryFind("options", out c); + RowCursor optionsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out optionsScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref optionsScope, c.TypeArgs, + out optionsScope)); + for (Integer item : value.Options) { + TypeArgument itemType = c.TypeArgs[0]; + RowCursor nullableScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(itemType.getType().TypeAs().WriteScope(row, ref optionsScope, + itemType.getTypeArgs().clone(), item != null, out nullableScope)); + + if (item != null) { + tangible.RefObject tempRef_nullableScope = new tangible.RefObject(nullableScope); + ResultAssert.IsSuccess(itemType.getTypeArgs().get(0).getType().TypeAs().WriteSparse(row, tempRef_nullableScope, item.intValue())); + nullableScope = tempRef_nullableScope.argValue; + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert !optionsScope.MoveNext(row, ref nullableScope); + } + } + + if (value.Ratings != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.layout.TryFind("ratings", out c); + RowCursor ratingsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out ratingsScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref ratingsScope, c.TypeArgs, + out ratingsScope)); + for (ArrayList item : value.Ratings) { + assert item != null; + TypeArgument innerType = c.TypeArgs[0]; + LayoutTypedArray innerLayout = innerType.getType().TypeAs(); + tangible.RefObject tempRef_ratingsScope = + new tangible.RefObject(ratingsScope); + RowCursor innerScope; + tangible.OutObject tempOut_innerScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(innerLayout.WriteScope(row, tempRef_ratingsScope, + innerType.getTypeArgs().clone(), tempOut_innerScope)); + innerScope = tempOut_innerScope.argValue; + ratingsScope = tempRef_ratingsScope.argValue; + for (double innerItem : item) { + LayoutFloat64 itemLayout = innerType.getTypeArgs().get(0).getType().TypeAs(); + tangible.RefObject tempRef_innerScope = + new tangible.RefObject(innerScope); + ResultAssert.IsSuccess(itemLayout.WriteSparse(row, tempRef_innerScope, innerItem)); + innerScope = tempRef_innerScope.argValue; + assert !innerScope.MoveNext(row); + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert !ratingsScope.MoveNext(row, ref innerScope); + } + } + + if (value.Similars != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.layout.TryFind("similars", out c); + RowCursor similarsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out similarsScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref similarsScope, c.TypeArgs, + out similarsScope)); + for (SimilarMatch item : value.Similars) { + TypeArgument innerType = c.TypeArgs[0]; + LayoutUDT innerLayout = innerType.getType().TypeAs(); + tangible.RefObject tempRef_similarsScope = + new tangible.RefObject(similarsScope); + RowCursor matchScope; + tangible.OutObject tempOut_matchScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(innerLayout.WriteScope(row, tempRef_similarsScope, + innerType.getTypeArgs().clone(), tempOut_matchScope)); + matchScope = tempOut_matchScope.argValue; + similarsScope = tempRef_similarsScope.argValue; + tangible.RefObject tempRef_matchScope = + new tangible.RefObject(matchScope); + TypedArrayUnitTests.WriteSimilarMatch(row, tempRef_matchScope, innerType.getTypeArgs().clone(), item); + matchScope = tempRef_matchScope.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert !similarsScope.MoveNext(row, ref matchScope); + } + } + + if (value.Priority != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.layout.TryFind("priority", out c); + RowCursor priorityScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out priorityScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref priorityScope, c.TypeArgs, + out priorityScope)); + for (Tuple item : value.Priority) { + TypeArgument innerType = c.TypeArgs[0]; + LayoutIndexedScope innerLayout = innerType.getType().TypeAs(); + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(innerLayout.WriteScope(row, ref priorityScope, innerType.getTypeArgs().clone() + , out tupleScope)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(innerType.getTypeArgs().get(0).getType().TypeAs().WriteSparse(row, + ref tupleScope, item.Item1)); + assert tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + ResultAssert.IsSuccess(innerType.getTypeArgs().get(1).getType().TypeAs().WriteSparse(row + , tempRef_tupleScope, item.Item2)); + tupleScope = tempRef_tupleScope.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + assert !priorityScope.MoveNext(row, ref tupleScope); + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test types.")] private sealed class SimilarMatch + private final static class SimilarMatch { + public double Score; + public String Thumbprint; + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof SimilarMatch; + SimilarMatch match = tempVar ? (SimilarMatch)obj : null; + return tempVar && this.equals(match); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + return (this.Thumbprint.hashCode() * 397) ^ (new Double(this.Score)).hashCode(); + } + } + + private boolean equals(SimilarMatch other) { + // ReSharper disable once CompareOfFloatsByEqualityOperator + return this.Thumbprint.equals(other.Thumbprint) && this.Score == other.Score; + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test + // types.")] private sealed class Tagged + private final static class Tagged { + public ArrayList Options; + public ArrayList> Priority; + public ArrayList> Ratings; + public ArrayList Similars; + public ArrayList Tags; + public String Title; + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof Tagged; + Tagged tagged = tempVar ? (Tagged)obj : null; + return tempVar && this.equals(tagged); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + int hashCode = this.Title == null ? null : this.Title.hashCode() != null ? this.Title.hashCode() : 0; + hashCode = (hashCode * 397) ^ (this.Tags == null ? null : this.Tags.hashCode() != null ? + this.Tags.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Options == null ? null : this.Options.hashCode() != null ? + this.Options.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Ratings == null ? null : this.Ratings.hashCode() != null ? this.Ratings.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Similars == null ? null : this.Similars.hashCode() != null ? this.Similars.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Priority == null ? null : this.Priority.hashCode() != null ? this.Priority.hashCode() : 0); + return hashCode; + } + } + + private static boolean NestedSequenceEquals(ArrayList> left, ArrayList> right) { + if (left.size() != right.size()) { + return false; + } + + for (int i = 0; i < left.size(); i++) { + //C# TO JAVA CONVERTER WARNING: Java AbstractList 'equals' is not always identical to LINQ 'SequenceEqual': + //ORIGINAL LINE: if (!left[i].SequenceEqual(right[i])) + if (!left.get(i).equals(right.get(i))) { + return false; + } + } + + return true; + } + + private boolean equals(Tagged other) { + //C# TO JAVA CONVERTER WARNING: Java AbstractList 'equals' is not always identical to LINQ 'SequenceEqual': + //ORIGINAL LINE: return string.Equals(this.Title, other.Title) && (object.ReferenceEquals(this.Tags, other.Tags) || ((this.Tags != null) && (other.Tags != null) && this.Tags.SequenceEqual(other.Tags))) && (object.ReferenceEquals(this.Options, other.Options) || ((this.Options != null) && (other.Options != null) && this.Options.SequenceEqual(other.Options))) && (object.ReferenceEquals(this.Ratings, other.Ratings) || ((this.Ratings != null) && (other.Ratings != null) && Tagged.NestedSequenceEquals(this.Ratings, other.Ratings))) && (object.ReferenceEquals(this.Similars, other.Similars) || ((this.Similars != null) && (other.Similars != null) && this.Similars.SequenceEqual(other.Similars))) && (object.ReferenceEquals(this.Priority, other.Priority) || ((this.Priority != null) && (other.Priority != null) && this.Priority.SequenceEqual(other.Priority))); + return this.Title.equals(other.Title) && (this.Tags == other.Tags || ((this.Tags != null) && (other.Tags != null) && this.Tags.equals(other.Tags))) && (this.Options == other.Options || ((this.Options != null) && (other.Options != null) && this.Options.equals(other.Options))) && (this.Ratings == other.Ratings || ((this.Ratings != null) && (other.Ratings != null) && Tagged.NestedSequenceEquals(this.Ratings, other.Ratings))) && (this.Similars == other.Similars || ((this.Similars != null) && (other.Similars != null) && this.Similars.equals(other.Similars))) && (this.Priority == other.Priority || ((this.Priority != null) && (other.Priority != null) && this.Priority.equals(other.Priority))); + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedMapUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedMapUnitTests.java new file mode 100644 index 0000000..36e5b57 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedMapUnitTests.java @@ -0,0 +1,1572 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.math.BigDecimal; +import java.nio.file.Files; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][DeploymentItem(TypedMapUnitTests.SchemaFile, "TestData")] public sealed class +// TypedMapUnitTests +public final class TypedMapUnitTests { + private static final int InitialRowSize = 2 * 1024 * 1024; + private static final String SchemaFile = "TestData\\MovieSchema.json"; + private Namespace counterSchema; + private Layout layout; + private LayoutResolver resolver; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateMovies() + public void CreateMovies() { + RowBuffer row = new RowBuffer(TypedMapUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + + // ReSharper disable StringLiteralTypo + Movie t1 = new Movie(); + t1.Cast = new HashMap(Map.ofEntries(Map.entry("Mark", "Luke"), Map.entry("Harrison", "Han"), + Map.entry("Carrie", "Leia"))); + t1.Stats = new HashMap(Map.ofEntries(Map.entry(UUID.fromString("{4674962B-CE11-4916-81C5" + + "-0421EE36F168}"), 11000000.00), Map.entry(UUID.fromString("{7499C40E-7077-45C1-AE5F-3E384966B3B9}"), + 1554475.00))); + t1.Related = new HashMap>(Map.ofEntries(Map.entry("Mark", new HashMap(Map.ofEntries(Map.entry(103359, "Joker"), Map.entry(131646, "Merlin")))), Map.entry("Harrison", + new HashMap(Map.ofEntries(Map.entry(0082971, "Indy"), Map.entry(83658, "Deckard")))))); + Earnings tempVar = new Earnings(); + tempVar.Domestic = new BigDecimal(307263857); + tempVar.Worldwide = new BigDecimal(100000); + Earnings tempVar2 = new Earnings(); + tempVar2.Domestic = new BigDecimal(15476285); + tempVar2.Worldwide = new BigDecimal(200000); + Earnings tempVar3 = new Earnings(); + tempVar3.Domestic = new BigDecimal(138257865); + tempVar3.Worldwide = new BigDecimal(300000); + t1.Revenue = new HashMap(Map.ofEntries(Map.entry(LocalDateTime.parse("05/25/1977"), + tempVar), Map.entry(LocalDateTime.parse("08/13/1982"), tempVar2), + Map.entry(LocalDateTime.parse("01/31/1997"), tempVar3))); + + // ReSharper restore StringLiteralTypo + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteMovie(tempRef_row, RowCursor.Create(tempRef_row2, out _), t1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Movie t2 = this.ReadMovie(tempRef_row3, RowCursor.Create(tempRef_row4, out _)); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + assert t1 == t2; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void FindAndDelete() + public void FindAndDelete() { + RowBuffer row = new RowBuffer(TypedMapUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row); + row = tempRef_row.argValue; + + ArrayList expected = new ArrayList(Arrays.asList("Mark", "Harrison", "Carrie")); + + for (java.lang.Iterable permutation : expected.Permute()) { + Movie t1 = new Movie(); + t1.Cast = new HashMap(Map.ofEntries(Map.entry("Mark", "Luke"), Map.entry("Harrison", "Han" + ), Map.entry("Carrie", "Leia"))); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + this.WriteMovie(tempRef_row2, root.Clone(out _), t1); + row = tempRef_row2.argValue; + + // Attempt to find each item in turn and then delete it. + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.layout.TryFind("cast", out c); + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + RowCursor mapScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.Clone(out mapScope).Find(tempRef_row3, c.Path); + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row4, ref mapScope, out mapScope)); + row = tempRef_row4.argValue; + for (String key : permutation) { + KeyValuePair pair = new KeyValuePair(key, "map lookup matches only on" + + " key"); + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row5, Utf8String.Empty); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row6, tempRef_tempCursor, c.TypeArgs, + pair)); + tempCursor = tempRef_tempCursor.argValue; + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + RowCursor findScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().Find(tempRef_row7, ref mapScope, ref tempCursor, + out findScope)); + row = tempRef_row7.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + TypeArgument tupleType = c.TypeAs().FieldType(ref mapScope); + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + tangible.RefObject tempRef_findScope = + new tangible.RefObject(findScope); + ResultAssert.IsSuccess(tupleType.TypeAs().DeleteScope(tempRef_row8, + tempRef_findScope)); + findScope = tempRef_findScope.argValue; + row = tempRef_row8.argValue; + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void FindInMap() + public void FindInMap() { + RowBuffer row = new RowBuffer(TypedMapUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row); + row = tempRef_row.argValue; + + Movie t1 = new Movie(); + t1.Cast = new HashMap(Map.ofEntries(Map.entry("Mark", "Luke"), Map.entry("Harrison", "Han"), + Map.entry("Carrie", "Leia"))); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor rc1 = RowCursor.Create(tempRef_row2); + row = tempRef_row2.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_rc1 = + new tangible.RefObject(rc1); + this.WriteMovie(tempRef_row3, tempRef_rc1, t1); + rc1 = tempRef_rc1.argValue; + row = tempRef_row3.argValue; + + // Attempt to find each item in turn. + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("cast", out c); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor mapScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out mapScope).Find(tempRef_row4, c.Path); + row = tempRef_row4.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row5, ref mapScope, out mapScope)); + row = tempRef_row5.argValue; + for (String key : t1.Cast.keySet()) { + KeyValuePair pair = new KeyValuePair(key, "map lookup matches only on key"); + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.Clone(out tempCursor).Find(tempRef_row6, Utf8String.Empty); + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row7, tempRef_tempCursor, c.TypeArgs, pair)); + tempCursor = tempRef_tempCursor.argValue; + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + RowCursor findScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().Find(tempRef_row8, ref mapScope, ref tempCursor, + out findScope)); + row = tempRef_row8.argValue; + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + tangible.RefObject tempRef_findScope = + new tangible.RefObject(findScope); + KeyValuePair foundPair; + tangible.OutObject> tempOut_foundPair = + new tangible.OutObject>(); + ResultAssert.IsSuccess(TypedMapUnitTests.ReadKeyValue(tempRef_row9, tempRef_findScope, c.TypeArgs, + tempOut_foundPair)); + foundPair = tempOut_foundPair.argValue; + findScope = tempRef_findScope.argValue; + row = tempRef_row9.argValue; + Assert.AreEqual(key, foundPair.Key, String.format("Failed to find t1.Cast[%1$s]", key)); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public void ParseNamespaceExample() { + String json = Files.readString(TypedMapUnitTests.SchemaFile); + this.counterSchema = Namespace.Parse(json); + this.resolver = new LayoutResolverNamespace(this.counterSchema); + this.layout = this.resolver.Resolve(tangible.ListHelper.find(this.counterSchema.getSchemas(), + x -> x.Name.equals("Movie")).SchemaId); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void PreventUniquenessViolations() + public void PreventUniquenessViolations() { + RowBuffer row = new RowBuffer(TypedMapUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row); + row = tempRef_row.argValue; + + Movie t1 = new Movie(); + t1.Cast = new HashMap(Map.ofEntries(Map.entry("Mark", "Luke"))); + t1.Stats = new HashMap(Map.ofEntries(Map.entry(UUID.fromString("{4674962B-CE11-4916-81C5" + + "-0421EE36F168}"), 11000000.00))); + t1.Related = new HashMap>(Map.ofEntries(Map.entry("Mark", new HashMap(Map.ofEntries(Map.entry(103359, "Joker")))))); + Earnings tempVar = new Earnings(); + tempVar.Domestic = new BigDecimal(307263857); + tempVar.Worldwide = new BigDecimal(100000); + t1.Revenue = new HashMap(Map.ofEntries(Map.entry(LocalDateTime.parse("05/25/1977"), + tempVar))); + + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor rc1 = RowCursor.Create(tempRef_row2); + row = tempRef_row2.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_rc1 = + new tangible.RefObject(rc1); + this.WriteMovie(tempRef_row3, tempRef_rc1, t1); + rc1 = tempRef_rc1.argValue; + row = tempRef_row3.argValue; + + // Attempt to insert duplicate items in existing sets. + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("cast", out c); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor mapScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out mapScope).Find(tempRef_row4, c.Path); + row = tempRef_row4.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row5, ref mapScope, out mapScope)); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row6, Utf8String.Empty); + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row7, tempRef_tempCursor, c.TypeArgs, + KeyValuePair.Create("Mark", "Luke"))); + tempCursor = tempRef_tempCursor.argValue; + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.Exists(c.TypeAs().MoveField(tempRef_row8, ref mapScope, ref tempCursor, + UpdateOptions.Insert)); + row = tempRef_row8.argValue; + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row9, Utf8String.Empty); + row = tempRef_row9.argValue; + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor2 = + new tangible.RefObject(tempCursor); + KeyValuePair _; + tangible.OutObject> tempOut__ = new tangible.OutObject>(); + ResultAssert.NotFound(TypedMapUnitTests.ReadKeyValue(tempRef_row10, tempRef_tempCursor2, c.TypeArgs, + tempOut__)); + _ = tempOut__.argValue; + tempCursor = tempRef_tempCursor2.argValue; + row = tempRef_row10.argValue; + tangible.RefObject tempRef_row11 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row11, Utf8String.Empty); + row = tempRef_row11.argValue; + tangible.RefObject tempRef_row12 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor3 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row12, tempRef_tempCursor3, c.TypeArgs, + KeyValuePair.Create("Mark", "Joker"))); + tempCursor = tempRef_tempCursor3.argValue; + row = tempRef_row12.argValue; + tangible.RefObject tempRef_row13 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.Exists(c.TypeAs().MoveField(tempRef_row13, ref mapScope, ref tempCursor, + UpdateOptions.Insert)); + row = tempRef_row13.argValue; + tangible.RefObject tempRef_row14 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row14, Utf8String.Empty); + row = tempRef_row14.argValue; + tangible.RefObject tempRef_row15 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor4 = + new tangible.RefObject(tempCursor); + KeyValuePair _; + tangible.OutObject> tempOut__2 = + new tangible.OutObject>(); + ResultAssert.NotFound(TypedMapUnitTests.ReadKeyValue(tempRef_row15, tempRef_tempCursor4, c.TypeArgs, + tempOut__2)); + _ = tempOut__2.argValue; + tempCursor = tempRef_tempCursor4.argValue; + row = tempRef_row15.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("stats", out c); + tangible.RefObject tempRef_row16 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out mapScope).Find(tempRef_row16, c.Path); + row = tempRef_row16.argValue; + tangible.RefObject tempRef_row17 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row17, ref mapScope, out mapScope)); + row = tempRef_row17.argValue; + KeyValuePair pair = KeyValuePair.Create(UUID.fromString("{4674962B-CE11-4916-81C5-0421EE36F168" + + "}"), 11000000.00); + tangible.RefObject tempRef_row18 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row18, Utf8String.Empty); + row = tempRef_row18.argValue; + tangible.RefObject tempRef_row19 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor5 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row19, tempRef_tempCursor5, c.TypeArgs, pair)); + tempCursor = tempRef_tempCursor5.argValue; + row = tempRef_row19.argValue; + tangible.RefObject tempRef_row20 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.Exists(c.TypeAs().MoveField(tempRef_row20, ref mapScope, ref tempCursor, + UpdateOptions.Insert)); + row = tempRef_row20.argValue; + tangible.RefObject tempRef_row21 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row21, Utf8String.Empty); + row = tempRef_row21.argValue; + tangible.RefObject tempRef_row22 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor6 = + new tangible.RefObject(tempCursor); + tangible.OutObject> tempOut_pair = new tangible.OutObject>(); + ResultAssert.NotFound(TypedMapUnitTests.ReadKeyValue(tempRef_row22, tempRef_tempCursor6, c.TypeArgs, + tempOut_pair)); + pair = tempOut_pair.argValue; + tempCursor = tempRef_tempCursor6.argValue; + row = tempRef_row22.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void PreventUpdatesInNonUpdatableScope() + public void PreventUpdatesInNonUpdatableScope() { + RowBuffer row = new RowBuffer(TypedMapUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row); + row = tempRef_row.argValue; + + // Write a map and then try to write directly into it. + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("cast", out c); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor mapScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out mapScope).Find(tempRef_row2, c.Path); + row = tempRef_row2.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(tempRef_row3, ref mapScope, c.TypeArgs, + out mapScope)); + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + tangible.RefObject tempRef_mapScope = + new tangible.RefObject(mapScope); + ResultAssert.InsufficientPermissions(TypedMapUnitTests.WriteKeyValue(tempRef_row4, tempRef_mapScope, + c.TypeArgs, KeyValuePair.Create("Mark", "Joker"))); + mapScope = tempRef_mapScope.argValue; + row = tempRef_row4.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row5, "cast.0"); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row6, tempRef_tempCursor, c.TypeArgs, + KeyValuePair.Create("Mark", "Joker"))); + tempCursor = tempRef_tempCursor.argValue; + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().MoveField(tempRef_row7, ref mapScope, ref tempCursor)); + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row8, "cast.0"); + row = tempRef_row8.argValue; + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor2 = + new tangible.RefObject(tempCursor); + KeyValuePair _; + tangible.OutObject> tempOut__ = new tangible.OutObject>(); + ResultAssert.NotFound(TypedMapUnitTests.ReadKeyValue(tempRef_row9, tempRef_tempCursor2, c.TypeArgs, tempOut__)); + _ = tempOut__.argValue; + tempCursor = tempRef_tempCursor2.argValue; + row = tempRef_row9.argValue; + + // Write a map of maps, successfully insert an empty map into it, and then try to write directly to the inner + // map. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("related", out c); + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out mapScope).Find(tempRef_row10, c.Path); + row = tempRef_row10.argValue; + tangible.RefObject tempRef_row11 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(tempRef_row11, ref mapScope, c.TypeArgs, + out mapScope)); + row = tempRef_row11.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + LayoutIndexedScope tupleLayout = + c.TypeAs().FieldType(ref mapScope).TypeAs(); + tangible.RefObject tempRef_row12 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row12, "related.0"); + row = tempRef_row12.argValue; + tangible.RefObject tempRef_row13 = + new tangible.RefObject(row); + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(tupleLayout.WriteScope(tempRef_row13, ref tempCursor, c.TypeArgs, out tupleScope)); + row = tempRef_row13.argValue; + tangible.RefObject tempRef_row14 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row14, ref tupleScope, + "Mark")); + row = tempRef_row14.argValue; + tangible.RefObject tempRef_row15 = + new tangible.RefObject(row); + assert tupleScope.MoveNext(tempRef_row15); + row = tempRef_row15.argValue; + TypeArgument valueType = c.TypeArgs[1]; + LayoutUniqueScope valueLayout = valueType.getType().TypeAs(); + tangible.RefObject tempRef_row16 = + new tangible.RefObject(row); + RowCursor innerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(valueLayout.WriteScope(tempRef_row16, ref tupleScope, valueType.getTypeArgs().clone(), + out innerScope)); + row = tempRef_row16.argValue; + tangible.RefObject tempRef_row17 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().MoveField(tempRef_row17, ref mapScope, ref tempCursor)); + row = tempRef_row17.argValue; + tangible.RefObject tempRef_row18 = + new tangible.RefObject(row); + assert mapScope.MoveNext(tempRef_row18); + row = tempRef_row18.argValue; + tangible.RefObject tempRef_row19 = + new tangible.RefObject(row); + tangible.RefObject tempRef_mapScope2 = + new tangible.RefObject(mapScope); + tangible.OutObject tempOut_tupleScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(tupleLayout.ReadScope(tempRef_row19, tempRef_mapScope2, tempOut_tupleScope)); + tupleScope = tempOut_tupleScope.argValue; + mapScope = tempRef_mapScope2.argValue; + row = tempRef_row19.argValue; + tangible.RefObject tempRef_row20 = + new tangible.RefObject(row); + assert tupleScope.MoveNext(tempRef_row20); + row = tempRef_row20.argValue; + + // Skip key. + tangible.RefObject tempRef_row21 = + new tangible.RefObject(row); + assert tupleScope.MoveNext(tempRef_row21); + row = tempRef_row21.argValue; + tangible.RefObject tempRef_row22 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + tangible.OutObject tempOut_innerScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(valueLayout.ReadScope(tempRef_row22, tempRef_tupleScope, tempOut_innerScope)); + innerScope = tempOut_innerScope.argValue; + tupleScope = tempRef_tupleScope.argValue; + row = tempRef_row22.argValue; + TypeArgument itemType = valueType.getTypeArgs().get(0).clone(); + tangible.RefObject tempRef_row23 = + new tangible.RefObject(row); + assert !innerScope.MoveNext(tempRef_row23); + row = tempRef_row23.argValue; + tangible.RefObject tempRef_row24 = + new tangible.RefObject(row); + tangible.RefObject tempRef_innerScope = + new tangible.RefObject(innerScope); + ResultAssert.InsufficientPermissions(itemType.getType().TypeAs().WriteSparse(tempRef_row24, + tempRef_innerScope, 1)); + innerScope = tempRef_innerScope.argValue; + row = tempRef_row24.argValue; + tangible.RefObject tempRef_row25 = + new tangible.RefObject(row); + tangible.RefObject tempRef_innerScope2 = + new tangible.RefObject(innerScope); + ResultAssert.InsufficientPermissions(itemType.getType().TypeAs().DeleteSparse(tempRef_row25, + tempRef_innerScope2)); + innerScope = tempRef_innerScope2.argValue; + row = tempRef_row25.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void UpdateInMap() + public void UpdateInMap() { + RowBuffer row = new RowBuffer(TypedMapUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row); + row = tempRef_row.argValue; + + ArrayList expected = new ArrayList(Arrays.asList("Mark", "Harrison", "Carrie")); + + for (java.lang.Iterable permutation : expected.Permute()) { + Movie t1 = new Movie(); + t1.Cast = new HashMap(Map.ofEntries(Map.entry("Mark", "Luke"), Map.entry("Harrison", "Han" + ), Map.entry("Carrie", "Leia"))); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + this.WriteMovie(tempRef_row2, root.Clone(out _), t1); + row = tempRef_row2.argValue; + + // Attempt to find each item in turn and then delete it. + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.layout.TryFind("cast", out c); + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + RowCursor mapScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.Clone(out mapScope).Find(tempRef_row3, c.Path); + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row4, ref mapScope, out mapScope)); + row = tempRef_row4.argValue; + for (String key : permutation) { + // Verify it is already there. + KeyValuePair pair = new KeyValuePair(key, "map lookup matches only on" + + " key"); + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row5, Utf8String.Empty); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row6, tempRef_tempCursor, c.TypeArgs, + pair)); + tempCursor = tempRef_tempCursor.argValue; + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + RowCursor findScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().Find(tempRef_row7, ref mapScope, ref tempCursor, + out findScope)); + row = tempRef_row7.argValue; + + // Insert it again with update. + KeyValuePair updatePair = new KeyValuePair(key, "update value"); + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row8, Utf8String.Empty); + row = tempRef_row8.argValue; + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor2 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row9, tempRef_tempCursor2, c.TypeArgs, + updatePair)); + tempCursor = tempRef_tempCursor2.argValue; + row = tempRef_row9.argValue; + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().MoveField(tempRef_row10, ref mapScope, + ref tempCursor, UpdateOptions.Update)); + row = tempRef_row10.argValue; + + // Verify that the value was updated. + tangible.RefObject tempRef_row11 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row11, Utf8String.Empty); + row = tempRef_row11.argValue; + tangible.RefObject tempRef_row12 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor3 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row12, tempRef_tempCursor3, c.TypeArgs + , pair)); + tempCursor = tempRef_tempCursor3.argValue; + row = tempRef_row12.argValue; + tangible.RefObject tempRef_row13 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().Find(tempRef_row13, ref mapScope, ref tempCursor + , out findScope)); + row = tempRef_row13.argValue; + tangible.RefObject tempRef_row14 = + new tangible.RefObject(row); + tangible.RefObject tempRef_findScope = + new tangible.RefObject(findScope); + KeyValuePair foundPair; + tangible.OutObject> tempOut_foundPair = + new tangible.OutObject>(); + ResultAssert.IsSuccess(TypedMapUnitTests.ReadKeyValue(tempRef_row14, tempRef_findScope, c.TypeArgs, + tempOut_foundPair)); + foundPair = tempOut_foundPair.argValue; + findScope = tempRef_findScope.argValue; + row = tempRef_row14.argValue; + assert key == foundPair.Key; + assert updatePair.Value == foundPair.Value; + + // Insert it again with upsert. + updatePair = new KeyValuePair(key, "upsert value"); + tangible.RefObject tempRef_row15 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row15, Utf8String.Empty); + row = tempRef_row15.argValue; + tangible.RefObject tempRef_row16 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor4 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row16, tempRef_tempCursor4, c.TypeArgs + , updatePair)); + tempCursor = tempRef_tempCursor4.argValue; + row = tempRef_row16.argValue; + + // ReSharper disable once RedundantArgumentDefaultValue + tangible.RefObject tempRef_row17 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().MoveField(tempRef_row17, ref mapScope, + ref tempCursor, UpdateOptions.Upsert)); + row = tempRef_row17.argValue; + + // Verify that the value was upserted. + tangible.RefObject tempRef_row18 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row18, Utf8String.Empty); + row = tempRef_row18.argValue; + tangible.RefObject tempRef_row19 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor5 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row19, tempRef_tempCursor5, c.TypeArgs + , pair)); + tempCursor = tempRef_tempCursor5.argValue; + row = tempRef_row19.argValue; + tangible.RefObject tempRef_row20 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().Find(tempRef_row20, ref mapScope, ref tempCursor + , out findScope)); + row = tempRef_row20.argValue; + tangible.RefObject tempRef_row21 = + new tangible.RefObject(row); + tangible.RefObject tempRef_findScope2 = + new tangible.RefObject(findScope); + tangible.OutObject> tempOut_foundPair2 = + new tangible.OutObject>(); + ResultAssert.IsSuccess(TypedMapUnitTests.ReadKeyValue(tempRef_row21, tempRef_findScope2, c.TypeArgs, + tempOut_foundPair2)); + foundPair = tempOut_foundPair2.argValue; + findScope = tempRef_findScope2.argValue; + row = tempRef_row21.argValue; + assert key == foundPair.Key; + assert updatePair.Value == foundPair.Value; + + // Insert it again with insert (fail: exists). + updatePair = new KeyValuePair(key, "insert value"); + tangible.RefObject tempRef_row22 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row22, Utf8String.Empty); + row = tempRef_row22.argValue; + tangible.RefObject tempRef_row23 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor6 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row23, tempRef_tempCursor6, c.TypeArgs + , updatePair)); + tempCursor = tempRef_tempCursor6.argValue; + row = tempRef_row23.argValue; + tangible.RefObject tempRef_row24 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.Exists(c.TypeAs().MoveField(tempRef_row24, ref mapScope, + ref tempCursor, UpdateOptions.Insert)); + row = tempRef_row24.argValue; + + // Insert it again with insert at (fail: disallowed). + updatePair = new KeyValuePair(key, "insertAt value"); + tangible.RefObject tempRef_row25 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row25, Utf8String.Empty); + row = tempRef_row25.argValue; + tangible.RefObject tempRef_row26 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor7 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(tempRef_row26, tempRef_tempCursor7, c.TypeArgs + , updatePair)); + tempCursor = tempRef_tempCursor7.argValue; + row = tempRef_row26.argValue; + tangible.RefObject tempRef_row27 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.TypeConstraint(c.TypeAs().MoveField(tempRef_row27, ref mapScope, + ref tempCursor, UpdateOptions.InsertAt)); + row = tempRef_row27.argValue; + } + } + } + + private static Earnings ReadEarnings(tangible.RefObject row, tangible.RefObject udtScope) { + Layout udt = udtScope.argValue.getLayout(); + Earnings m = new Earnings(); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert udt.TryFind("domestic", out c); + tangible.OutObject tempOut_Domestic = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadFixed(row, udtScope, c, tempOut_Domestic)); + m.Domestic = tempOut_Domestic.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert udt.TryFind("worldwide", out c); + tangible.OutObject tempOut_Worldwide = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadFixed(row, udtScope, c, tempOut_Worldwide)); + m.Worldwide = tempOut_Worldwide.argValue; + return m; + } + + private static Result ReadKeyValue(tangible.RefObject row, + tangible.RefObject scope, TypeArgumentList typeArgs, + tangible.OutObject> pair) { + pair.argValue = null; + LayoutIndexedScope tupleLayout = LayoutType.TypedTuple; + RowCursor tupleScope; + tangible.OutObject tempOut_tupleScope = + new tangible.OutObject(); + Result r = tupleLayout.ReadScope(row, scope, tempOut_tupleScope); + tupleScope = tempOut_tupleScope.argValue; + if (r != Result.Success) { + return r; + } + + tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + TKey key; + tangible.OutObject tempOut_key = new tangible.OutObject(); + r = typeArgs.get(0).getType().>TypeAs().ReadSparse(row, tempRef_tupleScope, tempOut_key); + key = tempOut_key.argValue; + tupleScope = tempRef_tupleScope.argValue; + if (r != Result.Success) { + return r; + } + + tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope2 = + new tangible.RefObject(tupleScope); + TValue value; + tangible.OutObject tempOut_value = new tangible.OutObject(); + r = typeArgs.get(1).getType().>TypeAs().ReadSparse(row, tempRef_tupleScope2, tempOut_value); + value = tempOut_value.argValue; + tupleScope = tempRef_tupleScope2.argValue; + if (r != Result.Success) { + return r; + } + + pair.argValue = new KeyValuePair(key, value); + return Result.Success; + } + + private Movie ReadMovie(tangible.RefObject row, tangible.RefObject root) { + Movie value = new Movie(); + + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("cast", out c); + RowCursor castScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out castScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref castScope, out castScope) == Result.Success) { + value.Cast = new HashMap(); + while (castScope.MoveNext(row)) { + tangible.RefObject tempRef_castScope = + new tangible.RefObject(castScope); + KeyValuePair item; + tangible.OutObject> tempOut_item = + new tangible.OutObject>(); + ResultAssert.IsSuccess(TypedMapUnitTests.ReadKeyValue(row, tempRef_castScope, c.TypeArgs, + tempOut_item)); + item = tempOut_item.argValue; + castScope = tempRef_castScope.argValue; + value.Cast.put(item.Key, item.Value); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("stats", out c); + RowCursor statsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out statsScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref statsScope, out statsScope) == Result.Success) { + value.Stats = new HashMap(); + while (statsScope.MoveNext(row)) { + tangible.RefObject tempRef_statsScope = + new tangible.RefObject(statsScope); + KeyValuePair item; + tangible.OutObject> tempOut_item2 = + new tangible.OutObject>(); + ResultAssert.IsSuccess(TypedMapUnitTests.ReadKeyValue(row, tempRef_statsScope, c.TypeArgs, + tempOut_item2)); + item = tempOut_item2.argValue; + statsScope = tempRef_statsScope.argValue; + value.Stats.put(item.Key, item.Value); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("related", out c); + RowCursor relatedScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out relatedScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref relatedScope, out relatedScope) == Result.Success) { + value.Related = new HashMap>(); + TypeArgument keyType = c.TypeArgs[0]; + TypeArgument valueType = c.TypeArgs[1]; + LayoutUtf8 keyLayout = keyType.getType().TypeAs(); + LayoutUniqueScope valueLayout = valueType.getType().TypeAs(); + while (relatedScope.MoveNext(row)) { + LayoutIndexedScope tupleLayout = LayoutType.TypedTuple; + tangible.RefObject tempRef_relatedScope = + new tangible.RefObject(relatedScope); + RowCursor tupleScope; + tangible.OutObject tempOut_tupleScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(tupleLayout.ReadScope(row, tempRef_relatedScope, tempOut_tupleScope)); + tupleScope = tempOut_tupleScope.argValue; + relatedScope = tempRef_relatedScope.argValue; + assert tupleScope.MoveNext(row); + String itemKey; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(keyLayout.ReadSparse(row, ref tupleScope, out itemKey)); + assert tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + RowCursor itemValueScope; + tangible.OutObject tempOut_itemValueScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(valueLayout.ReadScope(row, tempRef_tupleScope, tempOut_itemValueScope)); + itemValueScope = tempOut_itemValueScope.argValue; + tupleScope = tempRef_tupleScope.argValue; + HashMap itemValue = new HashMap(); + while (itemValueScope.MoveNext(row)) { + tangible.RefObject tempRef_itemValueScope = new tangible.RefObject(itemValueScope); + KeyValuePair innerItem; + tangible.OutObject> tempOut_innerItem = + new tangible.OutObject>(); + ResultAssert.IsSuccess(TypedMapUnitTests.ReadKeyValue(row, tempRef_itemValueScope, + valueType.getTypeArgs().clone(), tempOut_innerItem)); + innerItem = tempOut_innerItem.argValue; + itemValueScope = tempRef_itemValueScope.argValue; + itemValue.put(innerItem.Key, innerItem.Value); + } + + value.Related.put(itemKey, itemValue); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("revenue", out c); + RowCursor revenueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out revenueScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref revenueScope, out revenueScope) == Result.Success) { + value.Revenue = new HashMap(); + TypeArgument keyType = c.TypeArgs[0]; + TypeArgument valueType = c.TypeArgs[1]; + LayoutDateTime keyLayout = keyType.getType().TypeAs(); + LayoutUDT valueLayout = valueType.getType().TypeAs(); + while (revenueScope.MoveNext(row)) { + LayoutIndexedScope tupleLayout = LayoutType.TypedTuple; + tangible.RefObject tempRef_revenueScope = + new tangible.RefObject(revenueScope); + RowCursor tupleScope; + tangible.OutObject tempOut_tupleScope2 = + new tangible.OutObject(); + ResultAssert.IsSuccess(tupleLayout.ReadScope(row, tempRef_revenueScope, tempOut_tupleScope2)); + tupleScope = tempOut_tupleScope2.argValue; + revenueScope = tempRef_revenueScope.argValue; + assert tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope2 = new tangible.RefObject(tupleScope); + java.time.LocalDateTime itemKey; + tangible.OutObject tempOut_itemKey = new tangible.OutObject(); + ResultAssert.IsSuccess(keyLayout.ReadSparse(row, tempRef_tupleScope2, tempOut_itemKey)); + itemKey = tempOut_itemKey.argValue; + tupleScope = tempRef_tupleScope2.argValue; + assert tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope3 = new tangible.RefObject(tupleScope); + RowCursor itemValueScope; + tangible.OutObject tempOut_itemValueScope2 = new tangible.OutObject(); + ResultAssert.IsSuccess(valueLayout.ReadScope(row, tempRef_tupleScope3, tempOut_itemValueScope2)); + itemValueScope = tempOut_itemValueScope2.argValue; + tupleScope = tempRef_tupleScope3.argValue; + tangible.RefObject tempRef_itemValueScope2 = new tangible.RefObject(itemValueScope); + Earnings itemValue = TypedMapUnitTests.ReadEarnings(row, tempRef_itemValueScope2); + itemValueScope = tempRef_itemValueScope2.argValue; + + value.Revenue.put(itemKey, itemValue); + } + } + + return value; + } + + private static void WriteEarnings(tangible.RefObject row, tangible.RefObject udtScope, TypeArgumentList typeArgs, Earnings m) { + Layout udt = row.argValue.getResolver().Resolve(typeArgs.getSchemaId().clone()); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert udt.TryFind("domestic", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteFixed(row, udtScope, c, m.Domestic)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert udt.TryFind("worldwide", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteFixed(row, udtScope, c, m.Worldwide)); + } + + private static Result WriteKeyValue(tangible.RefObject row, + tangible.RefObject scope, TypeArgumentList typeArgs, KeyValuePair pair) { + LayoutIndexedScope tupleLayout = LayoutType.TypedTuple; + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Result r = tupleLayout.WriteScope(row, scope, typeArgs.clone(), out tupleScope); + if (r != Result.Success) { + return r; + } + + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + r = typeArgs.get(0).getType().>TypeAs().WriteSparse(row, tempRef_tupleScope, pair.Key); + tupleScope = tempRef_tupleScope.argValue; + if (r != Result.Success) { + return r; + } + + tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope2 = + new tangible.RefObject(tupleScope); + r = typeArgs.get(1).getType().>TypeAs().WriteSparse(row, tempRef_tupleScope2, pair.Value); + tupleScope = tempRef_tupleScope2.argValue; + return r; + } + + private void WriteMovie(tangible.RefObject row, tangible.RefObject root, Movie value) { + LayoutColumn c; + + if (value.Cast != null) { + tangible.OutObject tempOut_c = + new tangible.OutObject(); + assert this.layout.TryFind("cast", tempOut_c); + c = tempOut_c.argValue; + RowCursor castScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out castScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref castScope, + c.getTypeArgs().clone(), out castScope)); + for (KeyValuePair item : value.Cast) { + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(row, tempRef_tempCursor, + c.getTypeArgs().clone(), item)); + tempCursor = tempRef_tempCursor.argValue; + tangible.RefObject tempRef_castScope = + new tangible.RefObject(castScope); + tangible.RefObject tempRef_tempCursor2 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_castScope, + tempRef_tempCursor2)); + tempCursor = tempRef_tempCursor2.argValue; + castScope = tempRef_castScope.argValue; + } + } + + if (value.Stats != null) { + tangible.OutObject tempOut_c2 = + new tangible.OutObject(); + assert this.layout.TryFind("stats", tempOut_c2); + c = tempOut_c2.argValue; + RowCursor statsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out statsScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref statsScope, + c.getTypeArgs().clone(), out statsScope)); + for (KeyValuePair item : value.Stats) { + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + tangible.RefObject tempRef_tempCursor3 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(row, tempRef_tempCursor3, + c.getTypeArgs().clone(), item)); + tempCursor = tempRef_tempCursor3.argValue; + tangible.RefObject tempRef_statsScope = + new tangible.RefObject(statsScope); + tangible.RefObject tempRef_tempCursor4 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_statsScope, + tempRef_tempCursor4)); + tempCursor = tempRef_tempCursor4.argValue; + statsScope = tempRef_statsScope.argValue; + } + } + + if (value.Related != null) { + tangible.OutObject tempOut_c3 = + new tangible.OutObject(); + assert this.layout.TryFind("related", tempOut_c3); + c = tempOut_c3.argValue; + RowCursor relatedScoped; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out relatedScoped).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref relatedScoped, + c.getTypeArgs().clone(), out relatedScoped)); + for (KeyValuePair> item : value.Related) { + assert item.Value != null; + + LayoutIndexedScope tupleLayout = LayoutType.TypedTuple; + RowCursor tempCursor1; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor1).Find(row, "related.0"); + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(tupleLayout.WriteScope(row, ref tempCursor1, c.getTypeArgs().clone(), + out tupleScope)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.getTypeArgs().get(0).getType().TypeAs().WriteSparse(row, + ref tupleScope, item.Key)); + assert tupleScope.MoveNext(row); + TypeArgument valueType = c.getTypeArgs().get(1).clone(); + LayoutUniqueScope valueLayout = valueType.getType().TypeAs(); + RowCursor innerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(valueLayout.WriteScope(row, ref tupleScope, valueType.getTypeArgs().clone(), + out innerScope)); + for (KeyValuePair innerItem : item.Value) { + RowCursor tempCursor2; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword + // - these cannot be converted using the 'OutObject' helper class unless the method is within the + // code being modified: + root.argValue.Clone(out tempCursor2).Find(row, "related.0.0"); + tangible.RefObject tempRef_tempCursor2 + = new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(TypedMapUnitTests.WriteKeyValue(row, tempRef_tempCursor2, + valueType.getTypeArgs().clone(), innerItem)); + tempCursor2 = tempRef_tempCursor2.argValue; + tangible.RefObject tempRef_innerScope = + new tangible.RefObject(innerScope); + tangible.RefObject tempRef_tempCursor22 = new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(valueLayout.MoveField(row, tempRef_innerScope, tempRef_tempCursor22)); + tempCursor2 = tempRef_tempCursor22.argValue; + innerScope = tempRef_innerScope.argValue; + } + + tangible.RefObject tempRef_relatedScoped = + new tangible.RefObject(relatedScoped); + tangible.RefObject tempRef_tempCursor1 = + new tangible.RefObject(tempCursor1); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_relatedScoped, + tempRef_tempCursor1)); + tempCursor1 = tempRef_tempCursor1.argValue; + relatedScoped = tempRef_relatedScoped.argValue; + } + } + + if (value.Revenue != null) { + tangible.OutObject tempOut_c4 = + new tangible.OutObject(); + assert this.layout.TryFind("revenue", tempOut_c4); + c = tempOut_c4.argValue; + RowCursor revenueScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out revenueScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref revenueScope, + c.getTypeArgs().clone(), out revenueScope)); + for (KeyValuePair item : value.Revenue) { + assert item.Value != null; + + LayoutIndexedScope tupleLayout = LayoutType.TypedTuple; + RowCursor tempCursor1; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor1).Find(row, "revenue.0"); + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(tupleLayout.WriteScope(row, ref tempCursor1, c.getTypeArgs().clone(), + out tupleScope)); + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + ResultAssert.IsSuccess(c.getTypeArgs().get(0).getType().TypeAs().WriteSparse(row, + tempRef_tupleScope, item.Key)); + tupleScope = tempRef_tupleScope.argValue; + assert tupleScope.MoveNext(row); + TypeArgument valueType = c.getTypeArgs().get(1).clone(); + LayoutUDT valueLayout = valueType.getType().TypeAs(); + tangible.RefObject tempRef_tupleScope2 = + new tangible.RefObject(tupleScope); + RowCursor itemScope; + tangible.OutObject tempOut_itemScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(valueLayout.WriteScope(row, tempRef_tupleScope2, + valueType.getTypeArgs().clone(), tempOut_itemScope)); + itemScope = tempOut_itemScope.argValue; + tupleScope = tempRef_tupleScope2.argValue; + tangible.RefObject tempRef_itemScope = + new tangible.RefObject(itemScope); + TypedMapUnitTests.WriteEarnings(row, tempRef_itemScope, valueType.getTypeArgs().clone(), item.Value); + itemScope = tempRef_itemScope.argValue; + + tangible.RefObject tempRef_revenueScope = + new tangible.RefObject(revenueScope); + tangible.RefObject tempRef_tempCursor12 = + new tangible.RefObject(tempCursor1); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_revenueScope, + tempRef_tempCursor12)); + tempCursor1 = tempRef_tempCursor12.argValue; + revenueScope = tempRef_revenueScope.argValue; + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test types.")] private sealed class Earnings + private final static class Earnings { + public BigDecimal Domestic = new BigDecimal(0); + public BigDecimal Worldwide = new BigDecimal(0); + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof Earnings; + Earnings earnings = tempVar ? (Earnings)obj : null; + return tempVar && this.equals(earnings); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + return (this.Domestic.hashCode() * 397) ^ this.Worldwide.hashCode(); + } + } + + private boolean equals(Earnings other) { + return this.Domestic.compareTo(other.Domestic) == 0 && this.Worldwide.compareTo(other.Worldwide) == 0; + } + } + + private static class KeyValuePair { + public static KeyValuePair Create(TKey key, TValue value) { + return new KeyValuePair(key, value); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test types.")] private sealed class Movie + private final static class Movie { + public HashMap Cast; + public HashMap> Related; + public HashMap Revenue; + public HashMap Stats; + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof Movie; + Movie movie = tempVar ? (Movie)obj : null; + return tempVar && this.equals(movie); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + int hashCode = 0; + hashCode = (hashCode * 397) ^ (this.Cast == null ? null : this.Cast.hashCode() != null ? this.Cast.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Stats == null ? null : this.Stats.hashCode() != null ? this.Stats.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Related == null ? null : this.Related.hashCode() != null ? this.Related.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Revenue == null ? null : this.Revenue.hashCode() != null ? this.Revenue.hashCode() : 0); + return hashCode; + } + } + + private static boolean MapEquals(HashMap left, HashMap right) { + if (left.size() != right.size()) { + return false; + } + + for (KeyValuePair item : left) { + TValue value; + if (!(right.containsKey(item.Key) && (value = right.get(item.Key)) == value)) { + return false; + } + + if (!item.Value.equals(value)) { + return false; + } + } + + return true; + } + + private static boolean NestedMapEquals(HashMap> left, HashMap> right) { + if (left.size() != right.size()) { + return false; + } + + for (KeyValuePair> item : left) { + java.util.HashMap value; + if (!(right.containsKey(item.Key) && (value = right.get(item.Key)) == value)) { + return false; + } + + if (!Movie.MapEquals(item.Value, value)) { + return false; + } + } + + return true; + } + + private boolean equals(Movie other) { + return (this.Cast == other.Cast || ((this.Cast != null) && (other.Cast != null) && Movie.MapEquals(this.Cast, other.Cast))) && (this.Stats == other.Stats || ((this.Stats != null) && (other.Stats != null) && Movie.MapEquals(this.Stats, other.Stats))) && (this.Related == other.Related || ((this.Related != null) && (other.Related != null) && Movie.NestedMapEquals(this.Related, other.Related))) && (this.Revenue == other.Revenue || ((this.Revenue != null) && (other.Revenue != null) && Movie.MapEquals(this.Revenue, other.Revenue))); + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedSetUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedSetUnitTests.java new file mode 100644 index 0000000..6faa64e --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/TypedSetUnitTests.java @@ -0,0 +1,1992 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.HybridRowVersion; +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.RowBuffer; +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.UUID; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass][DeploymentItem(TypedSetUnitTests.SchemaFile, "TestData")] public sealed class +// TypedSetUnitTests +public final class TypedSetUnitTests { + private static final int InitialRowSize = 2 * 1024 * 1024; + private static final String SchemaFile = "TestData\\TodoSchema.json"; + private Namespace counterSchema; + private Layout layout; + private LayoutResolver resolver; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void CreateTodos() + public void CreateTodos() { + RowBuffer row = new RowBuffer(TypedSetUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + + Todo t1 = new Todo(); + t1.Attendees = new ArrayList(Arrays.asList("jason", "janice", "joshua")); + t1.Projects = new ArrayList(Arrays.asList(UUID.fromString("{4674962B-CE11-4916-81C5-0421EE36F168}"), + UUID.fromString("{7499C40E-7077-45C1-AE5F-3E384966B3B9}"), UUID.fromString("{B7BC39C2-1A2D-4EAF-8F33" + + "-ED976872D876}"), UUID.fromString("{DEA71ABE-3041-4CAF-BBD9-1A46D10832A0}"))); + t1.Checkboxes = new ArrayList(Arrays.asList(true, false)); + t1.Prices = new ArrayList>(Arrays.asList(new ArrayList(Arrays.asList(1.2F, 3.0F)), + new ArrayList(Arrays.asList(4.1F, 5.7F)), new ArrayList(Arrays.asList(7.3F, 8.12F, 9.14F)))); + t1.Nested = + new ArrayList>>(Arrays.asList(new ArrayList>(Arrays.asList(new ArrayList(Arrays.asList(1, 2)))), new ArrayList>(Arrays.asList(new ArrayList(Arrays.asList(3, 4)))), new ArrayList>(Arrays.asList(new ArrayList(Arrays.asList(5, 6)))))); + ShoppingItem tempVar = new ShoppingItem(); + tempVar.Label = "milk"; + tempVar.Count = 1; + ShoppingItem tempVar2 = new ShoppingItem(); + tempVar2.Label = "broccoli"; + tempVar2.Count = 2; + ShoppingItem tempVar3 = new ShoppingItem(); + tempVar3.Label = "steak"; + tempVar3.Count = 6; + t1.Shopping = new ArrayList(Arrays.asList(tempVar, tempVar2, tempVar3)); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: t1.Work = new List> { Tuple.Create(false, 10000UL), Tuple.Create(true, + // 49053UL), Tuple.Create(false, 53111UL)}; + t1.Work = new ArrayList>(Arrays.asList(Tuple.Create(false, 10000), Tuple.Create(true, + 49053), Tuple.Create(false, 53111))); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteTodo(tempRef_row, RowCursor.Create(tempRef_row2, out _), t1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + Todo t2 = this.ReadTodo(tempRef_row3, RowCursor.Create(tempRef_row4, out _)); + row = tempRef_row4.argValue; + row = tempRef_row3.argValue; + assert t1 == t2; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void FindAndDelete() + public void FindAndDelete() { + RowBuffer row = new RowBuffer(TypedSetUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + + ArrayList expected = new ArrayList(Arrays.asList(UUID.fromString("{4674962B-CE11-4916-81C5" + + "-0421EE36F168}"), UUID.fromString("{7499C40E-7077-45C1-AE5F-3E384966B3B9}"), UUID.fromString("{B7BC39C2" + + "-1A2D-4EAF-8F33-ED976872D876}"), UUID.fromString("{DEA71ABE-3041-4CAF-BBD9-1A46D10832A0}"))); + + for (java.lang.Iterable permutation : expected.Permute()) { + Todo t1 = new Todo(); + t1.Projects = new ArrayList(permutation); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + this.WriteTodo(tempRef_row, RowCursor.Create(tempRef_row2, out _), t1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + + // Attempt to update each item in turn and then update it with itself. + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row3); + row = tempRef_row3.argValue; + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.layout.TryFind("projects", out c); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor setScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.Clone(out setScope).Find(tempRef_row4, c.Path); + row = tempRef_row4.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row5, ref setScope, out setScope)); + row = tempRef_row5.argValue; + for (UUID p : t1.Projects) { + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row6, Utf8String.Empty); + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row7, + ref tempCursor, p)); + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + RowCursor findScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().Find(tempRef_row8, ref setScope, ref tempCursor, + out findScope)); + row = tempRef_row8.argValue; + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().DeleteSparse(tempRef_row9, + ref findScope)); + row = tempRef_row9.argValue; + } + } + + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void FindInSet() + public void FindInSet() { + RowBuffer row = new RowBuffer(TypedSetUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + + Todo t1 = new Todo(); + t1.Attendees = new ArrayList(Arrays.asList("jason", "janice", "joshua")); + t1.Prices = new ArrayList>(Arrays.asList(new ArrayList(Arrays.asList(1.2F, 3.0F)), + new ArrayList(Arrays.asList(4.1F, 5.7F)), new ArrayList(Arrays.asList(7.3F, 8.12F, 9.14F)))); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteTodo(tempRef_row, RowCursor.Create(tempRef_row2, out _), t1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + + // Attempt to find each item in turn. + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row3); + row = tempRef_row3.argValue; + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("attendees", out c); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor setScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out setScope).Find(tempRef_row4, c.Path); + row = tempRef_row4.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row5, ref setScope, out setScope)); + row = tempRef_row5.argValue; + for (int i = 0; i < t1.Attendees.size(); i++) { + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.Clone(out tempCursor).Find(tempRef_row6, Utf8String.Empty); + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row7, ref tempCursor, + t1.Attendees.get(i))); + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + RowCursor findScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().Find(tempRef_row8, ref setScope, ref tempCursor, + out findScope)); + row = tempRef_row8.argValue; + Assert.AreEqual(i, findScope.Index, String.format("Failed to find t1.Attendees[%1$s]", i)); + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("prices", out c); + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out setScope).Find(tempRef_row9, c.Path); + row = tempRef_row9.argValue; + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row10, ref setScope, out setScope)); + row = tempRef_row10.argValue; + TypeArgument innerType = c.TypeArgs[0]; + TypeArgument itemType = innerType.getTypeArgs().get(0).clone(); + LayoutUniqueScope innerLayout = innerType.getType().TypeAs(); + for (int i = 0; i < t1.Prices.size(); i++) { + tangible.RefObject tempRef_row11 = + new tangible.RefObject(row); + RowCursor tempCursor1; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.Clone(out tempCursor1).Find(tempRef_row11, Utf8String.Empty); + row = tempRef_row11.argValue; + tangible.RefObject tempRef_row12 = + new tangible.RefObject(row); + RowCursor innerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(innerLayout.WriteScope(tempRef_row12, ref tempCursor1, + innerType.getTypeArgs().clone(), out innerScope)); + row = tempRef_row12.argValue; + for (int j = 0; j < t1.Prices.get(i).size(); j++) { + tangible.RefObject tempRef_row13 = + new tangible.RefObject(row); + RowCursor tempCursor2; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor2).Find(tempRef_row13, "prices.0.0"); + row = tempRef_row13.argValue; + tangible.RefObject tempRef_row14 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor2 = + new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(itemType.getType().TypeAs().WriteSparse(tempRef_row14, + tempRef_tempCursor2, t1.Prices.get(i).get(j))); + tempCursor2 = tempRef_tempCursor2.argValue; + row = tempRef_row14.argValue; + tangible.RefObject tempRef_row15 = + new tangible.RefObject(row); + tangible.RefObject tempRef_innerScope = + new tangible.RefObject(innerScope); + tangible.RefObject tempRef_tempCursor22 = + new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(innerLayout.MoveField(tempRef_row15, tempRef_innerScope, tempRef_tempCursor22)); + tempCursor2 = tempRef_tempCursor22.argValue; + innerScope = tempRef_innerScope.argValue; + row = tempRef_row15.argValue; + } + + tangible.RefObject tempRef_row16 = + new tangible.RefObject(row); + RowCursor findScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().Find(tempRef_row16, ref setScope, ref tempCursor1, + out findScope)); + row = tempRef_row16.argValue; + Assert.AreEqual(i, findScope.Index, String.format("Failed to find t1.Prices[%1$s]", i)); + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestInitialize] public void ParseNamespaceExample() + public void ParseNamespaceExample() { + String json = Files.readString(TypedSetUnitTests.SchemaFile); + this.counterSchema = Namespace.Parse(json); + this.resolver = new LayoutResolverNamespace(this.counterSchema); + this.layout = this.resolver.Resolve(tangible.ListHelper.find(this.counterSchema.getSchemas(), + x -> x.Name.equals("Todo")).SchemaId); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void PreventUniquenessViolations() + public void PreventUniquenessViolations() { + RowBuffer row = new RowBuffer(TypedSetUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + + Todo t1 = new Todo(); + t1.Attendees = new ArrayList(Arrays.asList("jason")); + t1.Projects = new ArrayList(Arrays.asList(UUID.fromString("{4674962B-CE11-4916-81C5-0421EE36F168}"))); + t1.Prices = new ArrayList>(Arrays.asList(new ArrayList(Arrays.asList(1.2F, 3.0F)))); + ShoppingItem tempVar = new ShoppingItem(); + tempVar.Label = "milk"; + tempVar.Count = 1; + t1.Shopping = new ArrayList(Arrays.asList(tempVar)); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: t1.Work = new List> { Tuple.Create(false, 10000UL)}; + t1.Work = new ArrayList>(Arrays.asList(Tuple.Create(false, 10000))); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + this.WriteTodo(tempRef_row, RowCursor.Create(tempRef_row2, out _), t1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + + // Attempt to insert duplicate items in existing sets. + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row3); + row = tempRef_row3.argValue; + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("attendees", out c); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor setScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out setScope).Find(tempRef_row4, c.Path); + row = tempRef_row4.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row5, ref setScope, out setScope)); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row6, Utf8String.Empty); + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row7, ref tempCursor, + t1.Attendees.get(0))); + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.Exists(c.TypeAs().MoveField(tempRef_row8, ref setScope, ref tempCursor, + UpdateOptions.Insert)); + row = tempRef_row8.argValue; + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row9, Utf8String.Empty); + row = tempRef_row9.argValue; + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row10, ref tempCursor, + t1.Attendees.get(0))); + row = tempRef_row10.argValue; + tangible.RefObject tempRef_row11 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().Find(tempRef_row11, ref setScope, ref tempCursor, out _)); + row = tempRef_row11.argValue; + tangible.RefObject tempRef_row12 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row12, Utf8String.Empty); + row = tempRef_row12.argValue; + tangible.RefObject tempRef_row13 = + new tangible.RefObject(row); + String _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.NotFound(c.TypeArgs[0].Type.TypeAs().ReadSparse(tempRef_row13, ref tempCursor, out _)); + row = tempRef_row13.argValue; + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("projects", out c); + tangible.RefObject tempRef_row14 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out setScope).Find(tempRef_row14, c.Path); + row = tempRef_row14.argValue; + tangible.RefObject tempRef_row15 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row15, ref setScope, out setScope)); + row = tempRef_row15.argValue; + tangible.RefObject tempRef_row16 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row16, Utf8String.Empty); + row = tempRef_row16.argValue; + tangible.RefObject tempRef_row17 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row17, ref tempCursor, + t1.Projects.get(0))); + row = tempRef_row17.argValue; + tangible.RefObject tempRef_row18 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.Exists(c.TypeAs().MoveField(tempRef_row18, ref setScope, ref tempCursor, + UpdateOptions.Insert)); + row = tempRef_row18.argValue; + + // Attempt to move a duplicate set into a set of sets. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("prices", out c); + tangible.RefObject tempRef_row19 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out setScope).Find(tempRef_row19, c.Path); + row = tempRef_row19.argValue; + tangible.RefObject tempRef_row20 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row20, ref setScope, out setScope)); + row = tempRef_row20.argValue; + TypeArgument innerType = c.TypeArgs[0]; + LayoutUniqueScope innerLayout = innerType.getType().TypeAs(); + tangible.RefObject tempRef_row21 = + new tangible.RefObject(row); + RowCursor tempCursor1; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor1).Find(tempRef_row21, Utf8String.Empty); + row = tempRef_row21.argValue; + tangible.RefObject tempRef_row22 = + new tangible.RefObject(row); + RowCursor innerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(innerLayout.WriteScope(tempRef_row22, ref tempCursor1, innerType.getTypeArgs().clone() + , out innerScope)); + row = tempRef_row22.argValue; + for (float innerItem : t1.Prices.get(0)) { + LayoutFloat32 itemLayout = innerType.getTypeArgs().get(0).getType().TypeAs(); + tangible.RefObject tempRef_row23 = + new tangible.RefObject(row); + RowCursor tempCursor2; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.Clone(out tempCursor2).Find(tempRef_row23, "prices.0.0"); + row = tempRef_row23.argValue; + tangible.RefObject tempRef_row24 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor2 = + new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(itemLayout.WriteSparse(tempRef_row24, tempRef_tempCursor2, innerItem)); + tempCursor2 = tempRef_tempCursor2.argValue; + row = tempRef_row24.argValue; + tangible.RefObject tempRef_row25 = + new tangible.RefObject(row); + tangible.RefObject tempRef_innerScope = + new tangible.RefObject(innerScope); + tangible.RefObject tempRef_tempCursor22 = + new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(innerLayout.MoveField(tempRef_row25, tempRef_innerScope, tempRef_tempCursor22)); + tempCursor2 = tempRef_tempCursor22.argValue; + innerScope = tempRef_innerScope.argValue; + row = tempRef_row25.argValue; + } + + tangible.RefObject tempRef_row26 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.Exists(c.TypeAs().MoveField(tempRef_row26, ref setScope, ref tempCursor1, + UpdateOptions.Insert)); + row = tempRef_row26.argValue; + + // Attempt to move a duplicate UDT into a set of UDT. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("shopping", out c); + tangible.RefObject tempRef_row27 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out setScope).Find(tempRef_row27, c.Path); + row = tempRef_row27.argValue; + tangible.RefObject tempRef_row28 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row28, ref setScope, out setScope)); + row = tempRef_row28.argValue; + LayoutUDT udtLayout = c.TypeArgs[0].Type.TypeAs(); + tangible.RefObject tempRef_row29 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row29, Utf8String.Empty); + row = tempRef_row29.argValue; + tangible.RefObject tempRef_row30 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + RowCursor udtScope; + tangible.OutObject tempOut_udtScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(udtLayout.WriteScope(tempRef_row30, tempRef_tempCursor, c.TypeArgs[0].TypeArgs, + tempOut_udtScope)); + udtScope = tempOut_udtScope.argValue; + tempCursor = tempRef_tempCursor.argValue; + row = tempRef_row30.argValue; + tangible.RefObject tempRef_row31 = + new tangible.RefObject(row); + tangible.RefObject tempRef_udtScope = + new tangible.RefObject(udtScope); + TypedSetUnitTests.WriteShoppingItem(tempRef_row31, tempRef_udtScope, c.TypeArgs[0].TypeArgs, + t1.Shopping.get(0)); + udtScope = tempRef_udtScope.argValue; + row = tempRef_row31.argValue; + tangible.RefObject tempRef_row32 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.Exists(c.TypeAs().MoveField(tempRef_row32, ref setScope, ref tempCursor, + UpdateOptions.Insert)); + row = tempRef_row32.argValue; + + // Attempt to move a duplicate tuple into a set of tuple. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("work", out c); + tangible.RefObject tempRef_row33 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out setScope).Find(tempRef_row33, c.Path); + row = tempRef_row33.argValue; + tangible.RefObject tempRef_row34 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row34, ref setScope, out setScope)); + row = tempRef_row34.argValue; + innerType = c.TypeArgs[0]; + LayoutIndexedScope tupleLayout = innerType.getType().TypeAs(); + tangible.RefObject tempRef_row35 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.Clone(out tempCursor).Find(tempRef_row35, Utf8String.Empty); + row = tempRef_row35.argValue; + tangible.RefObject tempRef_row36 = + new tangible.RefObject(row); + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(tupleLayout.WriteScope(tempRef_row36, ref tempCursor, innerType.getTypeArgs().clone(), + out tupleScope)); + row = tempRef_row36.argValue; + tangible.RefObject tempRef_row37 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + ResultAssert.IsSuccess(innerType.getTypeArgs().get(0).getType().TypeAs().WriteSparse(tempRef_row37, tempRef_tupleScope, t1.Work.get(0).Item1)); + tupleScope = tempRef_tupleScope.argValue; + row = tempRef_row37.argValue; + tangible.RefObject tempRef_row38 = + new tangible.RefObject(row); + assert tupleScope.MoveNext(tempRef_row38); + row = tempRef_row38.argValue; + tangible.RefObject tempRef_row39 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tupleScope2 = + new tangible.RefObject(tupleScope); + ResultAssert.IsSuccess(innerType.getTypeArgs().get(1).getType().TypeAs().WriteSparse(tempRef_row39, tempRef_tupleScope2, t1.Work.get(0).Item2)); + tupleScope = tempRef_tupleScope2.argValue; + row = tempRef_row39.argValue; + tangible.RefObject tempRef_row40 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.Exists(c.TypeAs().MoveField(tempRef_row40, ref setScope, ref tempCursor, + UpdateOptions.Insert)); + row = tempRef_row40.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void PreventUpdatesInNonUpdatableScope() + public void PreventUpdatesInNonUpdatableScope() { + RowBuffer row = new RowBuffer(TypedSetUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + + // Write a set and then try to write directly into it. + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("attendees", out c); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor setScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row, out setScope).Find(tempRef_row2, c.Path); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(tempRef_row3, ref setScope, c.TypeArgs, + out setScope)); + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.InsufficientPermissions(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row4, + ref setScope, "foo")); + row = tempRef_row4.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row5, out tempCursor).Find(tempRef_row6, Utf8String.Empty); + row = tempRef_row6.argValue; + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row7, ref tempCursor, "foo" + )); + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().MoveField(tempRef_row8, ref setScope, ref tempCursor)); + row = tempRef_row8.argValue; + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.InsufficientPermissions(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row9, + ref setScope, "foo")); + row = tempRef_row9.argValue; + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().DeleteSparse(tempRef_row10, ref setScope)); + row = tempRef_row10.argValue; + + // Write a set of sets, successfully insert an empty set into it, and then try to write directly to the inner + // set. + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("prices", out c); + tangible.RefObject tempRef_row11 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row12 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row11, out setScope).Find(tempRef_row12, c.Path); + row = tempRef_row12.argValue; + row = tempRef_row11.argValue; + tangible.RefObject tempRef_row13 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(tempRef_row13, ref setScope, c.TypeArgs, + out setScope)); + row = tempRef_row13.argValue; + TypeArgument innerType = c.TypeArgs[0]; + TypeArgument itemType = innerType.getTypeArgs().get(0).clone(); + LayoutUniqueScope innerLayout = innerType.getType().TypeAs(); + tangible.RefObject tempRef_row14 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row15 = + new tangible.RefObject(row); + RowCursor tempCursor1; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row14, out tempCursor1).Find(tempRef_row15, "prices.0"); + row = tempRef_row15.argValue; + row = tempRef_row14.argValue; + tangible.RefObject tempRef_row16 = + new tangible.RefObject(row); + RowCursor innerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(innerLayout.WriteScope(tempRef_row16, ref tempCursor1, innerType.getTypeArgs().clone() + , out innerScope)); + row = tempRef_row16.argValue; + tangible.RefObject tempRef_row17 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row18 = + new tangible.RefObject(row); + RowCursor tempCursor2; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + RowCursor.Create(tempRef_row17, out tempCursor2).Find(tempRef_row18, "prices.0.0"); + row = tempRef_row18.argValue; + row = tempRef_row17.argValue; + tangible.RefObject tempRef_row19 = + new tangible.RefObject(row); + tangible.RefObject tempRef_tempCursor2 = + new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(itemType.getType().TypeAs().WriteSparse(tempRef_row19, + tempRef_tempCursor2, 1.0F)); + tempCursor2 = tempRef_tempCursor2.argValue; + row = tempRef_row19.argValue; + tangible.RefObject tempRef_row20 = + new tangible.RefObject(row); + tangible.RefObject tempRef_innerScope = + new tangible.RefObject(innerScope); + tangible.RefObject tempRef_tempCursor22 = + new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(innerLayout.MoveField(tempRef_row20, tempRef_innerScope, tempRef_tempCursor22)); + tempCursor2 = tempRef_tempCursor22.argValue; + innerScope = tempRef_innerScope.argValue; + row = tempRef_row20.argValue; + tangible.RefObject tempRef_row21 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(c.TypeAs().MoveField(tempRef_row21, ref setScope, ref tempCursor1)); + row = tempRef_row21.argValue; + tangible.RefObject tempRef_row22 = + new tangible.RefObject(row); + assert setScope.MoveNext(tempRef_row22); + row = tempRef_row22.argValue; + tangible.RefObject tempRef_row23 = + new tangible.RefObject(row); + tangible.RefObject tempRef_setScope = + new tangible.RefObject(setScope); + tangible.OutObject tempOut_innerScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(innerLayout.ReadScope(tempRef_row23, tempRef_setScope, tempOut_innerScope)); + innerScope = tempOut_innerScope.argValue; + setScope = tempRef_setScope.argValue; + row = tempRef_row23.argValue; + tangible.RefObject tempRef_row24 = + new tangible.RefObject(row); + tangible.RefObject tempRef_innerScope2 = + new tangible.RefObject(innerScope); + ResultAssert.InsufficientPermissions(itemType.getType().TypeAs().WriteSparse(tempRef_row24, + tempRef_innerScope2, 1.0F)); + innerScope = tempRef_innerScope2.argValue; + row = tempRef_row24.argValue; + tangible.RefObject tempRef_row25 = + new tangible.RefObject(row); + tangible.RefObject tempRef_innerScope3 = + new tangible.RefObject(innerScope); + ResultAssert.InsufficientPermissions(itemType.getType().TypeAs().DeleteSparse(tempRef_row25, + tempRef_innerScope3)); + innerScope = tempRef_innerScope3.argValue; + row = tempRef_row25.argValue; + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void RowWriterTest() + public void RowWriterTest() { + RowBuffer row = new RowBuffer(TypedSetUnitTests.InitialRowSize); + + ArrayList expected = new ArrayList(Arrays.asList(UUID.fromString("{4674962B-CE11-4916-81C5" + + "-0421EE36F168}"), UUID.fromString("{7499C40E-7077-45C1-AE5F-3E384966B3B9}"), UUID.fromString("{B7BC39C2" + + "-1A2D-4EAF-8F33-ED976872D876}"), UUID.fromString("{DEA71ABE-3041-4CAF-BBD9-1A46D10832A0}"))); + + for (java.lang.Iterable permutation : expected.Permute()) { + Todo t1 = new Todo(); + t1.Projects = new ArrayList(permutation); + + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + ResultAssert.IsSuccess(RowWriter.WriteBuffer(tempRef_row, t1, TypedSetUnitTests.SerializeTodo)); + row = tempRef_row.argValue; + + // Update the existing Set by updating each item with itself. This ensures that the RowWriter has + // maintained the unique index correctly. + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.layout.TryFind("projects", out c); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor root; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + RowCursor.Create(tempRef_row2, out root); + row = tempRef_row2.argValue; + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + RowCursor projScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.Clone(out projScope).Find(tempRef_row3, c.Path); + row = tempRef_row3.argValue; + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row4, ref projScope, out projScope)); + row = tempRef_row4.argValue; + for (UUID item : t1.Projects) { + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row5, Utf8String.Empty); + row = tempRef_row5.argValue; + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row6, + ref tempCursor, item)); + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().MoveField(tempRef_row7, ref projScope, + ref tempCursor)); + row = tempRef_row7.argValue; + } + + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + Todo t2 = this.ReadTodo(tempRef_row8, RowCursor.Create(tempRef_row9, out _)); + row = tempRef_row9.argValue; + row = tempRef_row8.argValue; + assert t1 == t2; + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void UpdateInSet() + public void UpdateInSet() { + RowBuffer row = new RowBuffer(TypedSetUnitTests.InitialRowSize); + row.InitLayout(HybridRowVersion.V1, this.layout, this.resolver); + + ArrayList expected = new ArrayList(Arrays.asList(UUID.fromString("{4674962B-CE11-4916-81C5" + + "-0421EE36F168}"), UUID.fromString("{7499C40E-7077-45C1-AE5F-3E384966B3B9}"), UUID.fromString("{B7BC39C2" + + "-1A2D-4EAF-8F33-ED976872D876}"), UUID.fromString("{DEA71ABE-3041-4CAF-BBD9-1A46D10832A0}"))); + + for (java.lang.Iterable permutation : expected.Permute()) { + Todo t1 = new Todo(); + t1.Projects = new ArrayList(permutation); + + tangible.RefObject tempRef_row = + new tangible.RefObject(row); + tangible.RefObject tempRef_row2 = + new tangible.RefObject(row); + RowCursor _; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + this.WriteTodo(tempRef_row, RowCursor.Create(tempRef_row2, out _), t1); + row = tempRef_row2.argValue; + row = tempRef_row.argValue; + + // Attempt to find each item in turn and then delete it. + tangible.RefObject tempRef_row3 = + new tangible.RefObject(row); + RowCursor root = RowCursor.Create(tempRef_row3); + row = tempRef_row3.argValue; + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert this.layout.TryFind("projects", out c); + tangible.RefObject tempRef_row4 = + new tangible.RefObject(row); + RowCursor setScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.Clone(out setScope).Find(tempRef_row4, c.Path); + row = tempRef_row4.argValue; + tangible.RefObject tempRef_row5 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().ReadScope(tempRef_row5, ref setScope, out setScope)); + row = tempRef_row5.argValue; + for (UUID elm : t1.Projects) { + // Verify it is already there. + tangible.RefObject tempRef_row6 = + new tangible.RefObject(row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row6, Utf8String.Empty); + row = tempRef_row6.argValue; + tangible.RefObject tempRef_row7 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row7, + ref tempCursor, elm)); + row = tempRef_row7.argValue; + tangible.RefObject tempRef_row8 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: C# to Java Converter could not resolve the named parameters in the + // following line: + //ORIGINAL LINE: ResultAssert.IsSuccess(c.TypeAs().Find(ref row, ref setScope, ref + // tempCursor, value: out RowCursor _)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().Find(tempRef_row8, ref setScope, ref tempCursor, + value: + out RowCursor _)) + row = tempRef_row8.argValue; + + // Insert it again with update. + tangible.RefObject tempRef_row9 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row9, Utf8String.Empty); + row = tempRef_row9.argValue; + tangible.RefObject tempRef_row10 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row10, + ref tempCursor, elm)); + row = tempRef_row10.argValue; + tangible.RefObject tempRef_row11 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().MoveField(tempRef_row11, ref setScope, + ref tempCursor, UpdateOptions.Update)); + row = tempRef_row11.argValue; + + // Insert it again with upsert. + tangible.RefObject tempRef_row12 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row12, Utf8String.Empty); + row = tempRef_row12.argValue; + tangible.RefObject tempRef_row13 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row13, + ref tempCursor, elm)); + row = tempRef_row13.argValue; + tangible.RefObject tempRef_row14 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeAs().MoveField(tempRef_row14, ref setScope, + ref tempCursor)); + row = tempRef_row14.argValue; + + // Insert it again with insert (fail: exists). + tangible.RefObject tempRef_row15 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row15, Utf8String.Empty); + row = tempRef_row15.argValue; + tangible.RefObject tempRef_row16 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row16, + ref tempCursor, elm)); + row = tempRef_row16.argValue; + tangible.RefObject tempRef_row17 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.Exists(c.TypeAs().MoveField(tempRef_row17, ref setScope, + ref tempCursor, UpdateOptions.Insert)); + row = tempRef_row17.argValue; + + // Insert it again with insert at (fail: disallowed). + tangible.RefObject tempRef_row18 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.Clone(out tempCursor).Find(tempRef_row18, Utf8String.Empty); + row = tempRef_row18.argValue; + tangible.RefObject tempRef_row19 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().WriteSparse(tempRef_row19, + ref tempCursor, elm)); + row = tempRef_row19.argValue; + tangible.RefObject tempRef_row20 = + new tangible.RefObject(row); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.TypeConstraint(c.TypeAs().MoveField(tempRef_row20, ref setScope, + ref tempCursor, UpdateOptions.InsertAt)); + row = tempRef_row20.argValue; + } + } + } + + private static ShoppingItem ReadShoppingItem(tangible.RefObject row, tangible.RefObject matchScope) { + Layout matchLayout = matchScope.argValue.getLayout(); + ShoppingItem m = new ShoppingItem(); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert matchLayout.TryFind("label", out c); + tangible.OutObject tempOut_Label = new tangible.OutObject(); + ResultAssert.IsSuccess(c.TypeAs().ReadVariable(row, matchScope, c, tempOut_Label)); + m.Label = tempOut_Label.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert matchLayout.TryFind("count", out c); + tangible.OutObject tempOut_Count = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ResultAssert.IsSuccess(c.TypeAs().ReadFixed(ref row, ref matchScope, c, out m.Count)); + ResultAssert.IsSuccess(c.TypeAs().ReadFixed(row, matchScope, c, tempOut_Count)); + m.Count = tempOut_Count.argValue; + return m; + } + + private Todo ReadTodo(tangible.RefObject row, tangible.RefObject root) { + Todo value = new Todo(); + + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("attendees", out c); + RowCursor tagsScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out tagsScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref tagsScope, out tagsScope) == Result.Success) { + value.Attendees = new ArrayList(); + while (tagsScope.MoveNext(row)) { + String item; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref tagsScope, + out item)); + value.Attendees.add(item); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("projects", out c); + RowCursor projScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out projScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref projScope, out projScope) == Result.Success) { + value.Projects = new ArrayList(); + while (projScope.MoveNext(row)) { + java.util.UUID item; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref projScope, + out item)); + value.Projects.add(item); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("checkboxes", out c); + RowCursor checkboxScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out checkboxScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref checkboxScope, out checkboxScope) == Result.Success) { + value.Checkboxes = new ArrayList(); + while (checkboxScope.MoveNext(row)) { + boolean item; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.TypeArgs[0].Type.TypeAs().ReadSparse(row, ref checkboxScope, + out item)); + value.Checkboxes.add(item); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("prices", out c); + RowCursor pricesScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out pricesScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref pricesScope, out pricesScope) == Result.Success) { + value.Prices = new ArrayList>(); + TypeArgument innerType = c.TypeArgs[0]; + LayoutUniqueScope innerLayout = innerType.getType().TypeAs(); + while (pricesScope.MoveNext(row)) { + ArrayList item = new ArrayList(); + tangible.RefObject tempRef_pricesScope = + new tangible.RefObject(pricesScope); + RowCursor innerScope; + tangible.OutObject tempOut_innerScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(innerLayout.ReadScope(row, tempRef_pricesScope, tempOut_innerScope)); + innerScope = tempOut_innerScope.argValue; + pricesScope = tempRef_pricesScope.argValue; + while (innerScope.MoveNext(row)) { + LayoutFloat32 itemLayout = innerType.getTypeArgs().get(0).getType().TypeAs(); + tangible.RefObject tempRef_innerScope = + new tangible.RefObject(innerScope); + float innerItem; + tangible.OutObject tempOut_innerItem = new tangible.OutObject(); + ResultAssert.IsSuccess(itemLayout.ReadSparse(row, tempRef_innerScope, tempOut_innerItem)); + innerItem = tempOut_innerItem.argValue; + innerScope = tempRef_innerScope.argValue; + item.add(innerItem); + } + + value.Prices.add(item); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("nested", out c); + RowCursor nestedScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out nestedScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref nestedScope, out nestedScope) == Result.Success) { + value.Nested = new ArrayList>>(); + TypeArgument in2Type = c.TypeArgs[0]; + LayoutUniqueScope in2Layout = in2Type.getType().TypeAs(); + while (nestedScope.MoveNext(row)) { + ArrayList> item = new ArrayList>(); + tangible.RefObject tempRef_nestedScope = + new tangible.RefObject(nestedScope); + RowCursor in2Scope; + tangible.OutObject tempOut_in2Scope = + new tangible.OutObject(); + ResultAssert.IsSuccess(in2Layout.ReadScope(row, tempRef_nestedScope, tempOut_in2Scope)); + in2Scope = tempOut_in2Scope.argValue; + nestedScope = tempRef_nestedScope.argValue; + while (in2Scope.MoveNext(row)) { + TypeArgument in3Type = in2Type.getTypeArgs().get(0).clone(); + LayoutUniqueScope in3Layout = in3Type.getType().TypeAs(); + ArrayList item2 = new ArrayList(); + tangible.RefObject tempRef_in2Scope = + new tangible.RefObject(in2Scope); + RowCursor in3Scope; + tangible.OutObject tempOut_in3Scope = + new tangible.OutObject(); + ResultAssert.IsSuccess(in3Layout.ReadScope(row, tempRef_in2Scope, tempOut_in3Scope)); + in3Scope = tempOut_in3Scope.argValue; + in2Scope = tempRef_in2Scope.argValue; + while (in3Scope.MoveNext(row)) { + LayoutInt32 itemLayout = in3Type.getTypeArgs().get(0).getType().TypeAs(); + tangible.RefObject tempRef_in3Scope = new tangible.RefObject(in3Scope); + int innerItem; + tangible.OutObject tempOut_innerItem2 = new tangible.OutObject(); + ResultAssert.IsSuccess(itemLayout.ReadSparse(row, tempRef_in3Scope, tempOut_innerItem2)); + innerItem = tempOut_innerItem2.argValue; + in3Scope = tempRef_in3Scope.argValue; + item2.add(innerItem); + } + + item.add(item2); + } + + value.Nested.add(item); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("shopping", out c); + RowCursor shoppingScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out shoppingScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref shoppingScope, out shoppingScope) == Result.Success) { + value.Shopping = new ArrayList(); + while (shoppingScope.MoveNext(row)) { + TypeArgument innerType = c.TypeArgs[0]; + LayoutUDT innerLayout = innerType.getType().TypeAs(); + tangible.RefObject tempRef_shoppingScope = + new tangible.RefObject(shoppingScope); + RowCursor matchScope; + tangible.OutObject tempOut_matchScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(innerLayout.ReadScope(row, tempRef_shoppingScope, tempOut_matchScope)); + matchScope = tempOut_matchScope.argValue; + shoppingScope = tempRef_shoppingScope.argValue; + tangible.RefObject tempRef_matchScope = + new tangible.RefObject(matchScope); + ShoppingItem item = TypedSetUnitTests.ReadShoppingItem(row, tempRef_matchScope); + matchScope = tempRef_matchScope.argValue; + value.Shopping.add(item); + } + } + + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert this.layout.TryFind("work", out c); + RowCursor workScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + root.argValue.Clone(out workScope).Find(row, c.Path); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these cannot be converted using the 'RefObject' helper class unless the method is within the code being modified: + if (c.TypeAs().ReadScope(row, ref workScope, out workScope) == Result.Success) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: value.Work = new List>(); + value.Work = new ArrayList>(); + while (workScope.MoveNext(row)) { + TypeArgument innerType = c.TypeArgs[0]; + LayoutIndexedScope innerLayout = innerType.getType().TypeAs(); + + tangible.RefObject tempRef_workScope = new tangible.RefObject(workScope); + RowCursor tupleScope; + tangible.OutObject tempOut_tupleScope = new tangible.OutObject(); + ResultAssert.IsSuccess(innerLayout.ReadScope(row, tempRef_workScope, tempOut_tupleScope)); + tupleScope = tempOut_tupleScope.argValue; + workScope = tempRef_workScope.argValue; + assert tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope = new tangible.RefObject(tupleScope); + boolean item1; + tangible.OutObject tempOut_item1 = new tangible.OutObject(); + ResultAssert.IsSuccess(innerType.getTypeArgs().get(0).getType().TypeAs().ReadSparse(row, tempRef_tupleScope, tempOut_item1)); + item1 = tempOut_item1.argValue; + tupleScope = tempRef_tupleScope.argValue; + assert tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope2 = new tangible.RefObject(tupleScope); + long item2; + tangible.OutObject tempOut_item2 = new tangible.OutObject(); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: ResultAssert.IsSuccess(innerType.TypeArgs[1].Type.TypeAs().ReadSparse(ref row, ref tupleScope, out ulong item2)); + ResultAssert.IsSuccess(innerType.getTypeArgs().get(1).getType().TypeAs().ReadSparse(row, tempRef_tupleScope2, tempOut_item2)); + item2 = tempOut_item2.argValue; + tupleScope = tempRef_tupleScope2.argValue; + value.Work.add(Tuple.Create(item1, item2)); + } + } + + return value; + } + + private static Result SerializeTodo(tangible.RefObject writer, TypeArgument typeArg, Todo value) { + if (value.Projects != null) { + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + assert writer.argValue.getLayout().TryFind("projects", out c); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are + // not converted by C# to Java Converter: + Result r = writer.argValue.WriteScope("projects", c.TypeArg, value.Projects, (ref RowWriter writer2, + TypeArgument typeArg2, ArrayList value2) -> + { + for (UUID item : value2) { + ResultAssert.IsSuccess(writer2.WriteGuid(null, item)); + } + + return Result.Success; + }); + return r; + } + + return Result.Success; + } + + private static void WriteShoppingItem(tangible.RefObject row, tangible.RefObject matchScope, TypeArgumentList typeArgs, ShoppingItem m) { + Layout matchLayout = row.argValue.getResolver().Resolve(typeArgs.getSchemaId().clone()); + LayoutColumn c; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert matchLayout.TryFind("label", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteVariable(row, matchScope, c, m.Label)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + assert matchLayout.TryFind("count", out c); + ResultAssert.IsSuccess(c.TypeAs().WriteFixed(row, matchScope, c, m.Count)); + } + + private void WriteTodo(tangible.RefObject row, tangible.RefObject root, Todo value) { + LayoutColumn c; + + if (value.Attendees != null) { + tangible.OutObject tempOut_c = + new tangible.OutObject(); + assert this.layout.TryFind("attendees", tempOut_c); + c = tempOut_c.argValue; + RowCursor attendScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out attendScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref attendScope, + c.getTypeArgs().clone(), out attendScope)); + for (String item : value.Attendees) { + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(c.getTypeArgs().get(0).getType().TypeAs().WriteSparse(row, + ref tempCursor, item)); + tangible.RefObject tempRef_attendScope = + new tangible.RefObject(attendScope); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_attendScope, + tempRef_tempCursor)); + tempCursor = tempRef_tempCursor.argValue; + attendScope = tempRef_attendScope.argValue; + } + } + + if (value.Projects != null) { + tangible.OutObject tempOut_c2 = + new tangible.OutObject(); + assert this.layout.TryFind("projects", tempOut_c2); + c = tempOut_c2.argValue; + RowCursor projScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out projScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref projScope, + c.getTypeArgs().clone(), out projScope)); + for (UUID item : value.Projects) { + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + tangible.RefObject tempRef_tempCursor2 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(c.getTypeArgs().get(0).getType().TypeAs().WriteSparse(row, + tempRef_tempCursor2, item)); + tempCursor = tempRef_tempCursor2.argValue; + tangible.RefObject tempRef_projScope = + new tangible.RefObject(projScope); + tangible.RefObject tempRef_tempCursor3 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_projScope, + tempRef_tempCursor3)); + tempCursor = tempRef_tempCursor3.argValue; + projScope = tempRef_projScope.argValue; + } + } + + if (value.Checkboxes != null) { + tangible.OutObject tempOut_c3 = + new tangible.OutObject(); + assert this.layout.TryFind("checkboxes", tempOut_c3); + c = tempOut_c3.argValue; + RowCursor checkboxScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out checkboxScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref checkboxScope, + c.getTypeArgs().clone(), out checkboxScope)); + for (boolean item : value.Checkboxes) { + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + tangible.RefObject tempRef_tempCursor4 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(c.getTypeArgs().get(0).getType().TypeAs().WriteSparse(row, + tempRef_tempCursor4, item)); + tempCursor = tempRef_tempCursor4.argValue; + tangible.RefObject tempRef_checkboxScope = + new tangible.RefObject(checkboxScope); + tangible.RefObject tempRef_tempCursor5 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_checkboxScope, + tempRef_tempCursor5)); + tempCursor = tempRef_tempCursor5.argValue; + checkboxScope = tempRef_checkboxScope.argValue; + } + } + + if (value.Prices != null) { + tangible.OutObject tempOut_c4 = + new tangible.OutObject(); + assert this.layout.TryFind("prices", tempOut_c4); + c = tempOut_c4.argValue; + RowCursor pricesScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out pricesScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref pricesScope, + c.getTypeArgs().clone(), out pricesScope)); + for (ArrayList item : value.Prices) { + assert item != null; + TypeArgument innerType = c.getTypeArgs().get(0).clone(); + LayoutUniqueScope innerLayout = innerType.getType().TypeAs(); + RowCursor tempCursor1; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor1).Find(row, "prices.0"); + RowCursor innerScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(innerLayout.WriteScope(row, ref tempCursor1, innerType.getTypeArgs().clone(), + out innerScope)); + for (float innerItem : item) { + LayoutFloat32 itemLayout = innerType.getTypeArgs().get(0).getType().TypeAs(); + RowCursor tempCursor2; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword + // - these cannot be converted using the 'OutObject' helper class unless the method is within the + // code being modified: + root.argValue.Clone(out tempCursor2).Find(row, "prices.0.0"); + tangible.RefObject tempRef_tempCursor2 + = new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(itemLayout.WriteSparse(row, tempRef_tempCursor2, innerItem)); + tempCursor2 = tempRef_tempCursor2.argValue; + tangible.RefObject tempRef_innerScope = + new tangible.RefObject(innerScope); + tangible.RefObject tempRef_tempCursor22 = new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(innerLayout.MoveField(row, tempRef_innerScope, tempRef_tempCursor22)); + tempCursor2 = tempRef_tempCursor22.argValue; + innerScope = tempRef_innerScope.argValue; + } + + tangible.RefObject tempRef_pricesScope = + new tangible.RefObject(pricesScope); + tangible.RefObject tempRef_tempCursor1 = + new tangible.RefObject(tempCursor1); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_pricesScope, + tempRef_tempCursor1)); + tempCursor1 = tempRef_tempCursor1.argValue; + pricesScope = tempRef_pricesScope.argValue; + } + } + + if (value.Nested != null) { + tangible.OutObject tempOut_c5 = + new tangible.OutObject(); + assert this.layout.TryFind("nested", tempOut_c5); + c = tempOut_c5.argValue; + RowCursor nestedScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out nestedScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref nestedScope, + c.getTypeArgs().clone(), out nestedScope)); + for (ArrayList> item : value.Nested) { + assert item != null; + TypeArgument in2Type = c.getTypeArgs().get(0).clone(); + LayoutUniqueScope in2Layout = in2Type.getType().TypeAs(); + RowCursor tempCursor1; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor1).Find(row, "prices.0"); + RowCursor in2Scope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(in2Layout.WriteScope(row, ref tempCursor1, in2Type.getTypeArgs().clone(), + out in2Scope)); + for (ArrayList item2 : item) { + assert item2 != null; + TypeArgument in3Type = in2Type.getTypeArgs().get(0).clone(); + LayoutUniqueScope in3Layout = in3Type.getType().TypeAs(); + RowCursor tempCursor2; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword + // - these cannot be converted using the 'OutObject' helper class unless the method is within the + // code being modified: + root.argValue.Clone(out tempCursor2).Find(row, "prices.0.0"); + RowCursor in3Scope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword + // - these cannot be converted using the 'OutObject' helper class unless the method is within the + // code being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword + // - these cannot be converted using the 'RefObject' helper class unless the method is within the + // code being modified: + ResultAssert.IsSuccess(in3Layout.WriteScope(row, ref tempCursor2, in3Type.getTypeArgs().clone(), + out in3Scope)); + for (int innerItem : item2) { + LayoutInt32 itemLayout = in3Type.getTypeArgs().get(0).getType().TypeAs(); + RowCursor tempCursor3; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' + // keyword - these cannot be converted using the 'OutObject' helper class unless the method + // is within the code being modified: + root.argValue.Clone(out tempCursor3).Find(row, "prices.0.0.0"); + tangible.RefObject tempRef_tempCursor3 = new tangible.RefObject(tempCursor3); + ResultAssert.IsSuccess(itemLayout.WriteSparse(row, tempRef_tempCursor3, innerItem)); + tempCursor3 = tempRef_tempCursor3.argValue; + tangible.RefObject tempRef_in3Scope = new tangible.RefObject(in3Scope); + tangible.RefObject tempRef_tempCursor32 = new tangible.RefObject(tempCursor3); + ResultAssert.IsSuccess(in3Layout.MoveField(row, tempRef_in3Scope, tempRef_tempCursor32)); + tempCursor3 = tempRef_tempCursor32.argValue; + in3Scope = tempRef_in3Scope.argValue; + } + + tangible.RefObject tempRef_in2Scope = + new tangible.RefObject(in2Scope); + tangible.RefObject tempRef_tempCursor23 = new tangible.RefObject(tempCursor2); + ResultAssert.IsSuccess(in2Layout.MoveField(row, tempRef_in2Scope, tempRef_tempCursor23)); + tempCursor2 = tempRef_tempCursor23.argValue; + in2Scope = tempRef_in2Scope.argValue; + } + + tangible.RefObject tempRef_nestedScope = + new tangible.RefObject(nestedScope); + tangible.RefObject tempRef_tempCursor12 = + new tangible.RefObject(tempCursor1); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_nestedScope, + tempRef_tempCursor12)); + tempCursor1 = tempRef_tempCursor12.argValue; + nestedScope = tempRef_nestedScope.argValue; + } + } + + if (value.Shopping != null) { + tangible.OutObject tempOut_c6 = + new tangible.OutObject(); + assert this.layout.TryFind("shopping", tempOut_c6); + c = tempOut_c6.argValue; + RowCursor shoppingScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out shoppingScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref shoppingScope, + c.getTypeArgs().clone(), out shoppingScope)); + for (ShoppingItem item : value.Shopping) { + TypeArgument innerType = c.getTypeArgs().get(0).clone(); + LayoutUDT innerLayout = innerType.getType().TypeAs(); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + tangible.RefObject tempRef_tempCursor6 = + new tangible.RefObject(tempCursor); + RowCursor itemScope; + tangible.OutObject tempOut_itemScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(innerLayout.WriteScope(row, tempRef_tempCursor6, + innerType.getTypeArgs().clone(), tempOut_itemScope)); + itemScope = tempOut_itemScope.argValue; + tempCursor = tempRef_tempCursor6.argValue; + tangible.RefObject tempRef_itemScope = + new tangible.RefObject(itemScope); + TypedSetUnitTests.WriteShoppingItem(row, tempRef_itemScope, innerType.getTypeArgs().clone(), item); + itemScope = tempRef_itemScope.argValue; + tangible.RefObject tempRef_shoppingScope = + new tangible.RefObject(shoppingScope); + tangible.RefObject tempRef_tempCursor7 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_shoppingScope, + tempRef_tempCursor7)); + tempCursor = tempRef_tempCursor7.argValue; + shoppingScope = tempRef_shoppingScope.argValue; + } + } + + if (value.Work != null) { + tangible.OutObject tempOut_c7 = + new tangible.OutObject(); + assert this.layout.TryFind("work", tempOut_c7); + c = tempOut_c7.argValue; + RowCursor workScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + root.argValue.Clone(out workScope).Find(row, c.getPath()); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + ResultAssert.IsSuccess(c.TypeAs().WriteScope(row, ref workScope, + c.getTypeArgs().clone(), out workScope)); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: foreach (Tuple item in value.Work) + for (Tuple item : value.Work) { + TypeArgument innerType = c.getTypeArgs().get(0).clone(); + LayoutIndexedScope innerLayout = innerType.getType().TypeAs(); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + root.argValue.Clone(out tempCursor).Find(row, Utf8String.Empty); + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - + // these cannot be converted using the 'OutObject' helper class unless the method is within the code + // being modified: + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - + // these cannot be converted using the 'RefObject' helper class unless the method is within the code + // being modified: + ResultAssert.IsSuccess(innerLayout.WriteScope(row, ref tempCursor, innerType.getTypeArgs().clone(), + out tupleScope)); + tangible.RefObject tempRef_tupleScope = + new tangible.RefObject(tupleScope); + ResultAssert.IsSuccess(innerType.getTypeArgs().get(0).getType().TypeAs().WriteSparse(row, tempRef_tupleScope, item.Item1)); + tupleScope = tempRef_tupleScope.argValue; + assert tupleScope.MoveNext(row); + tangible.RefObject tempRef_tupleScope2 = + new tangible.RefObject(tupleScope); + ResultAssert.IsSuccess(innerType.getTypeArgs().get(1).getType().TypeAs().WriteSparse(row, tempRef_tupleScope2, item.Item2)); + tupleScope = tempRef_tupleScope2.argValue; + tangible.RefObject tempRef_workScope = + new tangible.RefObject(workScope); + tangible.RefObject tempRef_tempCursor8 = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(c.TypeAs().MoveField(row, tempRef_workScope, + tempRef_tempCursor8)); + tempCursor = tempRef_tempCursor8.argValue; + workScope = tempRef_workScope.argValue; + } + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test types.")] private sealed class ShoppingItem + private final static class ShoppingItem { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public byte Count; + public byte Count; + public String Label; + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof ShoppingItem; + ShoppingItem shoppingItem = tempVar ? (ShoppingItem)obj : null; + return tempVar && this.equals(shoppingItem); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: return (this.Label.GetHashCode() * 397) ^ this.Count.GetHashCode(); + return (this.Label.hashCode() * 397) ^ (new Byte(this.Count)).hashCode(); + } + } + + private boolean equals(ShoppingItem other) { + return this.Label.equals(other.Label) && this.Count == other.Count; + } + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1401", Justification = "Test types.")] private sealed class Todo + private final static class Todo { + public ArrayList Attendees; + public ArrayList Checkboxes; + public ArrayList>> Nested; + public ArrayList> Prices; + public ArrayList Projects; + public ArrayList Shopping; + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: public List> Work; + public ArrayList> Work; + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + boolean tempVar = obj instanceof Todo; + Todo todo = tempVar ? (Todo)obj : null; + return tempVar && this.equals(todo); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + int hashCode = 0; + hashCode = (hashCode * 397) ^ (this.Attendees == null ? null : this.Attendees.hashCode() != null ? this.Attendees.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Projects == null ? null : this.Projects.hashCode() != null ? this.Projects.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Checkboxes == null ? null : this.Checkboxes.hashCode() != null ? this.Checkboxes.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Prices == null ? null : this.Prices.hashCode() != null ? this.Prices.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Nested == null ? null : this.Nested.hashCode() != null ? this.Nested.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Shopping == null ? null : this.Shopping.hashCode() != null ? this.Shopping.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Work == null ? null : this.Work.hashCode() != null ? this.Work.hashCode() : 0); + return hashCode; + } + } + + private static boolean NestedNestedSetEquals(ArrayList>> left, ArrayList>> right) { + if (left.size() != right.size()) { + return false; + } + + for (int i = 0; i < left.size(); i++) { + if (!Todo.NestedSetEquals(left.get(i), right.get(i))) { + return false; + } + } + + return true; + } + + private static boolean NestedSetEquals(ArrayList> left, ArrayList> right) { + if (left.size() != right.size()) { + return false; + } + + for (int i = 0; i < left.size(); i++) { + if (!Todo.SetEquals(left.get(i), right.get(i))) { + return false; + } + } + + return true; + } + + private static boolean SetEquals(ArrayList left, ArrayList right) { + if (left.size() != right.size()) { + return false; + } + + for (T item : left) { + if (!right.contains(item)) { + return false; + } + } + + return true; + } + + private boolean equals(Todo other) { + return (this.Attendees == other.Attendees || ((this.Attendees != null) && (other.Attendees != null) && Todo.SetEquals(this.Attendees, other.Attendees))) && (this.Projects == other.Projects || ((this.Projects != null) && (other.Projects != null) && Todo.SetEquals(this.Projects, other.Projects))) && (this.Checkboxes == other.Checkboxes || ((this.Checkboxes != null) && (other.Checkboxes != null) && Todo.SetEquals(this.Checkboxes, other.Checkboxes))) && (this.Prices == other.Prices || ((this.Prices != null) && (other.Prices != null) && Todo.NestedSetEquals(this.Prices, other.Prices))) && (this.Nested == other.Nested || ((this.Nested != null) && (other.Nested != null) && Todo.NestedNestedSetEquals(this.Nested, other.Nested))) && (this.Shopping == other.Shopping || ((this.Shopping != null) && (other.Shopping != null) && Todo.SetEquals(this.Shopping, other.Shopping))) && (this.Work == other.Work || ((this.Work != null) && (other.Work != null) && Todo.SetEquals(this.Work, other.Work))); + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/UpdateOptionsUnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/UpdateOptionsUnitTests.java new file mode 100644 index 0000000..6e558dc --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/UpdateOptionsUnitTests.java @@ -0,0 +1,21 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.RowOptions; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass] public class UpdateOptionsUnitTests +public class UpdateOptionsUnitTests { + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void UpdateOptionsTest() + public final void UpdateOptionsTest() { + assert RowOptions.None.getValue() == UpdateOptions.None.getValue(); + assert RowOptions.Update.getValue() == UpdateOptions.Update.getValue(); + assert RowOptions.Insert.getValue() == UpdateOptions.Insert.getValue(); + assert RowOptions.Upsert.getValue() == UpdateOptions.Upsert.getValue(); + assert RowOptions.InsertAt.getValue() == UpdateOptions.InsertAt.getValue(); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/WriteRowDispatcher.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/WriteRowDispatcher.java new file mode 100644 index 0000000..bc0a443 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/WriteRowDispatcher.java @@ -0,0 +1,242 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit; + +import azure.data.cosmos.serialization.hybridrow.RowCursor; + +import java.util.List; +import java.util.UUID; + +//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class may differ +// from the original: +//ORIGINAL LINE: internal struct WriteRowDispatcher : IDispatcher +public final class WriteRowDispatcher implements IDispatcher { + + public , TValue> void Dispatch(tangible.RefObject dispatcher, tangible.RefObject field, LayoutColumn col, LayoutType t) { + Dispatch(dispatcher, field, col, t, null); + } + + //C# TO JAVA CONVERTER NOTE: Java does not support optional parameters. Overloaded method(s) are created above: + //ORIGINAL LINE: public void Dispatch(ref RowOperationDispatcher dispatcher, ref RowCursor + // field, LayoutColumn col, LayoutType t, TValue value = default) where TLayout : LayoutType + public , TValue> void Dispatch(tangible.RefObject dispatcher, tangible.RefObject field, LayoutColumn col, LayoutType t, TValue value) { + switch (col == null ? null : col.getStorage()) { + case Fixed: + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + ResultAssert.IsSuccess(t.TypeAs().WriteFixed(tempRef_Row, field, col, value)); + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + break; + case Variable: + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + ResultAssert.IsSuccess(t.TypeAs().WriteVariable(tempRef_Row2, field, col, value)); + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + break; + default: + tangible.RefObject tempRef_Row3 = + new tangible.RefObject(dispatcher.argValue.Row); + ResultAssert.IsSuccess(t.TypeAs().WriteSparse(tempRef_Row3, field, value)); + dispatcher.argValue.argValue.Row = tempRef_Row3.argValue; + break; + } + } + + public void DispatchArray(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 1); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor arrayScope; + tangible.OutObject tempOut_arrayScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().WriteScope(tempRef_Row, scope, typeArgs.clone(), + tempOut_arrayScope)); + arrayScope = tempOut_arrayScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + + List items = (List)value; + for (Object item : items) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + dispatcher.argValue.LayoutCodeSwitch(ref arrayScope, null, typeArgs.get(0).getType(), + typeArgs.get(0).getTypeArgs().clone(), item); + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + arrayScope.MoveNext(tempRef_Row2); + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + } + } + + public void DispatchMap(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 2); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor mapScope; + tangible.OutObject tempOut_mapScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().WriteScope(tempRef_Row, scope, typeArgs.clone(), + tempOut_mapScope)); + mapScope = tempOut_mapScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + tangible.RefObject tempRef_mapScope = + new tangible.RefObject(mapScope); + TypeArgument fieldType = t.TypeAs().FieldType(tempRef_mapScope).clone(); + mapScope = tempRef_mapScope.argValue; + List pairs = (List)value; + for (Object pair : pairs) { + String elmPath = UUID.NewGuid().toString(); + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + RowCursor.CreateForAppend(tempRef_Row2, out tempCursor); + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + dispatcher.argValue.LayoutCodeSwitch(ref tempCursor, elmPath, fieldType.getType(), + fieldType.getTypeArgs().clone(), pair); + + // Move item into the map. + tangible.RefObject tempRef_Row3 = + new tangible.RefObject(dispatcher.argValue.Row); + tangible.RefObject tempRef_mapScope2 = + new tangible.RefObject(mapScope); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(t.TypeAs().MoveField(tempRef_Row3, tempRef_mapScope2, + tempRef_tempCursor)); + tempCursor = tempRef_tempCursor.argValue; + mapScope = tempRef_mapScope2.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row3.argValue; + } + } + + public void DispatchNullable(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 1); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor nullableScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(t.TypeAs().WriteScope(tempRef_Row, scope, typeArgs.clone(), + value != null, out nullableScope)); + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + + if (value != null) { + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + dispatcher.argValue.LayoutCodeSwitch(ref nullableScope, null, typeArgs.get(0).getType(), + typeArgs.get(0).getTypeArgs().clone(), value); + } + } + + public void DispatchObject(tangible.RefObject dispatcher, + tangible.RefObject scope) { + } + + public void DispatchSet(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() == 1); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor setScope; + tangible.OutObject tempOut_setScope = + new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().WriteScope(tempRef_Row, scope, typeArgs.clone(), + tempOut_setScope)); + setScope = tempOut_setScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + List items = (List)value; + for (Object item : items) { + String elmPath = UUID.NewGuid().toString(); + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor tempCursor; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being + // modified: + RowCursor.CreateForAppend(tempRef_Row2, out tempCursor); + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + dispatcher.argValue.LayoutCodeSwitch(ref tempCursor, elmPath, typeArgs.get(0).getType(), + typeArgs.get(0).getTypeArgs().clone(), item); + + // Move item into the set. + tangible.RefObject tempRef_Row3 = + new tangible.RefObject(dispatcher.argValue.Row); + tangible.RefObject tempRef_setScope = + new tangible.RefObject(setScope); + tangible.RefObject tempRef_tempCursor = + new tangible.RefObject(tempCursor); + ResultAssert.IsSuccess(t.TypeAs().MoveField(tempRef_Row3, tempRef_setScope, + tempRef_tempCursor)); + tempCursor = tempRef_tempCursor.argValue; + setScope = tempRef_setScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row3.argValue; + } + } + + public void DispatchTuple(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + Contract.Requires(typeArgs.getCount() >= 2); + + tangible.RefObject tempRef_Row = + new tangible.RefObject(dispatcher.argValue.Row); + RowCursor tupleScope; + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'out' keyword - these + // cannot be converted using the 'OutObject' helper class unless the method is within the code being modified: + ResultAssert.IsSuccess(t.TypeAs().WriteScope(tempRef_Row, scope, typeArgs.clone(), + out tupleScope)); + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + + for (int i = 0; i < typeArgs.getCount(); i++) { + PropertyInfo valueAccessor = value.getClass().GetProperty(String.format("Item%1$s", i + 1)); + // TODO: C# TO JAVA CONVERTER: The following method call contained an unresolved 'ref' keyword - these + // cannot be converted using the 'RefObject' helper class unless the method is within the code being + // modified: + dispatcher.argValue.LayoutCodeSwitch(ref tupleScope, null, typeArgs.get(i).getType(), + typeArgs.get(i).getTypeArgs().clone(), valueAccessor.GetValue(value)); + tangible.RefObject tempRef_Row2 = + new tangible.RefObject(dispatcher.argValue.Row); + tupleScope.MoveNext(tempRef_Row2); + dispatcher.argValue.argValue.Row = tempRef_Row2.argValue; + } + } + + public void DispatchUDT(tangible.RefObject dispatcher, + tangible.RefObject scope, LayoutType t, TypeArgumentList typeArgs, + Object value) { + tangible.RefObject tempRef_Row = new tangible.RefObject(dispatcher.argValue.Row); + RowCursor udtScope; + tangible.OutObject tempOut_udtScope = new tangible.OutObject(); + ResultAssert.IsSuccess(t.TypeAs().WriteScope(tempRef_Row, scope, typeArgs.clone(), tempOut_udtScope)); + udtScope = tempOut_udtScope.argValue; + dispatcher.argValue.argValue.Row = tempRef_Row.argValue; + IDispatchable valueDispatcher = value instanceof IDispatchable ? (IDispatchable)value : null; + assert valueDispatcher != null; + tangible.RefObject tempRef_udtScope = new tangible.RefObject(udtScope); + valueDispatcher.Dispatch(dispatcher, tempRef_udtScope); + udtScope = tempRef_udtScope.argValue; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Address.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Address.java new file mode 100644 index 0000000..55e2b71 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Address.java @@ -0,0 +1,48 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit.customerschema; + +import azure.data.cosmos.serialization.hybridrow.Tests.Unit.*; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Fields should be private + + +public final class Address { + public String City; + public PostalCode PostalCode; + public String State; + public String Street; + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + return obj instanceof Address && this.equals((Address)obj); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + int hashCode = this.Street != null ? this.Street.hashCode() : 0; + hashCode = (hashCode * 397) ^ (this.City != null ? this.City.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.State != null ? this.State.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.PostalCode != null ? this.PostalCode.hashCode() : 0); + return hashCode; + } + } + + private boolean equals(Address other) { + return this.Street.equals(other.Street) && this.City.equals(other.City) && this.State.equals(other.State) && this.PostalCode.equals(other.PostalCode); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/AddressSerializer.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/AddressSerializer.java new file mode 100644 index 0000000..2e92f21 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/AddressSerializer.java @@ -0,0 +1,94 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit.customerschema; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.Tests.Unit.*; + +public final class AddressSerializer { + public static Result Read(tangible.RefObject reader, tangible.OutObject
obj) { + obj.argValue = new Address(); + while (reader.argValue.Read()) { + Result r; + switch (reader.argValue.getPath()) { + case "street": + tangible.OutObject tempOut_Street = new tangible.OutObject(); + r = reader.argValue.ReadString(tempOut_Street); + obj.argValue.argValue.Street = tempOut_Street.argValue; + if (r != Result.Success) { + return r; + } + + break; + case "city": + tangible.OutObject tempOut_City = new tangible.OutObject(); + r = reader.argValue.ReadString(tempOut_City); + obj.argValue.argValue.City = tempOut_City.argValue; + if (r != Result.Success) { + return r; + } + + break; + case "state": + tangible.OutObject tempOut_State = new tangible.OutObject(); + r = reader.argValue.ReadString(tempOut_State); + obj.argValue.argValue.State = tempOut_State.argValue; + if (r != Result.Success) { + return r; + } + + break; + case "postal_code": + tangible.RefObject tempRef_child = + new tangible.RefObject(child); + tangible.OutObject tempOut_PostalCode = new tangible.OutObject(); + // TODO: C# TO JAVA CONVERTER: The following lambda contained an unresolved 'ref' keyword - these are not converted by C# to Java Converter: + r = reader.argValue.ReadScope(obj.argValue, (ref RowReader child, Address parent) -> PostalCodeSerializer.Read(tempRef_child, tempOut_PostalCode)); + parent.PostalCode = tempOut_PostalCode.argValue; + child = tempRef_child.argValue; + + if (r != Result.Success) { + return r; + } + + break; + } + } + + return Result.Success; + } + + public static Result Write(tangible.RefObject writer, TypeArgument typeArg, Address obj) { + Result r; + if (obj.Street != null) { + r = writer.argValue.WriteString("street", obj.Street); + if (r != Result.Success) { + return r; + } + } + + if (obj.City != null) { + r = writer.argValue.WriteString("city", obj.City); + if (r != Result.Success) { + return r; + } + } + + if (obj.State != null) { + r = writer.argValue.WriteString("state", obj.State); + if (r != Result.Success) { + return r; + } + } + + if (obj.PostalCode != null) { + r = writer.argValue.WriteScope("postal_code", PostalCodeSerializer.TypeArg, obj.PostalCode, + PostalCodeSerializer.Write); + return r; + } + + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Guest.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Guest.java new file mode 100644 index 0000000..2c48cfb --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Guest.java @@ -0,0 +1,95 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit.customerschema; + +import azure.data.cosmos.serialization.hybridrow.Tests.Unit.*; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Fields should be private + + +public final class Guest { + public Map Addresses; + public String ConfirmNumber; + public Set Emails; + public String FirstName; + public UUID Id; + public String LastName; + public List PhoneNumbers; + public String Title; + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + return obj instanceof Guest && this.equals((Guest)obj); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + int hashCode = this.Id.hashCode(); + hashCode = (hashCode * 397) ^ (this.FirstName != null ? this.FirstName.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.LastName != null ? this.LastName.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Title != null ? this.Title.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Emails != null ? this.Emails.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.PhoneNumbers != null ? this.PhoneNumbers.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Addresses != null ? this.Addresses.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.ConfirmNumber != null ? this.ConfirmNumber.hashCode() : 0); + return hashCode; + } + } + + private static boolean DictionaryEquals(Map left, Map right) { + if (left == right) { + return true; + } + + if ((left == null) || (right == null)) { + return false; + } + + if (left.size() != right.size()) { + return false; + } + + for (Map.Entry p : left.entrySet()) { + TValue value; + if (!(right.containsKey(p.getKey()) && (value = right.get(p.getKey())) == value)) { + return false; + } + + if (!p.getValue().equals(value)) { + return false; + } + } + + return true; + } + + private boolean equals(Guest other) { + //C# TO JAVA CONVERTER WARNING: Java AbstractList 'equals' is not always identical to LINQ 'SequenceEqual': + //ORIGINAL LINE: return this.Id.Equals(other.Id) && string.Equals(this.FirstName, other.FirstName) && string + // .Equals(this.LastName, other.LastName) && string.Equals(this.Title, other.Title) && string.Equals(this + // .ConfirmNumber, other.ConfirmNumber) && ((this.Emails == other.Emails) || ((this.Emails != null) && (other + // .Emails != null) && this.Emails.SetEquals(other.Emails))) && ((this.PhoneNumbers == other.PhoneNumbers) || + // ((this.PhoneNumbers != null) && (other.PhoneNumbers != null) && this.PhoneNumbers.SequenceEqual(other + // .PhoneNumbers))) && Guest.DictionaryEquals(this.Addresses, other.Addresses); + return this.Id.equals(other.Id) && this.FirstName.equals(other.FirstName) && this.LastName.equals(other.LastName) && this.Title.equals(other.Title) && this.ConfirmNumber.equals(other.ConfirmNumber) && ((this.Emails == other.Emails) || ((this.Emails != null) && (other.Emails != null) && this.Emails.equals(other.Emails))) && ((this.PhoneNumbers == other.PhoneNumbers) || ((this.PhoneNumbers != null) && (other.PhoneNumbers != null) && this.PhoneNumbers.equals(other.PhoneNumbers))) && Guest.DictionaryEquals(this.Addresses, other.Addresses); + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Hotel.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Hotel.java new file mode 100644 index 0000000..d57a32f --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/Hotel.java @@ -0,0 +1,51 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit.customerschema; + +import azure.data.cosmos.serialization.hybridrow.Tests.Unit.*; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Fields should be private + + +public final class Hotel { + public Address Address; + public String Id; + public String Name; + public String Phone; + + public boolean equals(Hotel other) { + return this.Id.equals(other.Id) && this.Name.equals(other.Name) && this.Phone.equals(other.Phone) && this.Address.equals(other.Address); + } + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + return obj instanceof Hotel && this.equals((Hotel)obj); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + int hashCode = this.Id == null ? null : this.Id.hashCode() != null ? this.Id.hashCode() : 0; + hashCode = (hashCode * 397) ^ (this.Name == null ? null : this.Name.hashCode() != null ? + this.Name.hashCode() : 0); + hashCode = (hashCode * 397) ^ (this.Phone == null ? null : this.Phone.hashCode() != null ? + this.Phone.hashCode() : 0); + int tempVar = this.Address.GetHashCode(); + hashCode = (hashCode * 397) ^ (this.Address == null ? null : tempVar != null ? tempVar : 0); + return hashCode; + } + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/PostalCode.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/PostalCode.java new file mode 100644 index 0000000..87f150e --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/PostalCode.java @@ -0,0 +1,42 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit.customerschema; + +import azure.data.cosmos.serialization.hybridrow.Tests.Unit.*; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Fields should be private + + +public final class PostalCode { + public Short Plus4; + public int Zip; + + @Override + public boolean equals(Object obj) { + if (null == obj) { + return false; + } + + if (this == obj) { + return true; + } + + return obj instanceof PostalCode && this.equals((PostalCode)obj); + } + + @Override + public int hashCode() { + // TODO: C# TO JAVA CONVERTER: There is no equivalent to an 'unchecked' block in Java: + unchecked + { + return (this.Zip * 397) ^ this.Plus4.hashCode(); + } + } + + private boolean equals(PostalCode other) { + return this.Zip == other.Zip && this.Plus4 == other.Plus4; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/PostalCodeSerializer.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/PostalCodeSerializer.java new file mode 100644 index 0000000..d1aa0a1 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/customerschema/PostalCodeSerializer.java @@ -0,0 +1,63 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit.customerschema; + +import azure.data.cosmos.serialization.hybridrow.Result; +import azure.data.cosmos.serialization.hybridrow.SchemaId; +import azure.data.cosmos.serialization.hybridrow.Tests.Unit.*; + +// TODO: C# TO JAVA CONVERTER: There is no preprocessor in Java: +///#pragma warning disable SA1401 // Fields should be private + + +public final class PostalCodeSerializer { + public static TypeArgument TypeArg = new TypeArgument(LayoutType.UDT, new TypeArgumentList(new SchemaId(1))); + + public static Result Read(tangible.RefObject reader, tangible.OutObject obj) { + obj.argValue = new PostalCode(); + while (reader.argValue.Read()) { + Result r; + switch (reader.argValue.getPath()) { + case "zip": + tangible.OutObject tempOut_Zip = new tangible.OutObject(); + r = reader.argValue.ReadInt32(tempOut_Zip); + obj.argValue.argValue.Zip = tempOut_Zip.argValue; + if (r != Result.Success) { + return r; + } + + break; + case "plus4": + short value; + tangible.OutObject tempOut_value = new tangible.OutObject(); + r = reader.argValue.ReadInt16(tempOut_value); + value = tempOut_value.argValue; + if (r != Result.Success) { + return r; + } + + obj.argValue.Plus4 = value; + break; + } + } + + return Result.Success; + } + + public static Result Write(tangible.RefObject writer, TypeArgument typeArg, PostalCode obj) { + Result r; + r = writer.argValue.WriteInt32("zip", obj.Zip); + if (r != Result.Success) { + return r; + } + + if (obj.Plus4.HasValue) { + r = writer.argValue.WriteInt16("plus4", obj.Plus4.Value); + return r; + } + + return Result.Success; + } +} \ No newline at end of file diff --git a/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/internal/MurmurHash3UnitTests.java b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/internal/MurmurHash3UnitTests.java new file mode 100644 index 0000000..2ed3034 --- /dev/null +++ b/jre/src/test/java/azure/data/cosmos/serialization/hybridrow/unit/internal/MurmurHash3UnitTests.java @@ -0,0 +1,112 @@ +//------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All rights reserved. +//------------------------------------------------------------ + +package azure.data.cosmos.serialization.hybridrow.unit.internal; + +import azure.data.cosmos.serialization.hybridrow.Tests.Unit.*; + +import java.util.Random; + +// TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: +//ORIGINAL LINE: [TestClass] public class MurmurHash3UnitTests +public class MurmurHash3UnitTests { + { + (0x56F1549659CBEE1A, 0xCEB3EE124C3E3855),(0xFE84B58886F9D717, 0xD24C5DE024F5EA6B), + (0x89F6250648BB11BF, 0x95595FB9D4CF58B0),(0xC76AFDB39EDC6262, 0xB9286AF4FADAF497), + (0xC2CB4D9B3C9C247E, 0xB465D40116B8B7A2),(0x317178F5B26D0B35, 0x1D564F53E2E468AD), + (0xE8D75F7C05F43F09, 0xA81CEA052AE92D6F),(0x8F837665508C08A8, 0x2A74E6E47E5497BC), + (0x609778FDA1AFD731, 0x3EB1A0E3BFC653E4),(0x0F59B8965FA49D1A, 0xCB3BC158243A5DEE), + (0x7A6D0AC9C98F5908, 0xBC93D3042C3E7178),(0x863FE5AEBA9A3DFA, 0xDF42416658CB87C5), + (0xDB4C82337C8FB216, 0xCA7616B64ABF6B3D),(0x0049223177425B48, 0x25510D7246BC3C2C), + (0x31AC129B24F82CAB, 0xCD7174C2040E9834),(0xCE39465288116345, 0x1CE6A26BA2E9E67D), + (0xD2BE55791E13DB17, 0xCF30BF3D93B3A9FA),(0x43E323DD0F079145, 0xF06721555571ABBA), + (0xB0CE9F170A96F5BC, 0x18EE95960369D702),(0xBFFAF6BEBC84A2A9, 0xE0612B6FC0C9D502), + (0x33E2D699697BC2DA, 0xB7E9CD6313DE05EE),(0xCBFD7D8DA2A962BF, 0xCF4C281A7750E88A), + (0xBD8D863F83863088, 0x01AFFBDE3D405D35),(0xBA2E05DF3328C7DB, 0x9620867ADDFE6579), + (0xC57BD1FB63CA0947, 0xE1391F8454D4EA9F),(0x6AB710460A5BF9BA, 0x11D7E13FBEF63775), + (0x55C2C7C95F41C483, 0xA4DCC9F547A89563),(0x8AA5A2031027F216, 0x1653FC7AD6CC6104), + (0xAD8A899FF093D9A5, 0x0EB26F6D1CCEB258),(0xA3B6D57EBEB965D1, 0xE8078FCC5D8C2E3E), + (0x91ABF587B38224F6, 0x35899665A8A9252C),(0xF05B1AF0487EE2D4, 0x5D7496C1665DDE12)} =new Object[] + +//C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: private static readonly(ulong low, ulong high)[] Expected = new[] { (0x56F1549659CBEE1AUL, + // 0xCEB3EE124C3E3855UL), (0xFE84B58886F9D717UL, 0xD24C5DE024F5EA6BUL), (0x89F6250648BB11BFUL, + // 0x95595FB9D4CF58B0UL), (0xC76AFDB39EDC6262UL, 0xB9286AF4FADAF497UL), (0xC2CB4D9B3C9C247EUL, + // 0xB465D40116B8B7A2UL), (0x317178F5B26D0B35UL, 0x1D564F53E2E468ADUL), (0xE8D75F7C05F43F09UL, + // 0xA81CEA052AE92D6FUL), (0x8F837665508C08A8UL, 0x2A74E6E47E5497BCUL), (0x609778FDA1AFD731UL, + // 0x3EB1A0E3BFC653E4UL), (0x0F59B8965FA49D1AUL, 0xCB3BC158243A5DEEUL), (0x7A6D0AC9C98F5908UL, + // 0xBC93D3042C3E7178UL), (0x863FE5AEBA9A3DFAUL, 0xDF42416658CB87C5UL), (0xDB4C82337C8FB216UL, + // 0xCA7616B64ABF6B3DUL), (0x0049223177425B48UL, 0x25510D7246BC3C2CUL), (0x31AC129B24F82CABUL, + // 0xCD7174C2040E9834UL), (0xCE39465288116345UL, 0x1CE6A26BA2E9E67DUL), (0xD2BE55791E13DB17UL, + // 0xCF30BF3D93B3A9FAUL), (0x43E323DD0F079145UL, 0xF06721555571ABBAUL), (0xB0CE9F170A96F5BCUL, + // 0x18EE95960369D702UL), (0xBFFAF6BEBC84A2A9UL, 0xE0612B6FC0C9D502UL), (0x33E2D699697BC2DAUL, + // 0xB7E9CD6313DE05EEUL), (0xCBFD7D8DA2A962BFUL, 0xCF4C281A7750E88AUL), (0xBD8D863F83863088UL, + // 0x01AFFBDE3D405D35UL), (0xBA2E05DF3328C7DBUL, 0x9620867ADDFE6579UL), (0xC57BD1FB63CA0947UL, + // 0xE1391F8454D4EA9FUL), (0x6AB710460A5BF9BAUL, 0x11D7E13FBEF63775UL), (0x55C2C7C95F41C483UL, + // 0xA4DCC9F547A89563UL), (0x8AA5A2031027F216UL, 0x1653FC7AD6CC6104UL), (0xAD8A899FF093D9A5UL, + // 0x0EB26F6D1CCEB258UL), (0xA3B6D57EBEB965D1UL, 0xE8078FCC5D8C2E3EUL), (0x91ABF587B38224F6UL, + // 0x35899665A8A9252CUL), (0xF05B1AF0487EE2D4UL, 0x5D7496C1665DDE12UL)}; + private static readonly(long low, long high)[] Expected + + ; + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [TestMethod][Owner("jthunter")] public void Hash128Check() + public final void Hash128Check() { + // Generate deterministic data for which the MurmurHash3 is known (see Expected). + Random rand = new Random(42); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: byte[][] samples = new byte[MurmurHash3UnitTests.Expected.Length][]; + byte[][] samples = new byte[MurmurHash3UnitTests.Expected.Length][]; + for (int i = 0; i < samples.length; i++) { + int sampleLength = rand.nextInt(10 * 1024); + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: samples[i] = new byte[sampleLength]; + samples[i] = new byte[sampleLength]; + rand.nextBytes(samples[i]); + } + + // Warm up the loop and verify correctness. + for (int i = 0; i < samples.length; i++) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: byte[] sample = samples[i]; + byte[] sample = samples[i]; + // TODO: C# TO JAVA CONVERTER: Java has no equivalent to C# deconstruction declarations: + ( long low, long high) =MurmurHash3.Hash128(sample, (0, 0)) + System.out.println(String.format("(0x%016XUL, 0x%1.16XUL),", high, low)); + assert MurmurHash3UnitTests.Expected[i].high == high; + assert MurmurHash3UnitTests.Expected[i].low == low; + } + + // Measure performance. + long ticks = MurmurHash3UnitTests.MeasureLoop(samples); + System.out.println(String.format("MurmurHash3: %1$s", ticks)); + } + + // TODO: C# TO JAVA CONVERTER: Java annotations will not correspond to .NET attributes: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.NoInlining)][SuppressMessage("Microsoft.Reliability", + // "CA2001:Avoid calling problematic methods", Justification = "Perf Benchmark")] private static long MeasureLoop + // (byte[][] samples) + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: [MethodImpl(MethodImplOptions.NoInlining)][SuppressMessage("Microsoft.Reliability", + // "CA2001:Avoid calling problematic methods", Justification = "Perf Benchmark")] private static long MeasureLoop + // (byte[][] samples) + private static long MeasureLoop(byte[][] samples) { + final int outerLoopCount = 10000; + System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); + + System.gc(); + watch.Start(); + for (int j = 0; j < outerLoopCount; j++) { + //C# TO JAVA CONVERTER WARNING: Unsigned integer types have no direct equivalent in Java: + //ORIGINAL LINE: foreach (byte[] sample in samples) + for (byte[] sample : samples) { + MurmurHash3.Hash128(sample, (0, 0)) + } + } + + watch.Stop(); + return watch.ElapsedTicks; + } +} \ No newline at end of file