コード例 #1
0
        public void GivenARawResourceOfUnknownType_WhenDeserializing_ThenANotSupportedExceptionIsThrown()
        {
            var raw     = new RawResource("{}", FhirResourceFormat.Unknown);
            var wrapper = new ResourceWrapper("id1", "version1", "Observation", raw, new ResourceRequest(HttpMethod.Post, "http://fhir"), Clock.UtcNow, false, null, null, null);

            Assert.Throws <NotSupportedException>(() => Deserializers.ResourceDeserializer.Deserialize(wrapper));
        }
コード例 #2
0
        /// <summary>
        /// Client for making requests to the API.
        /// </summary>
        /// <param name="authHandler">The authentication handler.</param>
        /// <param name="ctx">The HTTP context to use for this session.</param>
        private Client(Func <CancellationToken, Task <string> > authHandler, HttpContext ctx)
        {
            // Setup resources.
            Assets              = new AssetsResource(authHandler, ctx);
            TimeSeries          = new TimeSeriesResource(authHandler, ctx);
            DataPoints          = new DataPointsResource(authHandler, ctx);
            Events              = new EventsResource(authHandler, ctx);
            Sequences           = new SequencesResource(authHandler, ctx);
            Raw                 = new RawResource(authHandler, ctx);
            Relationships       = new RelationshipResource(authHandler, ctx);
            DataSets            = new DataSetsResource(authHandler, ctx);
            ThreeDModels        = new ThreeDModelsResource(authHandler, ctx);
            ThreeDRevisions     = new ThreeDRevisionsResource(authHandler, ctx);
            ThreeDAssetMappings = new ThreeDAssetMappingsResource(authHandler, ctx);
            Files               = new FilesResource(authHandler, ctx);
            Login               = new LoginResource(authHandler, ctx);
            Token               = new TokenResource(authHandler, ctx);
            ExtPipes            = new ExtPipesResource(authHandler, ctx);
            Labels              = new LabelsResource(authHandler, ctx);
            Groups              = new GroupsResource(authHandler, ctx);

            // Playground features (experimental)
            Playground = new PlaygroundResource(authHandler, ctx);
            // Beta features (experimental)
            Beta = new BetaResource(authHandler, ctx);
        }
コード例 #3
0
        public async Task DeleteSearchParameterAsync(RawResource searchParamResource)
        {
            try
            {
                var searchParam        = _modelInfoProvider.ToTypedElement(searchParamResource);
                var searchParameterUrl = searchParam.GetStringScalar("url");

                // First we delete the status metadata from the data store as this fuction depends on the
                // the in memory definition manager.  Once complete we remove the SearchParameter from
                // the definition manager.
                await _searchParameterStatusManager.DeleteSearchParameterStatusAsync(searchParameterUrl);

                _searchParameterDefinitionManager.DeleteSearchParameter(searchParam);
            }
            catch (FhirException fex)
            {
                fex.Issues.Add(new OperationOutcomeIssue(
                                   OperationOutcomeConstants.IssueSeverity.Error,
                                   OperationOutcomeConstants.IssueType.Exception,
                                   Core.Resources.CustomSearchDeleteError));

                throw;
            }
            catch (Exception ex)
            {
                var customSearchException = new ConfigureCustomSearchException(Core.Resources.CustomSearchDeleteError);
                customSearchException.Issues.Add(new OperationOutcomeIssue(
                                                     OperationOutcomeConstants.IssueSeverity.Error,
                                                     OperationOutcomeConstants.IssueType.Exception,
                                                     ex.Message));

                throw customSearchException;
            }
        }
コード例 #4
0
ファイル: ResourceTests.cs プロジェクト: yarwelp/tooll
        public void TryGet_ReadSameRawResources_Returns2EqualRawResource()
        {
            RawResource rawResource1 = ResourceManager.ReadRaw(f_filePath);
            RawResource rawResource2 = ResourceManager.ReadRaw(f_filePath);

            Assert.AreEqual(rawResource1.GetHashCode(), rawResource2.GetHashCode()); //because the resource was cached
        }
コード例 #5
0
        public async Task UpdateSearchParameterAsync(ITypedElement searchParam, RawResource previousSearchParam)
        {
            try
            {
                // We need to make sure we have the latest search parameters before trying to update
                // existing search parameter. This is to avoid trying to update a search parameter that
                // was recently added and that hasn't propogated to all fhir-server instances.
                await GetAndApplySearchParameterUpdates(CancellationToken.None);

                var searchParameterWrapper = new SearchParameterWrapper(searchParam);
                var searchParameterInfo    = new SearchParameterInfo(searchParameterWrapper);
                (bool Supported, bool IsPartiallySupported)supportedResult = _searchParameterSupportResolver.IsSearchParameterSupported(searchParameterInfo);

                if (!supportedResult.Supported)
                {
                    throw new SearchParameterNotSupportedException(searchParameterInfo.Url);
                }

                // check data store specific support for SearchParameter
                if (!_dataStoreSearchParameterValidator.ValidateSearchParameter(searchParameterInfo, out var errorMessage))
                {
                    throw new SearchParameterNotSupportedException(errorMessage);
                }

                var prevSearchParam    = _modelInfoProvider.ToTypedElement(previousSearchParam);
                var prevSearchParamUrl = prevSearchParam.GetStringScalar("url");

                // As any part of the SearchParameter may have been changed, including the URL
                // the most reliable method of updating the SearchParameter is to delete the previous
                // data and insert the updated version
                await _searchParameterStatusManager.DeleteSearchParameterStatusAsync(prevSearchParamUrl);

                _searchParameterDefinitionManager.DeleteSearchParameter(prevSearchParam);
                _searchParameterDefinitionManager.AddNewSearchParameters(new List <ITypedElement>()
                {
                    searchParam
                });
                await _searchParameterStatusManager.AddSearchParameterStatusAsync(new List <string>() { searchParameterWrapper.Url });
            }
            catch (FhirException fex)
            {
                fex.Issues.Add(new OperationOutcomeIssue(
                                   OperationOutcomeConstants.IssueSeverity.Error,
                                   OperationOutcomeConstants.IssueType.Exception,
                                   Core.Resources.CustomSearchUpdateError));

                throw;
            }
            catch (Exception ex)
            {
                var customSearchException = new ConfigureCustomSearchException(Core.Resources.CustomSearchUpdateError);
                customSearchException.Issues.Add(new OperationOutcomeIssue(
                                                     OperationOutcomeConstants.IssueSeverity.Error,
                                                     OperationOutcomeConstants.IssueType.Exception,
                                                     ex.Message));

                throw customSearchException;
            }
        }
コード例 #6
0
ファイル: ResourceTests.cs プロジェクト: yarwelp/tooll
        public void TryGet_ReadSameRawResourcesViaAbsolutAndRelativFilename_Returns2EqualRawResource()
        {
            FileInfo    fi           = new FileInfo(f_filePath);
            RawResource rawResource1 = ResourceManager.ReadRaw(f_filePath);
            RawResource rawResource2 = ResourceManager.ReadRaw(fi.FullName);

            Assert.AreEqual(rawResource1.GetHashCode(), rawResource2.GetHashCode()); //because the resource was cached
        }
コード例 #7
0
        private ResourceElement CreatePatientResourceElement(string patientName, string id)
        {
            var json = Samples.GetJson("Patient");

            json = json.Replace("Chalmers", patientName);
            json = json.Replace("\"id\": \"example\"", "\"id\": \"" + id + "\"");
            var rawResource = new RawResource(json, FhirResourceFormat.Json, isMetaSet: false);

            return(Deserializers.ResourceDeserializer.DeserializeRaw(rawResource, "v1", DateTimeOffset.UtcNow));
        }
コード例 #8
0
        public BaseResource(RawResource obj)
        {
            Type = (BaseResourceType)Enum.Parse(typeof(BaseResourceType), obj.type, true);
            Name = obj.name;

            Path         = new UniversalPath(obj.path ?? string.Empty);
            Size         = new FileSize(string.IsNullOrEmpty(obj.size) ? 0 : Convert.ToUInt64(obj.size));
            ModifiedTime = string.IsNullOrEmpty(obj.date_modified) ? DateTime.MinValue : DateTime.FromFileTime(Convert.ToInt64(obj.date_modified));
            CreatedTime  = string.IsNullOrEmpty(obj.date_created) ? DateTime.MinValue : DateTime.FromFileTime(Convert.ToInt64(obj.date_created));
            Attributes   = obj.attributes ?? string.Empty;
        }
コード例 #9
0
ファイル: ResourceTests.cs プロジェクト: yarwelp/tooll
        public void TryGet_ReadSameFileAsDifferentResources_FirstReadResourceIsValidSecondFails()
        {
            RawResource rawResource = ResourceManager.ReadRaw(f_filePath);

            //this fails, because the file is already cached but as a raw resource. currently there exists no conversion from raw to image resource.
            //therefor the 'casting' fails.
            ImageResource imageResource = ResourceManager.ReadImage(f_filePath);

            Assert.IsNotNull(rawResource);
            Assert.IsNull(imageResource);
        }
コード例 #10
0
 private ResourceWrapper CreateResourceWrapper(RawResource rawResource)
 {
     return(new ResourceWrapper(
                _resource.ToResourceElement(),
                rawResource,
                null,
                false,
                null,
                null,
                null));
 }
コード例 #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceWrapperWithSearchIndices"/> class.
 /// </summary>
 /// <param name="resource">The resource.</param>
 /// <param name="rawResource">The raw resource.</param>
 /// <param name="request">Request information for how th resource was made.</param>
 /// <param name="isDeleted">A flag indicating whether the source is deleted or not.</param>
 /// <param name="searchIndices">The search indices.</param>
 /// <param name="compartmentIndices">The comparment indices.</param>
 /// <param name="lastModifiedClaims">The security claims when the resource was last modified.</param>
 public ResourceWrapperWithSearchIndices(
     Resource resource,
     RawResource rawResource,
     ResourceRequest request,
     bool isDeleted,
     IReadOnlyCollection <SearchIndexEntry> searchIndices,
     CompartmentIndices compartmentIndices,
     IReadOnlyCollection <KeyValuePair <string, string> > lastModifiedClaims)
     : base(resource, rawResource, request, isDeleted, lastModifiedClaims, compartmentIndices)
 {
     SearchIndices = searchIndices ?? System.Array.Empty <SearchIndexEntry>();
 }
コード例 #12
0
        private SearchResultEntry CreateSearchResultEntry(string jsonName, IReadOnlyCollection <SearchIndexEntry> searchIndices)
        {
            var json               = Samples.GetJson(jsonName);
            var rawResource        = new RawResource(json, FhirResourceFormat.Json, isMetaSet: false);
            var resourceRequest    = Substitute.For <ResourceRequest>();
            var compartmentIndices = Substitute.For <CompartmentIndices>();
            var resourceElement    = _resourceDeserializer.DeserializeRaw(rawResource, "v1", DateTimeOffset.UtcNow);
            var wrapper            = new ResourceWrapper(resourceElement, rawResource, resourceRequest, false, searchIndices, compartmentIndices, new List <KeyValuePair <string, string> >(), "hash");
            var entry              = new SearchResultEntry(wrapper);

            return(entry);
        }
コード例 #13
0
        public void GivenARawResourceInXmlFormat_WhenSerialized_ThenCorrectByteArrayShouldBeProduced()
        {
            var rawResource = new RawResource(
                new FhirXmlSerializer().SerializeToString(_resource),
                FhirResourceFormat.Xml);

            ResourceWrapper resourceWrapper = CreateResourceWrapper(rawResource);

            byte[] actualBytes = _serializer.Serialize(resourceWrapper);

            Assert.Equal(_expectedBytes, actualBytes);
        }
コード例 #14
0
        public void GivenARawResourceInXmlFormat_WhenSerialized_ThenCorrectByteArrayShouldBeProduced()
        {
            var rawResource = new RawResource(
                new FhirXmlSerializer().SerializeToString(_resource),
                FhirResourceFormat.Xml);

            ResourceWrapper resourceWrapper = CreateResourceWrapper(rawResource);
            ResourceElement element         = _resourceDeserializaer.DeserializeRaw(resourceWrapper.RawResource, resourceWrapper.Version, resourceWrapper.LastModified);

            byte[] actualBytes = _serializer.Serialize(element);

            Assert.Equal(_expectedBytes, actualBytes);
        }
コード例 #15
0
        internal static BundleWrapper ReadEmbeddedSearchParameters(
            string embeddedResourceName,
            IModelInfoProvider modelInfoProvider,
            string embeddedResourceNamespace = null,
            Assembly assembly = null)
        {
            using Stream stream = modelInfoProvider.OpenVersionedFileStream(embeddedResourceName, embeddedResourceNamespace, assembly);

            using TextReader reader = new StreamReader(stream);
            var data        = reader.ReadToEnd();
            var rawResource = new RawResource(data, FhirResourceFormat.Json, true);

            return(new BundleWrapper(modelInfoProvider.ToTypedElement(rawResource)));
        }
コード例 #16
0
        private ResourceWrapper CreateResourceWrapper(string patientName)
        {
            var json = Samples.GetJson("Patient");

            json = json.Replace("Chalmers", patientName);
            json = json.Replace("\"id\": \"example\"", "\"id\": \"" + patientName + "\"");
            var rawResource        = new RawResource(json, FhirResourceFormat.Json, isMetaSet: false);
            var resourceRequest    = Substitute.For <ResourceRequest>();
            var compartmentIndices = Substitute.For <CompartmentIndices>();
            var resourceElement    = Deserializers.ResourceDeserializer.DeserializeRaw(rawResource, "v1", DateTimeOffset.UtcNow);
            var searchIndices      = _searchIndexer.Extract(resourceElement);
            var wrapper            = new ResourceWrapper(resourceElement, rawResource, resourceRequest, false, searchIndices, compartmentIndices, new List <KeyValuePair <string, string> >(), "hash");

            return(wrapper);
        }
        public async Task UpdateSearchParameterAsync(ITypedElement searchParam, RawResource prevSearchParamRaw)
        {
            try
            {
                var searchParameterWrapper = new SearchParameterWrapper(searchParam);
                var searchParameterInfo    = new SearchParameterInfo(searchParameterWrapper);
                (bool Supported, bool IsPartiallySupported)supportedResult = _searchParameterSupportResolver.IsSearchParameterSupported(searchParameterInfo);

                if (!supportedResult.Supported)
                {
                    throw new SearchParameterNotSupportedException(searchParameterInfo.Url);
                }

                var prevSearchParam    = _modelInfoProvider.ToTypedElement(prevSearchParamRaw);
                var prevSearchParamUrl = prevSearchParam.GetStringScalar("url");

                // As any part of the SearchParameter may have been changed, including the URL
                // the most reliable method of updating the SearchParameter is to delete the previous
                // data and insert the updated version
                await _searchParameterStatusManager.DeleteSearchParameterStatusAsync(prevSearchParamUrl);

                _searchParameterDefinitionManager.DeleteSearchParameter(prevSearchParam);
                _searchParameterDefinitionManager.AddNewSearchParameters(new List <ITypedElement>()
                {
                    searchParam
                });
                await _searchParameterStatusManager.AddSearchParameterStatusAsync(new List <string>() { searchParameterWrapper.Url });
            }
            catch (FhirException fex)
            {
                fex.Issues.Add(new OperationOutcomeIssue(
                                   OperationOutcomeConstants.IssueSeverity.Error,
                                   OperationOutcomeConstants.IssueType.Exception,
                                   Core.Resources.CustomSearchUpdateError));

                throw;
            }
            catch (Exception ex)
            {
                var customSearchException = new ConfigureCustomSearchException(Core.Resources.CustomSearchUpdateError);
                customSearchException.Issues.Add(new OperationOutcomeIssue(
                                                     OperationOutcomeConstants.IssueSeverity.Error,
                                                     OperationOutcomeConstants.IssueType.Exception,
                                                     ex.Message));

                throw customSearchException;
            }
        }
コード例 #18
0
        /// <inheritdoc />
        public ResourceWrapper Create(Resource resource, bool deleted)
        {
            RawResource rawResource = _rawResourceFactory.Create(resource);
            IReadOnlyCollection <SearchIndexEntry> searchIndices = _searchIndexer.Extract(resource);

            IFhirRequestContext fhirRequestContext = _fhirRequestContextAccessor.FhirRequestContext;

            return(new ResourceWrapperWithSearchIndices(
                       resource,
                       rawResource,
                       new ResourceRequest(fhirRequestContext.Uri, fhirRequestContext.Method),
                       deleted,
                       searchIndices,
                       _compartmentIndexer.Extract(resource.ResourceType, searchIndices),
                       _claimsIndexer.Extract()));
        }
コード例 #19
0
 public FhirCosmosResourceWrapper(
     string resourceId,
     string versionId,
     string resourceTypeName,
     RawResource rawResource,
     ResourceRequest request,
     DateTimeOffset lastModified,
     bool deleted,
     bool history,
     IReadOnlyCollection <SearchIndexEntry> searchIndices,
     CompartmentIndices compartmentIndices,
     IReadOnlyCollection <KeyValuePair <string, string> > lastModifiedClaims)
     : base(resourceId, versionId, resourceTypeName, rawResource, request, lastModified, deleted, searchIndices, compartmentIndices, lastModifiedClaims)
 {
     IsHistory = history;
 }
コード例 #20
0
        private void SetupDataStoreToReturnDummyResourceWrapper()
        {
            ResourceElement patientResourceElement = Samples.GetDefaultPatient();
            Patient         patientResource        = patientResourceElement.ToPoco <Patient>();
            RawResource     rawResource            = new RawResource(new FhirJsonSerializer().SerializeToString(patientResource), FhirResourceFormat.Json, isMetaSet: false);

            ResourceWrapper dummyResourceWrapper = new ResourceWrapper(
                patientResourceElement,
                rawResource,
                request: null,
                deleted: false,
                searchIndices: null,
                compartmentIndices: null,
                lastModifiedClaims: null);

            _fhirDataStore.GetAsync(Arg.Any <ResourceKey>(), _cancellationToken).Returns(Task.FromResult(dummyResourceWrapper));
        }
コード例 #21
0
        private async Task <UpsertOutcome> UpsertPatientData()
        {
            var json               = Samples.GetJson("Patient");
            var rawResource        = new RawResource(json, FhirResourceFormat.Json, isMetaSet: false);
            var resourceRequest    = new ResourceRequest(WebRequestMethods.Http.Put);
            var compartmentIndices = Substitute.For <CompartmentIndices>();
            var resourceElement    = Deserializers.ResourceDeserializer.DeserializeRaw(rawResource, "v1", DateTimeOffset.UtcNow);
            var searchIndices      = _searchIndexer.Extract(resourceElement);

            var wrapper = new ResourceWrapper(
                resourceElement,
                rawResource,
                resourceRequest,
                false,
                searchIndices,
                compartmentIndices,
                new List <KeyValuePair <string, string> >(),
                _searchParameterDefinitionManager.GetSearchParameterHashForResourceType("Patient"));

            return(await _scopedDataStore.Value.UpsertAsync(wrapper, null, true, true, CancellationToken.None));
        }
コード例 #22
0
        public async Task DeleteSearchParameterAsync(RawResource searchParamResource, CancellationToken cancellationToken)
        {
            try
            {
                // We need to make sure we have the latest search parameters before trying to delete
                // existing search parameter. This is to avoid trying to update a search parameter that
                // was recently added and that hasn't propogated to all fhir-server instances.
                await GetAndApplySearchParameterUpdates(cancellationToken);

                var searchParam        = _modelInfoProvider.ToTypedElement(searchParamResource);
                var searchParameterUrl = searchParam.GetStringScalar("url");

                // First we delete the status metadata from the data store as this fuction depends on the
                // the in memory definition manager.  Once complete we remove the SearchParameter from
                // the definition manager.
                _logger.LogTrace("Deleting the search parameter '{url}'", searchParameterUrl);
                await _searchParameterStatusManager.DeleteSearchParameterStatusAsync(searchParameterUrl, cancellationToken);

                _searchParameterDefinitionManager.DeleteSearchParameter(searchParam);
            }
            catch (FhirException fex)
            {
                fex.Issues.Add(new OperationOutcomeIssue(
                                   OperationOutcomeConstants.IssueSeverity.Error,
                                   OperationOutcomeConstants.IssueType.Exception,
                                   Core.Resources.CustomSearchDeleteError));

                throw;
            }
            catch (Exception ex)
            {
                var customSearchException = new ConfigureCustomSearchException(Core.Resources.CustomSearchDeleteError);
                customSearchException.Issues.Add(new OperationOutcomeIssue(
                                                     OperationOutcomeConstants.IssueSeverity.Error,
                                                     OperationOutcomeConstants.IssueType.Exception,
                                                     ex.Message));

                throw customSearchException;
            }
        }
コード例 #23
0
        private static SearchResult GetSearchResultFromSearchParam(SearchParameter searchParam, string continuationToken)
        {
            var serializer = new FhirJsonSerializer();

            var rawResource = new RawResource(
                serializer.SerializeToString(searchParam),
                FhirResourceFormat.Json,
                false);

            var wrapper = new ResourceWrapper(
                new ResourceElement(
                    rawResource.ToITypedElement(ModelInfoProvider.Instance)),
                rawResource,
                new ResourceRequest("POST"),
                false,
                null,
                null,
                null);
            var searchEntry = new SearchResultEntry(wrapper);

            return(new SearchResult(Enumerable.Repeat(searchEntry, 1), continuationToken, null, new List <Tuple <string, string> >()));
        }
コード例 #24
0
ファイル: SoundManager.cs プロジェクト: ryancheung/WinWar
        public bool LoadSound(int resIndex)
        {
            if (effectCache.ContainsKey(resIndex) || WarFile.AreResoucesLoaded == false)
            {
                return(false);
            }

            RawResource res = WarFile.GetResource(resIndex) as RawResource;

            if (res == null ||
                res.Type != ContentFileType.FileWave)
            {
                return(false);
            }

            using (MemoryStream memStream = new MemoryStream(res.Resource.data))
            {
                SoundEffect eff = SoundEffect.FromStream(memStream);
                effectCache.Add(resIndex, eff);
            }

            return(true);
        }
コード例 #25
0
        /// <summary>
        /// Converts the RawResource to an ITypedElement
        /// </summary>
        /// <param name="rawResource">The RawResource to convert</param>
        /// <param name="modelInfoProvider">The IModelInfoProvider to use when converting the RawResource</param>
        /// <returns>An ITypedElement of the RawResource</returns>
        public static ITypedElement ToITypedElement(this RawResource rawResource, IModelInfoProvider modelInfoProvider)
        {
            EnsureArg.IsNotNull(rawResource, nameof(rawResource));
            EnsureArg.IsNotNull(modelInfoProvider, nameof(modelInfoProvider));

            using TextReader reader     = new StringReader(rawResource.Data);
            using JsonReader jsonReader = new JsonTextReader(reader);
            try
            {
                ISourceNode sourceNode = FhirJsonNode.Read(jsonReader);
                return(modelInfoProvider.ToTypedElement(sourceNode));
            }
            catch (FormatException ex)
            {
                var issue = new OperationOutcomeIssue(
                    OperationOutcomeConstants.IssueSeverity.Fatal,
                    OperationOutcomeConstants.IssueType.Invalid,
                    ex.Message);

                throw new InvalidDefinitionException(
                          Core.Resources.SearchParameterDefinitionContainsInvalidEntry,
                          new OperationOutcomeIssue[] { issue });
            }
        }
コード例 #26
0
        public ITypedElement ToTypedElement(RawResource rawResource)
        {
            EnsureArg.IsNotNull(rawResource, nameof(rawResource));

            using TextReader reader     = new StringReader(rawResource.Data);
            using JsonReader jsonReader = new JsonTextReader(reader);
            try
            {
                ISourceNode sourceNode = FhirJsonNode.Read(jsonReader);
                return(sourceNode.ToTypedElement(StructureDefinitionSummaryProvider));
            }
            catch (FormatException ex)
            {
                var issue = new OperationOutcomeIssue(
                    OperationOutcomeConstants.IssueSeverity.Fatal,
                    OperationOutcomeConstants.IssueType.Invalid,
                    ex.Message);

                throw new ResourceNotValidException(new List <OperationOutcomeIssue>()
                {
                    issue
                });
            }
        }
コード例 #27
0
 public FolderResource(RawResource obj) : base(obj)
 {
 }
コード例 #28
0
ファイル: ResourceTests.cs プロジェクト: yarwelp/tooll
        public void TryGet_ReadRawResource_ReturnsValidResource()
        {
            RawResource rawResource = ResourceManager.ReadRaw(f_filePath);

            Assert.IsNotNull(rawResource);
        }
コード例 #29
0
 public FileResource(RawResource obj) : base(obj)
 {
 }