public FhirJsonOutputFormatter( FhirJsonSerializer fhirJsonSerializer, ResourceDeserializer deserializer, ILogger <FhirJsonOutputFormatter> logger, ArrayPool <char> charPool, BundleSerializer bundleSerializer) { EnsureArg.IsNotNull(fhirJsonSerializer, nameof(fhirJsonSerializer)); EnsureArg.IsNotNull(deserializer, nameof(deserializer)); EnsureArg.IsNotNull(logger, nameof(logger)); EnsureArg.IsNotNull(charPool, nameof(charPool)); EnsureArg.IsNotNull(bundleSerializer, nameof(bundleSerializer)); _fhirJsonSerializer = fhirJsonSerializer; _deserializer = deserializer; _logger = logger; _charPool = new JsonArrayPool(charPool); _bundleSerializer = bundleSerializer; SupportedEncodings.Add(Encoding.UTF8); SupportedEncodings.Add(Encoding.Unicode); SupportedMediaTypes.Add(KnownContentTypes.JsonContentType); SupportedMediaTypes.Add(KnownMediaTypeHeaderValues.ApplicationJson); SupportedMediaTypes.Add(KnownMediaTypeHeaderValues.TextJson); SupportedMediaTypes.Add(KnownMediaTypeHeaderValues.ApplicationAnyJsonSyntax); }
public void GivenARawResourceOfUnknownType_WhenDeserializing_ThenANotSupportedExceptionIsThrown() { var raw = new RawResource("{}", ResourceFormat.Unknown); var wrapper = new ResourceWrapper("id1", "version1", "Observation", raw, new ResourceRequest("http://fhir", HttpMethod.Post), Clock.UtcNow, false, null, null); Assert.Throws <NotSupportedException>(() => ResourceDeserializer.Deserialize(wrapper)); }
public void DeserializesHasManyRelationship() { var target = new ResourceDeserializer(_singleJson, typeof(Person)); var result = target.Deserialize() as Person; var expectedFriend = _person.Friends.Single(); var actualFriend = result?.Friends.Single(); Assert.Equal(expectedFriend.Identifier, actualFriend?.Identifier); Assert.Null(actualFriend?.FirstName); Assert.Null(actualFriend?.LastName); Assert.Equal(default(int?), actualFriend?.Age); Assert.Null(actualFriend?.Job); Assert.Null(actualFriend?.Friends); var expectedFamilyMembers = _person.FamilyMembers.ToArray(); var actualFamilyMembers = result?.FamilyMembers?.ToArray(); Assert.NotNull(actualFamilyMembers); Assert.Equal(expectedFamilyMembers.Length, actualFamilyMembers.Length); expectedFamilyMembers.Zip(actualFamilyMembers, (expected, actual) => { Assert.Equal(expected.Identifier, actual.Identifier); return(true); }); }
public void ValidatesTopLevelMemberExclusivity() { var content = FileAsJson("invalid-top-level.json"); var target = new ResourceDeserializer(content, typeof(Person)); Assert.Throws <JsonApiException>(() => target.Deserialize()); }
public void ValidatesRootIsObject() { var content = FileAsJson("no-object-root.json"); var target = new ResourceDeserializer(content, typeof(Person)); Assert.Throws <JsonApiException>(() => target.Deserialize()); }
public void ValidatesMutuallyExclusiveTopLevelMembers() { var content = FileAsJson("errors-and-data.json"); var target = new ResourceDeserializer(content, typeof(Person)); Assert.Throws <JsonApiException>(() => target.Deserialize()); }
public void ValidatesNoIncludedWithoutData() { var content = FileAsJson("included-no-data.json"); var target = new ResourceDeserializer(content, typeof(Person)); Assert.Throws <JsonApiException>(() => target.Deserialize()); }
public void ValidatesRequiredTopLevelMembers() { var content = FileAsJson("no-data-errors-meta.json"); var target = new ResourceDeserializer(content, typeof(Person)); Assert.Throws <JsonApiException>(() => target.Deserialize()); }
public static Resource ToPoco(this RawResourceElement resource, ResourceDeserializer deserializer) { EnsureArg.IsNotNull(resource, nameof(resource)); EnsureArg.IsNotNull(deserializer, nameof(deserializer)); return(resource.ToPoco <Resource>(deserializer)); }
public ValidateController(IMediator mediator, ResourceDeserializer resourceDeserializer) { EnsureArg.IsNotNull(mediator, nameof(mediator)); _mediator = mediator; _resourceDeserializer = resourceDeserializer; }
private T GetResourceDefinition <T>(TagResourceReference resourceReference) { var tagResource = GetPageableResource(resourceReference).Resource; T result; byte[] resourceDefinitionData = tagResource.DefinitionData; ApplyResourceDefinitionFixups(tagResource, resourceDefinitionData); byte[] resourceRawData = GetResourceData(resourceReference); if (resourceRawData == null) { resourceRawData = new byte[0]; } // deserialize the resource definition again using (var definitionDataStream = new MemoryStream(resourceDefinitionData)) using (var definitionDataReader = new EndianReader(definitionDataStream, EndianFormat.LittleEndian)) using (var dataStream = new MemoryStream(resourceRawData)) using (var dataReader = new EndianReader(dataStream, EndianFormat.LittleEndian)) { var context = new ResourceDefinitionSerializationContext(dataReader, definitionDataReader, tagResource.DefinitionAddress.Type); var deserializer = new ResourceDeserializer(Cache.Version); // deserialize without access to the data definitionDataReader.SeekTo(tagResource.DefinitionAddress.Offset); result = deserializer.Deserialize <T>(context); } return(result); }
public ResourceHandlerTests() { _fhirDataStore = Substitute.For <IFhirDataStore>(); _conformanceProvider = Substitute.For <ConformanceProviderBase>(); _searchService = Substitute.For <ISearchService>(); // TODO: FhirRepository instantiate ResourceDeserializer class directly // which will try to deserialize the raw resource. We should mock it as well. _rawResourceFactory = Substitute.For <RawResourceFactory>(new FhirJsonSerializer()); _resourceWrapperFactory = Substitute.For <IResourceWrapperFactory>(); _resourceWrapperFactory .Create(Arg.Any <ResourceElement>(), Arg.Any <bool>(), Arg.Any <bool>()) .Returns(x => CreateResourceWrapper(x.ArgAt <ResourceElement>(0), x.ArgAt <bool>(1))); _conformanceStatement = CapabilityStatementMock.GetMockedCapabilityStatement(); CapabilityStatementMock.SetupMockResource(_conformanceStatement, ResourceType.Observation, null); var observationResource = _conformanceStatement.Rest.First().Resource.Find(x => x.Type == ResourceType.Observation); observationResource.ReadHistory = false; observationResource.UpdateCreate = true; observationResource.ConditionalCreate = true; observationResource.ConditionalUpdate = true; observationResource.Versioning = CapabilityStatement.ResourceVersionPolicy.Versioned; CapabilityStatementMock.SetupMockResource(_conformanceStatement, ResourceType.Patient, null); var patientResource = _conformanceStatement.Rest.First().Resource.Find(x => x.Type == ResourceType.Patient); patientResource.ReadHistory = true; patientResource.UpdateCreate = true; patientResource.ConditionalCreate = true; patientResource.ConditionalUpdate = true; patientResource.Versioning = CapabilityStatement.ResourceVersionPolicy.VersionedUpdate; _conformanceProvider.GetCapabilityStatementOnStartup().Returns(_conformanceStatement.ToTypedElement().ToResourceElement()); var lazyConformanceProvider = new Lazy <IConformanceProvider>(() => _conformanceProvider); var collection = new ServiceCollection(); // an auth service that allows all. _authorizationService = Substitute.For <IAuthorizationService <DataActions> >(); _authorizationService.CheckAccess(Arg.Any <DataActions>(), Arg.Any <CancellationToken>()).Returns(ci => ci.Arg <DataActions>()); var referenceResolver = new ResourceReferenceResolver(_searchService, new TestQueryStringParser()); _resourceIdProvider = new ResourceIdProvider(); collection.Add(x => _mediator).Singleton().AsSelf(); collection.Add(x => new CreateResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, referenceResolver, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces(); collection.Add(x => new UpsertResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, _authorizationService, ModelInfoProvider.Instance)).Singleton().AsSelf().AsImplementedInterfaces(); collection.Add(x => new ConditionalCreateResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _searchService, x.GetService <IMediator>(), _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces(); collection.Add(x => new ConditionalUpsertResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _searchService, x.GetService <IMediator>(), _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces(); collection.Add(x => new GetResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces(); collection.Add(x => new DeleteResourceHandler(_fhirDataStore, lazyConformanceProvider, _resourceWrapperFactory, _resourceIdProvider, _authorizationService)).Singleton().AsSelf().AsImplementedInterfaces(); ServiceProvider provider = collection.BuildServiceProvider(); _mediator = new Mediator(type => provider.GetService(type)); _deserializer = new ResourceDeserializer( (FhirResourceFormat.Json, new Func <string, string, DateTimeOffset, ResourceElement>((str, version, lastUpdated) => _fhirJsonParser.Parse(str).ToResourceElement()))); }
public ResourceToNdjsonBytesSerializer(ResourceDeserializer resourceDeserializer, FhirJsonSerializer fhirJsonSerializer) { EnsureArg.IsNotNull(resourceDeserializer, nameof(resourceDeserializer)); EnsureArg.IsNotNull(fhirJsonSerializer, nameof(fhirJsonSerializer)); _resourceDeserializer = resourceDeserializer; _fhirJsonSerializer = fhirJsonSerializer; }
public FhirStorageTests(FhirStorageTestsFixture fixture) { _fixture = fixture; _searchService = Substitute.For <ISearchService>(); _dataStore = fixture.DataStore; _conformance = CapabilityStatementMock.GetMockedCapabilityStatement(); CapabilityStatementMock.SetupMockResource(_conformance, ResourceType.Observation, null); var observationResource = _conformance.Rest[0].Resource.Find(r => r.Type == ResourceType.Observation); observationResource.UpdateCreate = true; observationResource.Versioning = CapabilityStatement.ResourceVersionPolicy.Versioned; CapabilityStatementMock.SetupMockResource(_conformance, ResourceType.Organization, null); var organizationResource = _conformance.Rest[0].Resource.Find(r => r.Type == ResourceType.Organization); organizationResource.UpdateCreate = true; organizationResource.Versioning = CapabilityStatement.ResourceVersionPolicy.NoVersion; var provider = Substitute.For <ConformanceProviderBase>(); provider.GetCapabilityStatementAsync().Returns(_conformance.ToTypedElement().ToResourceElement()); // TODO: FhirRepository instantiate ResourceDeserializer class directly // which will try to deserialize the raw resource. We should mock it as well. var rawResourceFactory = Substitute.For <RawResourceFactory>(new FhirJsonSerializer()); var resourceWrapperFactory = Substitute.For <IResourceWrapperFactory>(); resourceWrapperFactory .Create(Arg.Any <ResourceElement>(), Arg.Any <bool>(), Arg.Any <bool>()) .Returns(x => { ResourceElement resource = x.ArgAt <ResourceElement>(0); return(new ResourceWrapper(resource, rawResourceFactory.Create(resource, keepMeta: true), new ResourceRequest(HttpMethod.Post, "http://fhir"), x.ArgAt <bool>(1), null, null, null)); }); var collection = new ServiceCollection(); var resourceIdProvider = new ResourceIdProvider(); _searchParameterUtilities = Substitute.For <ISearchParameterUtilities>(); collection.AddSingleton(typeof(IRequestHandler <CreateResourceRequest, UpsertResourceResponse>), new CreateResourceHandler(_dataStore, new Lazy <IConformanceProvider>(() => provider), resourceWrapperFactory, resourceIdProvider, new ResourceReferenceResolver(_searchService, new TestQueryStringParser()), DisabledFhirAuthorizationService.Instance, _searchParameterUtilities)); collection.AddSingleton(typeof(IRequestHandler <UpsertResourceRequest, UpsertResourceResponse>), new UpsertResourceHandler(_dataStore, new Lazy <IConformanceProvider>(() => provider), resourceWrapperFactory, resourceIdProvider, DisabledFhirAuthorizationService.Instance, ModelInfoProvider.Instance)); collection.AddSingleton(typeof(IRequestHandler <GetResourceRequest, GetResourceResponse>), new GetResourceHandler(_dataStore, new Lazy <IConformanceProvider>(() => provider), resourceWrapperFactory, resourceIdProvider, DisabledFhirAuthorizationService.Instance)); collection.AddSingleton(typeof(IRequestHandler <DeleteResourceRequest, DeleteResourceResponse>), new DeleteResourceHandler(_dataStore, new Lazy <IConformanceProvider>(() => provider), resourceWrapperFactory, resourceIdProvider, DisabledFhirAuthorizationService.Instance)); ServiceProvider services = collection.BuildServiceProvider(); Mediator = new Mediator(type => services.GetService(type)); _deserializer = new ResourceDeserializer( (FhirResourceFormat.Json, new Func <string, string, DateTimeOffset, ResourceElement>((str, version, lastUpdated) => _fhirJsonParser.Parse(str).ToResourceElement()))); }
public FhirStorageTests(FhirStorageTestsFixture fixture) { _fixture = fixture; _capabilityStatement = fixture.CapabilityStatement; _deserializer = fixture.Deserializer; _dataStore = fixture.DataStore; _fhirJsonParser = fixture.JsonParser; _conformanceProvider = fixture.ConformanceProvider; Mediator = fixture.Mediator; }
public void DeserializesBelongsToRelationships() { var target = new ResourceDeserializer(_singleJson, typeof(Person)); var result = target.Deserialize() as Person; var job = result?.Job; Assert.Equal(_person.Job.Id, job?.Id); Assert.Null(job?.Name); Assert.Equal(0, job?.NumberOfEmployees); }
public static T ToPoco <T>(this RawResourceElement resource, ResourceDeserializer deserializer) where T : Resource { EnsureArg.IsNotNull(resource, nameof(resource)); EnsureArg.IsNotNull(deserializer, nameof(deserializer)); var deserialized = deserializer.DeserializeRawResourceElement(resource); return(deserialized.ToPoco <T>()); }
public BundleFactory(IUrlResolver urlResolver, IFhirRequestContextAccessor fhirRequestContextAccessor, ResourceDeserializer deserializer) { EnsureArg.IsNotNull(urlResolver, nameof(urlResolver)); EnsureArg.IsNotNull(fhirRequestContextAccessor, nameof(fhirRequestContextAccessor)); EnsureArg.IsNotNull(deserializer, nameof(deserializer)); _urlResolver = urlResolver; _fhirRequestContextAccessor = fhirRequestContextAccessor; _deserializer = deserializer; }
/// <summary> /// Converts json into an object of a specified type /// </summary> /// <param name="object">Json to convert</param> /// <param name="type">Type to convert to</param> /// <param name="config">The configuration to be used for deserialization</param> /// <returns>Json converted into the specified type of object</returns> public object Deserialize(JToken @object, Type type, JsonApiConfiguration config = null) { if (config == null) { config = new JsonApiConfiguration(); } var target = new ResourceDeserializer(@object, type, config.PropertyNameConverter); return target.Deserialize(); }
public void DeserializesBelongsToRelationshipsWithNullData() { var person = JToken.Parse("{'data': {'relationships': {'job': {data: null}}}}"); var target = new ResourceDeserializer(person, typeof(Person)); var result = target.Deserialize() as Person; var job = result?.Job; Assert.Null(job); }
public void DeserializesAttributes() { var target = new ResourceDeserializer(_singleJson, typeof(Person)); var result = target.Deserialize() as Person; Assert.Equal(_person.Identifier, result?.Identifier); Assert.Equal(_person.FirstName, result?.FirstName); Assert.Equal(_person.LastName, result?.LastName); Assert.Equal(_person.Age, result?.Age); }
public GetResourceHandler( IFhirDataStore fhirDataStore, Lazy <IConformanceProvider> conformanceProvider, IResourceWrapperFactory resourceWrapperFactory, ResourceDeserializer deserializer) : base(fhirDataStore, conformanceProvider, resourceWrapperFactory) { EnsureArg.IsNotNull(deserializer, nameof(deserializer)); _deserializer = deserializer; }
public void DeserializesEnumerables() { var target = new ResourceDeserializer(_collectionJson, typeof(Person[])); var result = target.Deserialize() as Person[]; Assert.Equal(_people.Length, result?.Length); for (var i = 0; i < _people.Length; i++) { Assert.Equal(_people[i].Identifier, result?[i].Identifier); } }
public void DeserializesWithoutId() { (_singleJson["data"] as JObject)?.Property("id").Remove(); var target = new ResourceDeserializer(_singleJson, typeof(Person)); var result = target.Deserialize() as Person; Assert.Equal(null, result?.Identifier); Assert.Equal(_person.FirstName, result?.FirstName); Assert.Equal(_person.LastName, result?.LastName); Assert.Equal(_person.Age, result?.Age); }
public Bundle CreateHistoryBundle(IEnumerable <Tuple <string, string> > unsupportedSearchParams, SearchResult result) { // Create the bundle from the result. var bundle = new Bundle(); if (result != null) { IEnumerable <Bundle.EntryComponent> entries = result.Results.Select(r => { Resource resource = ResourceDeserializer.Deserialize(r); var hasVerb = Enum.TryParse(r.Request?.Method, true, out Bundle.HTTPVerb httpVerb); return(new Bundle.EntryComponent { FullUrlElement = new FhirUri(_urlResolver.ResolveResourceUrl(resource, true)), Resource = resource, Request = new Bundle.RequestComponent { Method = hasVerb ? (Bundle.HTTPVerb?)httpVerb: null, Url = r.Request?.Url?.ToString(), }, Response = new Bundle.ResponseComponent { LastModified = r.LastModified, Etag = WeakETag.FromVersionId(r.Version).ToString(), }, }); }); bundle.Entry.AddRange(entries); if (result.ContinuationToken != null) { bundle.NextLink = _urlResolver.ResolveRouteUrl( _fhirRequestContextAccessor.FhirRequestContext.RouteName, unsupportedSearchParams, result.ContinuationToken); } } // Add the self link to indicate which search parameters were used. bundle.SelfLink = _urlResolver.ResolveRouteUrl(_fhirRequestContextAccessor.FhirRequestContext.RouteName, unsupportedSearchParams); bundle.Id = _fhirRequestContextAccessor.FhirRequestContext.CorrelationId; bundle.Type = Bundle.BundleType.History; bundle.Total = result?.TotalCount; bundle.Meta = new Meta { LastUpdated = Clock.UtcNow, }; return(bundle); }
public void GivenARawResource_WhenDeserializingFromJson_ThenTheObjectIsReturned() { var observation = Samples.GetDefaultObservation(); observation.Id = "id1"; var wrapper = new ResourceWrapper(observation, _rawResourceFactory.Create(observation), new ResourceRequest("http://fhir", HttpMethod.Post), false, null, null); var newObject = ResourceDeserializer.Deserialize(wrapper); Assert.Equal(observation.Id, newObject.Id); Assert.Equal(observation.VersionId, newObject.VersionId); }
public ReindexUtilities( Func <IScoped <IFhirDataStore> > fhirDataStoreFactory, ISearchIndexer searchIndexer, ResourceDeserializer deserializer) { EnsureArg.IsNotNull(fhirDataStoreFactory, nameof(fhirDataStoreFactory)); EnsureArg.IsNotNull(searchIndexer, nameof(searchIndexer)); EnsureArg.IsNotNull(deserializer, nameof(deserializer)); _fhirDataStoreFactory = fhirDataStoreFactory; _searchIndexer = searchIndexer; _deserializer = deserializer; }
public GroupMemberExtractor( IScoped <IFhirDataStore> fhirDataStore, ResourceDeserializer resourceDeserializer, IReferenceToElementResolver referenceToElementResolver) { EnsureArg.IsNotNull(fhirDataStore, nameof(fhirDataStore)); EnsureArg.IsNotNull(resourceDeserializer, nameof(resourceDeserializer)); EnsureArg.IsNotNull(referenceToElementResolver, nameof(referenceToElementResolver)); _fhirDataStore = fhirDataStore; _resourceDeserializer = resourceDeserializer; _referenceToElementResolver = referenceToElementResolver; }
public void TestStringListProps() { ResourceSerializer serializer = new ResourceSerializer(); IResource origin = _storage.NewResource("Email"); origin.SetProp(_propSize, 100); origin.SetProp(_propReceived, DateTime.Now); IStringList strLst = origin.GetStringListProp(_propValueList); using ( strLst ) { strLst.Add("One"); strLst.Add("Two"); strLst.Add("Three"); } origin.SetProp(_propUnread, true); origin.SetProp(_propSimilarity, 1.0); ResourceNode resNode = serializer.AddResource(origin); foreach (IResourceProperty prop in origin.Properties) { resNode.AddProperty(prop); } serializer.GenerateXML("SerializationResult.xml"); origin.Delete(); StreamReader sr = new StreamReader("SerializationResult.xml", Encoding.Default); string str = Utils.StreamReaderReadToEnd(sr); Console.WriteLine(str); sr.Close(); ResourceDeserializer deserializer = new ResourceDeserializer("SerializationResult.xml"); ArrayList list = deserializer.GetSelectedResources(); Assert.AreEqual(1, list.Count, "List must contain only one resource. Current count is [" + list.Count + "]"); ResourceUnpack ru = (ResourceUnpack)list[0]; origin = ru.Resource; Assert.IsTrue(origin.HasProp(_propValueList), "Resource must contain StringList property"); IStringList stringsList = origin.GetStringListProp(_propValueList); Assert.AreEqual(3, stringsList.Count, "StringList must contain three elements. Current count is [" + stringsList.Count + "]"); Assert.AreEqual("One", stringsList [0], "StringList[ 0 ] must be equal to [One]. Current value is [" + stringsList[0] + "]"); Assert.AreEqual("Two", stringsList [1], "StringList[ 1 ] must be equal to [Two]. Current value is [" + stringsList[1] + "]"); Assert.AreEqual("Three", stringsList [2], "StringList[ 2 ] must be equal to [Three]. Current value is [" + stringsList[2] + "]"); }
private void PopulateTreeView() { ResourceDeserializer resSer = new ResourceDeserializer(_fileName); foreach (ResourceUnpack resourceNode in resSer.GetSelectedResources()) { int iconIndex = GetIcon(resourceNode.Resource); TreeNode node = new TreeNode(GetTypeDisplayName(resourceNode.Resource.Type) + ": " + resourceNode.Resource.DisplayName, iconIndex, iconIndex); node.Tag = resourceNode; _resourceTreeView.Nodes.Add(node); AddLinks(node, resourceNode); _resourceTreeView.SetNodeCheckState(node, NodeCheckState.Checked); node.Expand(); } }