Пример #1
0
        /// <summary>
        /// Process single file, and all its fragment dependencies.
        /// This is mostly for test use, as you can run just a single file that has troubles in it
        /// rather than all the files in a directory.
        /// All fragments must be in same dir as file, and they must be named
        /// 'StructureDefinition-{last part of fragment uri}'
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool ProcessOne(String fragmentDir, String name)
        {
            const String fcn = "ProcessOne";

            String fragmentPath = FragPath(fragmentDir, name);

            if (File.Exists(fragmentPath) == false)
            {
                this.ConversionError(this.GetType().Name,
                                     fcn,
                                     $"Missing fragment file {fragmentPath}");
                return(false);
            }

            FhirJsonParser      parser = new FhirJsonParser();
            StructureDefinition sd     = parser.Parse <StructureDefinition>(File.ReadAllText(fragmentPath));

            // add and process all referenced fragment files.
            {
                AddReferences(new HashSet <String>(), fragmentDir, sd);
                if (this.HasErrors == true)
                {
                    return(false);
                }
                Process();
                if (this.HasErrors == true)
                {
                    return(false);
                }
            }

            // all referenced fragments have been executed.
            // process test resource.
            ProcessItem pi = new ProcessItem(this, sd);

            this.Process(pi);

            return(this.HasErrors);
        }
Пример #2
0
        public static List <ParsedPatient> ParsePatientFromFiles(string[] fileNames)
        {
            ParsingSyntheaData?.Invoke("SyntheaRunner", EventArgs.Empty);

            var parsedPatients = new List <ParsedPatient>();
            var resourceParser = new FhirJsonParser(
                new ParserSettings {
                AcceptUnknownMembers = true, AllowUnrecognizedEnums = true, PermissiveParsing = true
            });

            foreach (var file in fileNames)
            {
                var json         = File.ReadAllText(file);
                var parsedBundle = resourceParser.Parse <Bundle>(json);
                if (parsedBundle.Entry[0].Resource is Patient)
                {
                    parsedPatients.Add(ParsedPatient.FromBundle(parsedBundle));
                }
            }

            return(parsedPatients);
        }
        public async Task <Patient> LoadPatientAsyncWithIndentifier(string patientIdentifier)
        {
            var path  = DiscoveryPathConstants.OnPatientPath;
            var query = HttpUtility.ParseQueryString(string.Empty);

            if (!string.IsNullOrEmpty(patientIdentifier))
            {
                query["identifier"] = patientIdentifier;
            }
            if (query.ToString() != "")
            {
                path = $"{path}/?{query}";
            }

            var response = await openMrsClient.GetAsync(path);

            var content = await response.Content.ReadAsStringAsync();

            var bundle = new FhirJsonParser().Parse <Bundle>(content);

            return((Patient)bundle.Entry[0].Resource);
        }
Пример #4
0
        public async Task GivenConvertDataRequest_WithDefaultTemplates_CorrectResultShouldReturn()
        {
            var convertDataEngine = GetDefaultEngine();
            var request           = GetHl7V2RequestWithDefaultTemplates();
            var response          = await convertDataEngine.Process(request, CancellationToken.None);

            var setting = new ParserSettings()
            {
                AcceptUnknownMembers = true,
                PermissiveParsing    = true,
            };
            var parser         = new FhirJsonParser(setting);
            var bundleResource = parser.Parse <Bundle>(response.Resource);

            Assert.Equal("urn:uuid:9d697ec3-48c3-3e17-db6a-29a1765e22c6", bundleResource.Entry.First().FullUrl);
            Assert.Equal(4, bundleResource.Entry.Count);

            var patient = bundleResource.Entry.First().Resource as Patient;

            Assert.Equal("Kinmonth", patient.Name.First().Family);
            Assert.Equal("1987-06-24", patient.BirthDate);
        }
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return(Task.Factory.StartNew <object>(() =>
            {
                try
                {
                    var body = ReadBodyFromStream(readStream, content);

                    if (typeof(Resource).IsAssignableFrom(type))
                    {
                        var fhirparser = new FhirJsonParser();
                        var resource = fhirparser.Parse(body, type);
                        return resource;
                    }
                    throw Error.Internal("Cannot read unsupported type {0} from body", type.Name);
                }
                catch (FormatException exception)
                {
                    throw Error.BadRequest("Body parsing failed: " + exception.Message);
                }
            }));
        }
        private async SystemTasks.Task <FhirResponse> ParseResource(HttpContent content, CommandRequest request, FhirResponse fhirResponse)
        {
            var data = await content.ReadAsStreamAsync();

            if (data == null)
            {
                throw new HttpRequestException($"Request resulted in nothing for: {request.FullUrl}.");
            }

            using (var reader = new StreamReader(data, Encoding.UTF8))
            {
                try
                {
                    var mediaType = content.Headers.ContentType.MediaType.ToLowerInvariant();

                    var body = reader.ReadToEnd();

                    if (!string.IsNullOrEmpty(body))
                    {
                        if (mediaType.Contains("xml"))
                        {
                            var xmlParser = new FhirXmlParser();
                            fhirResponse.Resource = xmlParser.Parse <Resource>(body);
                        }
                        else
                        {
                            var jsonParser = new FhirJsonParser();
                            fhirResponse.Resource = jsonParser.Parse <Resource>(body);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new HttpRequestException(ex.Message, ex.InnerException);
                }
            }

            return(fhirResponse);
        }
Пример #7
0
        public async Task GivenAJsonValidRequestWithDefaultTemplateSet_WhenConvertData_CorrectResponseShouldReturn()
        {
            Skip.IfNot(_convertDataEnabled);

            var parameters               = GetConvertDataParams(Samples.SampleJsonMessage, "Json", JsonDefaultTemplateSetReference, "ExamplePatient");
            var requestMessage           = GenerateConvertDataRequest(parameters);
            HttpResponseMessage response = await _testFhirClient.HttpClient.SendAsync(requestMessage);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var patientContent = await response.Content.ReadAsStringAsync();

            var setting = new ParserSettings
            {
                AcceptUnknownMembers = true,
                PermissiveParsing    = true,
            };
            var parser          = new FhirJsonParser(setting);
            var patientResource = parser.Parse <Patient>(patientContent);

            Assert.NotEmpty(patientResource.Id);
        }
        public async Task <List <Patient> > LoadPatientsAsync(string name, AdministrativeGender?gender, string yearOfBirth)
        {
            var path  = DiscoveryPathConstants.OnPatientPath;
            var query = HttpUtility.ParseQueryString(string.Empty);

            if (!string.IsNullOrEmpty(name))
            {
                query["name"] = name;
            }
            if (gender != null)
            {
                query["gender"] = gender.ToString().ToLower();
            }
            if (!string.IsNullOrEmpty(yearOfBirth))
            {
                query["birthdate"] = yearOfBirth;
            }
            if (query.ToString() != "")
            {
                path = $"{path}/?{query}";
            }

            var patients = new List <Patient>();
            var response = await openMrsClient.GetAsync(path);

            var content = await response.Content.ReadAsStringAsync();

            var bundle = new FhirJsonParser().Parse <Bundle>(content);

            bundle.Entry.ForEach(entry =>
            {
                if (entry.Resource.ResourceType.Equals(ResourceType.Patient))
                {
                    patients.Add((Patient)entry.Resource);
                }
            });

            return(patients);
        }
Пример #9
0
        public BundleHandler(IHttpContextAccessor httpContextAccessor, IFhirRequestContextAccessor fhirRequestContextAccessor, FhirJsonSerializer fhirJsonSerializer, FhirJsonParser fhirJsonParser, ITransactionHandler transactionHandler, ILogger <BundleHandler> logger)
        {
            EnsureArg.IsNotNull(httpContextAccessor, nameof(httpContextAccessor));
            EnsureArg.IsNotNull(fhirRequestContextAccessor, nameof(fhirRequestContextAccessor));
            EnsureArg.IsNotNull(fhirJsonSerializer, nameof(fhirJsonSerializer));
            EnsureArg.IsNotNull(fhirJsonParser, nameof(fhirJsonParser));
            EnsureArg.IsNotNull(transactionHandler, nameof(transactionHandler));
            EnsureArg.IsNotNull(logger, nameof(logger));

            _fhirRequestContextAccessor = fhirRequestContextAccessor;
            _fhirJsonSerializer         = fhirJsonSerializer;
            _fhirJsonParser             = fhirJsonParser;
            _transactionHandler         = transactionHandler;
            _logger = logger;

            // Not all versions support the same enum values, so do the dictionary creation in the version specific partial.
            _requests = GenerateRequestDictionary();

            _httpAuthenticationFeature = httpContextAccessor.HttpContext.Features.First(x => x.Key == typeof(IHttpAuthenticationFeature)).Value as IHttpAuthenticationFeature;
            _router          = httpContextAccessor.HttpContext.GetRouteData().Routers.First();
            _requestServices = httpContextAccessor.HttpContext.RequestServices;
        }
Пример #10
0
        private static Resource ParseResource(string data)
        {
            if (SerializationUtil.ProbeIsJson(data))
            {
                // TODO read config to determine if PermissiveParsing should be on
                var parser = new FhirJsonParser(new ParserSettings {
                    PermissiveParsing = true
                });
                return(parser.Parse <Resource>(data));
            }

            if (SerializationUtil.ProbeIsXml(data))
            {
                // TODO read config to determine if PermissiveParsing should be on
                var parser = new FhirXmlParser(new ParserSettings {
                    PermissiveParsing = true
                });
                return(parser.Parse <Resource>(data));
            }

            throw new FormatException("Data is neither Json nor Xml");
        }
Пример #11
0
        public ResourceJsonInputFormatter(FhirJsonParser parser, ArrayPool <char> charPool)
        {
            if (parser == null)
            {
                throw new ArgumentNullException(nameof(parser));
            }
            if (charPool == null)
            {
                throw new ArgumentNullException(nameof(charPool));
            }

            _parser   = parser;
            _charPool = new JsonArrayPool(charPool);

            SupportedEncodings.Clear();
            SupportedEncodings.Add(Encoding.UTF8);

            SupportedMediaTypes.Add("application/json");
            SupportedMediaTypes.Add("application/fhir+json");
            SupportedMediaTypes.Add("application/json+fhir");
            SupportedMediaTypes.Add("text/json");
        }
Пример #12
0
        public async Task GivenAHl7v2ValidRequestWithDefaultTemplateSet_WhenConvertData_CorrectResponseShouldReturn(string templateReference)
        {
            Skip.IfNot(_convertDataEnabled);

            var parameters               = GetConvertDataParams(Samples.SampleHl7v2Message, "hl7v2", templateReference, "ADT_A01");
            var requestMessage           = GenerateConvertDataRequest(parameters);
            HttpResponseMessage response = await _testFhirClient.HttpClient.SendAsync(requestMessage);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var bundleContent = await response.Content.ReadAsStringAsync();

            var setting = new ParserSettings()
            {
                AcceptUnknownMembers = true,
                PermissiveParsing    = true,
            };
            var parser         = new FhirJsonParser(setting);
            var bundleResource = parser.Parse <Bundle>(bundleContent);

            Assert.NotEmpty(bundleResource.Entry.ByResourceType <Patient>().First().Id);
        }
Пример #13
0
        public BundleHandlerTests()
        {
            _router = Substitute.For <IRouter>();

            var fhirRequestContext = Substitute.For <IFhirRequestContext>();

            fhirRequestContext.BaseUri.Returns(new Uri("https://localhost/"));
            fhirRequestContext.CorrelationId.Returns(Guid.NewGuid().ToString());

            _fhirRequestContextAccessor = Substitute.For <IFhirRequestContextAccessor>();
            _fhirRequestContextAccessor.FhirRequestContext.Returns(fhirRequestContext);

            _httpContextAccessor = Substitute.For <IHttpContextAccessor>();

            _fhirJsonSerializer = new FhirJsonSerializer();
            _fhirJsonParser     = new FhirJsonParser();

            _bundleHttpContextAccessor = new BundleHttpContextAccessor();

            IFeatureCollection featureCollection = CreateFeatureCollection();
            var httpContext = new DefaultHttpContext(featureCollection)
            {
                Request =
                {
                    Scheme   = "https",
                    Host     = new HostString("localhost"),
                    PathBase = new PathString("/"),
                },
            };

            _httpContextAccessor.HttpContext.Returns(httpContext);

            var transactionHandler = Substitute.For <ITransactionHandler>();

            _resourceIdProvider = new ResourceIdProvider();

            _bundleHandler = new BundleHandler(_httpContextAccessor, _fhirRequestContextAccessor, _fhirJsonSerializer, _fhirJsonParser, transactionHandler, _bundleHttpContextAccessor, _resourceIdProvider, NullLogger <BundleHandler> .Instance);
        }
Пример #14
0
        private List <T> Exec <T>(string sql, Type type) where T : Base
        {
            using (var conn = new NpgsqlConnection(m_connString))
            {
                conn.Open();
                var da = new NpgsqlDataAdapter(sql, conn);
                var ds = new DataSet();
                da.Fill(ds);

                var res = new List <T>();

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var parser = new FhirJsonParser();
                    using (var reader = new FhirbaseJsonReader(row.ItemArray[0], type))
                    {
                        res.Add(parser.Parse <T>(reader));
                    }
                }

                return(res);
            }
        }
Пример #15
0
        public IActionResult Edit(JsonTextModel json)
        {
            if (string.IsNullOrWhiteSpace(json.JsonText_))
            {
                return(View(json));
            }
            var parser = new FhirJsonParser();

            try
            {
                var        res      = parser.Parse <Resource>(json.JsonText_);
                FhirClient client   = new FhirClient(url);
                var        resEntry = client.Update(res);
                json.Status_ = JsonTextModel.UPDATED;
            }

            catch (Exception e)
            {
                json.Status_ = JsonTextModel.FAILED;
                return(View(json));
            }
            return(View(json));
        }
Пример #16
0
        public void GivenAResource_WhenCreateARawResourceWithKeepMetaFalse_ThenTheObjectPassedInIsModified()
        {
            var serializer         = new FhirJsonSerializer();
            var rawResourceFactory = new RawResourceFactory(serializer);

            string versionId   = Guid.NewGuid().ToString();
            var    observation = Samples.GetDefaultObservation()
                                 .UpdateVersion(versionId);

            Assert.NotNull(observation.VersionId);

            var raw = rawResourceFactory.Create(observation, keepMeta: false);

            Assert.NotNull(raw.Data);

            var parser = new FhirJsonParser(DefaultParserSettings.Settings);

            var deserialized = parser.Parse <Observation>(raw.Data);

            Assert.NotNull(deserialized);
            Assert.Null(deserialized.VersionId);
            Assert.Null(deserialized.Meta?.LastUpdated);
        }
        public void STU3_TestSuccessfulCreate()
        {
            MockObjectRepository mockRepo = new MockObjectRepository();

            mockRepo.InitializeFHIR3Repository();
            mockRepo.InitializeLCG();

            var parserSettings = new ParserSettings();

            parserSettings.AcceptUnknownMembers        = true;
            parserSettings.AllowUnrecognizedEnums      = true;
            parserSettings.DisallowXsiAttributesOnRoot = false;

            var strucDefJson             = Helper.GetSampleContents("Trifolia.Test.DocSamples.FHIR.STU3.cqif-questionnaire-strucdef.json");
            var fhirJsonParser           = new FhirJsonParser(parserSettings);
            StructureDefinition strucDef = fhirJsonParser.Parse <StructureDefinition>(strucDefJson);

            HttpRequestMessage request = new HttpRequestMessage();

            request.RequestUri = new Uri("http://localhost:8080/api/FHIR3/StructureDefinition");

            HttpRequest  contextRequest  = new HttpRequest(null, "http://localhost:8080/api/FHIR3/StructureDefinition", null);
            HttpResponse contextResponse = new HttpResponse(new StringWriter());

            HttpContext.Current = new HttpContext(contextRequest, contextResponse);

            FHIR3StructureDefinitionController controller = new FHIR3StructureDefinitionController(mockRepo, request);
            var response = controller.CreateStructureDefinition(strucDef);
            var result   = AssertHelper.IsType <TrifoliaApiController.CustomHeadersWithContentResult <StructureDefinition> >(response);

            Assert.AreEqual(HttpStatusCode.Created, result.StatusCode);
            Assert.IsNotNull(result.CustomHeaders["Location"]);
            Assert.AreEqual(result.CustomHeaders["Location"], "http://localhost:8080/api/FHIR3/StructureDefinition/1");

            Assert.IsNotNull(result.Content);
            Assert.AreEqual(strucDef.Name, result.Content.Name);
        }
Пример #18
0
        public void WhenFhirImmunizationWithExtensionToHealthVaultImmunization_ThenExtendedValuesAreParsedAndAreEqual()
        {
            var json = SampleUtil.GetSampleContent("HealthVaultToFhirImmunization.json");

            var fhirParser       = new FhirJsonParser();
            var fhirImmunization = fhirParser.Parse <Immunization>(json);

            var hvImmunization = fhirImmunization.ToHealthVault();

            Assert.IsNotNull(hvImmunization);
            Assert.AreEqual("cholera vaccine", hvImmunization.Name.Text);
            Assert.IsNotNull(hvImmunization.DateAdministrated.ApproximateDate);
            Assert.AreEqual(2017, hvImmunization.DateAdministrated.ApproximateDate.Year);
            Assert.IsNotNull(hvImmunization.DateAdministrated.ApproximateDate.Month);
            Assert.AreEqual(9, hvImmunization.DateAdministrated.ApproximateDate.Month.Value);
            Assert.IsNotNull(hvImmunization.DateAdministrated.ApproximateDate.Day);
            Assert.AreEqual(21, hvImmunization.DateAdministrated.ApproximateDate.Day.Value);
            Assert.AreEqual("By mouth", hvImmunization.Route.Text);
            Assert.AreEqual("AAJN11K", hvImmunization.Lot);
            Assert.IsNotNull(hvImmunization.ExpirationDate);
            Assert.AreEqual(2017, hvImmunization.ExpirationDate.Year);
            Assert.IsNotNull(hvImmunization.ExpirationDate.Month);
            Assert.AreEqual(10, hvImmunization.ExpirationDate.Month.Value);
            Assert.IsNotNull(hvImmunization.ExpirationDate.Day);
            Assert.AreEqual(20, hvImmunization.ExpirationDate.Day.Value);
            Assert.AreEqual("Metacarpophalangeal joint structure of index finger", hvImmunization.AnatomicSurface.Text);

            Assert.IsNotNull(hvImmunization.Administrator);
            Assert.AreEqual("Justin Case", hvImmunization.Administrator.Name.Full);
            Assert.IsNotNull(hvImmunization.Manufacturer);
            Assert.AreEqual("Baxter Healthcare Corporation", hvImmunization.Manufacturer.Text);

            //Extensions
            Assert.AreEqual("Last", hvImmunization.Sequence);
            Assert.AreEqual("A concent from parent goes here", hvImmunization.Consent);
            Assert.AreEqual("Something bad happened", hvImmunization.AdverseEvent);
        }
Пример #19
0
        private void ChooseSyntheaGeneratedFilesBtn_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            var status = driver.ChooseSyntheaGeneratedDataFile();

            if (status.IsOk)
            {
                fhirResourceString = status.Expect();
                var parser = new FhirJsonParser();
                var bundle = parser.Parse <Bundle>(fhirResourceString);
                resourceTypeDisplayLabel.Text = bundle.Entry[0].Resource.TypeName;
                foreach (var entryComponent in bundle.Entry)
                {
                    var resource = entryComponent.Resource;
                    if (resource.ResourceType == ResourceType.Patient)
                    {
                        var p = new Patient();
                        entryComponent.Resource.CopyTo(p);
                        patientForm.Display(p);
                    }
                }
            }
            else
            {
                var result = MessageBox.Show("Doh! Something went wrong\nWould you like to create a Patient from scratch?", "Doh!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                switch (result)
                {
                case DialogResult.Yes:
                    patientForm.EnterInfo();
                    break;

                default:
                    break;
                }
            }
            this.Enabled = true;
        }
        public async Task GivenAValidConfigurationWithoutETag_WhenExportingAnonymizedData_ResourceShouldBeAnonymized()
        {
            _metricHandler?.ResetCount();

            var resourceToCreate = Samples.GetDefaultPatient().ToPoco <Patient>();

            resourceToCreate.Id = Guid.NewGuid().ToString();
            var dateTime = DateTimeOffset.UtcNow;
            await _testFhirClient.UpdateAsync(resourceToCreate);

            (string fileName, string _) = await UploadConfigurationAsync(RedactResourceIdAnonymizationConfiguration);

            string containerName   = Guid.NewGuid().ToString("N");
            Uri    contentLocation = await _testFhirClient.AnonymizedExportAsync(fileName, dateTime, containerName);

            HttpResponseMessage response = await WaitForCompleteAsync(contentLocation);

            IList <Uri> blobUris = await CheckExportStatus(response);

            IEnumerable <string> dataFromExport = await DownloadBlobAndParse(blobUris);

            FhirJsonParser parser = new FhirJsonParser();

            foreach (string content in dataFromExport)
            {
                Resource result = parser.Parse <Resource>(content);

                Assert.Contains(result.Meta.Security, c => "REDACTED".Equals(c.Code));
            }

            // Only check metric for local tests
            if (_isUsingInProcTestServer)
            {
                Assert.Single(_metricHandler.NotificationMapping[typeof(ExportTaskMetricsNotification)]);
            }
        }
Пример #21
0
        /// <inheritdoc />
        public void Load(IServiceCollection services)
        {
            EnsureArg.IsNotNull(services, nameof(services));

            var jsonParser     = new FhirJsonParser(DefaultParserSettings.Settings);
            var jsonSerializer = new FhirJsonSerializer();

            var xmlParser     = new FhirXmlParser();
            var xmlSerializer = new FhirXmlSerializer();

            services.AddSingleton(jsonParser);
            services.AddSingleton(jsonSerializer);
            services.AddSingleton(xmlParser);
            services.AddSingleton(xmlSerializer);

            FhirPathCompiler.DefaultSymbolTable.AddFhirExtensions();

            ResourceElement SetMetadata(Resource resource, string versionId, DateTimeOffset lastModified)
            {
                resource.VersionId        = versionId;
                resource.Meta.LastUpdated = lastModified;

                return(resource.ToResourceElement());
            }

            services.AddSingleton <IReadOnlyDictionary <FhirResourceFormat, Func <string, string, DateTimeOffset, ResourceElement> > >(_ =>
            {
                return(new Dictionary <FhirResourceFormat, Func <string, string, DateTimeOffset, ResourceElement> >
                {
                    {
                        FhirResourceFormat.Json, (str, version, lastModified) =>
                        {
                            var resource = jsonParser.Parse <Resource>(str);

                            return SetMetadata(resource, version, lastModified);
                        }
                    },
                    {
                        FhirResourceFormat.Xml, (str, version, lastModified) =>
                        {
                            var resource = xmlParser.Parse <Resource>(str);

                            return SetMetadata(resource, version, lastModified);
                        }
                    },
                });
            });

            services.Add <ResourceDeserializer>()
            .Singleton()
            .AsSelf()
            .AsService <IResourceDeserializer>();

            services.Add <FormatterConfiguration>()
            .Singleton()
            .AsSelf()
            .AsService <IPostConfigureOptions <MvcOptions> >();

            services.AddSingleton <IContentTypeService, ContentTypeService>();
            services.AddSingleton <OperationOutcomeExceptionFilterAttribute>();
            services.AddSingleton <ValidateContentTypeFilterAttribute>();
            services.AddSingleton <ValidateExportRequestFilterAttribute>();
            services.AddSingleton <ValidationQueryFilterAndParameterParserAttribute>();
            services.AddSingleton <ValidateReindexRequestFilterAttribute>();

            // Support for resolve()
            FhirPathCompiler.DefaultSymbolTable.AddFhirExtensions();

            services.Add <FhirJsonInputFormatter>()
            .Singleton()
            .AsSelf()
            .AsService <TextInputFormatter>();

            services.Add <FhirJsonOutputFormatter>()
            .Singleton()
            .AsSelf()
            .AsService <TextOutputFormatter>();

            services.Add <FhirRequestContextAccessor>()
            .Singleton()
            .AsSelf()
            .AsService <IFhirRequestContextAccessor>();

            services.AddSingleton <CorrelationIdProvider>(_ => () => Guid.NewGuid().ToString());

            // Add conformance provider for implementation metadata.
            services.Add <SystemConformanceProvider>()
            .Singleton()
            .AsSelf()
            .AsImplementedInterfaces();

            services.TypesInSameAssembly(KnownAssemblies.All)
            .AssignableTo <IProvideCapability>()
            .Transient()
            .AsService <IProvideCapability>();

            services.AddSingleton <IClaimsExtractor, PrincipalClaimsExtractor>();

            ModelExtensions.SetModelInfoProvider();
            services.Add(_ => ModelInfoProvider.Instance).Singleton().AsSelf().AsImplementedInterfaces();

            // Register a factory to resolve a scope that returns all components that provide capabilities
            services.AddFactory <IScoped <IEnumerable <IProvideCapability> > >();

            services.AddLazy();
            services.AddScoped();
        }
        public void TestPatientWithOrganization()
        {
            // DirectorySource (and ResourceStreamScanner) does not support json...
            // var source = new DirectorySource(@"TestData\validation");
            // var res = source.ResolveByUri("Patient/pat1"); // cf. "Patient/Levin"

            var jsonPatient = File.ReadAllText(@"TestData\validation\patient-ck.json");
            var parser      = new FhirJsonParser();
            var patient     = parser.Parse <Patient>(jsonPatient);

            Assert.IsNotNull(patient);

            var jsonOrganization = File.ReadAllText(@"TestData\validation\organization-ck.json");
            var organization     = parser.Parse <Organization>(jsonOrganization);

            Assert.IsNotNull(organization);

            var resources   = new Resource[] { patient, organization };
            var memResolver = new InMemoryResourceResolver(resources);

            // [WMR 20161220] Validator always uses existing snapshots if present
            // ProfilePreprocessor.GenerateSnapshots:
            // if (!sd.HasSnapshot) { ... snapshotGenerator(sd) ... }

            // Create custom source to properly force snapshot expansion
            // Run validator on instance
            // Afterwards, verify that instance profile has been expanded

            var source = new CachedResolver(
                // Clear snapshots after initial load
                // This will force the validator to regenerate all snapshots
                new ClearSnapshotResolver(
                    new MultiResolver(
                        // new BundleExampleResolver(@"TestData\validation"),
                        // new DirectorySource(@"TestData\validation"),
                        // new TestProfileArtifactSource(),
                        memResolver,
                        new ZipSource("specification.zip"))));

            var ctx = new ValidationSettings()
            {
                ResourceResolver    = source,
                GenerateSnapshot    = true,
                EnableXsdValidation = true,
                Trace = false,
                ResolveExteralReferences = true
            };

            var validator = new Validator(ctx);

            var report = validator.Validate(patient);

            Assert.IsTrue(report.Success);

            // Assert.AreEqual(4, report.Warnings);

            // To check for ele-1 constraints on expanded Patient snapshot:
            // source.FindStructureDefinitionForCoreType(FHIRDefinedType.Patient).Snapshot.Element.Select(e=>e.Path + " : " + e.Constraint.FirstOrDefault()?.Key ?? "").ToArray()
            var patientStructDef = source.FindStructureDefinitionForCoreType(FHIRDefinedType.Patient);

            Assert.IsNotNull(patientStructDef);
            Assert.IsTrue(patientStructDef.HasSnapshot);
            assertElementConstraints(patientStructDef.Snapshot.Element);
        }
Пример #23
0
        public SearchParameterDefinitionManager(FhirJsonParser fhirJsonParser)
        {
            EnsureArg.IsNotNull(fhirJsonParser, nameof(fhirJsonParser));

            _fhirJsonParser = fhirJsonParser;
        }
Пример #24
0
        public GetCapabilitiesHandler(IConformanceProvider provider, ISystemConformanceProvider systemConformanceProvider, FhirJsonParser parser, IUrlResolver urlResolver)
        {
            EnsureArg.IsNotNull(provider, nameof(provider));
            EnsureArg.IsNotNull(systemConformanceProvider, nameof(systemConformanceProvider));
            EnsureArg.IsNotNull(parser, nameof(parser));
            EnsureArg.IsNotNull(urlResolver, nameof(urlResolver));

            _provider = provider;
            _systemConformanceProvider = systemConformanceProvider;
            _parser      = parser;
            _urlResolver = urlResolver;
        }
Пример #25
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "manage/{cmd}/{res}/{id}/{name}")] HttpRequest req,
            ILogger log, ClaimsPrincipal principal, string cmd, string res, string id, string name)
        {
            log.LogInformation("SecureLink Function Invoked");
            //Is the principal authenticated
            if (!Utils.isServerAccessAuthorized(req))
            {
                return(new ContentResult()
                {
                    Content = "User is not Authenticated", StatusCode = (int)System.Net.HttpStatusCode.Unauthorized
                });
            }

            if (!Utils.inServerAccessRole(req, "A"))
            {
                return(new ContentResult()
                {
                    Content = "User does not have suffiecient rights (Administrator required)", StatusCode = (int)System.Net.HttpStatusCode.Unauthorized
                });
            }
            if (string.IsNullOrEmpty(cmd) || !validcmds.Any(cmd.Contains))
            {
                return(new BadRequestObjectResult("Invalid Command....Valid commands are link, unlink and list"));
            }
            //Are we linking the correct resource type
            if (string.IsNullOrEmpty(res) || !allowedresources.Any(res.Contains))
            {
                return(new BadRequestObjectResult("Resource must be Patient,Practitioner or RelatedPerson"));
            }

            ClaimsIdentity ci      = (ClaimsIdentity)principal.Identity;
            string         aadten  = (string.IsNullOrEmpty(ci.Tenant()) ? "Unknown" : ci.Tenant());
            FhirJsonParser _parser = new FhirJsonParser();

            _parser.Settings.AcceptUnknownMembers   = true;
            _parser.Settings.AllowUnrecognizedEnums = true;
            //Get a FHIR Client so we can talk to the FHIR Server
            log.LogInformation($"Instanciating FHIR Client Proxy");
            FHIRClient fhirClient  = FHIRClientFactory.getClient(log);
            int        i_link_days = 0;

            int.TryParse(System.Environment.GetEnvironmentVariable("FP-LINK-DAYS"), out i_link_days);
            if (i_link_days == 0)
            {
                i_link_days = 365;
            }
            //Load the resource to Link
            var fhirresp = await fhirClient.LoadResource(res + "/" + id, null, false, req.Headers);

            var lres = _parser.Parse <Resource>((string)fhirresp.Content);

            if (lres.ResourceType == Hl7.Fhir.Model.ResourceType.OperationOutcome)
            {
                return(new BadRequestObjectResult(lres.ToString()));
            }
            CloudTable table = Utils.getTable();

            switch (cmd)
            {
            case "link":
                LinkEntity linkentity = new LinkEntity(res, aadten + "-" + name);
                linkentity.ValidUntil       = DateTime.Now.AddDays(i_link_days);
                linkentity.LinkedResourceId = id;
                Utils.setLinkEntity(table, linkentity);
                return(new OkObjectResult($"Identity: {name} in directory {aadten} is now linked to {res}/{id}"));

            case "unlink":
                LinkEntity delentity = Utils.getLinkEntity(table, res, aadten + "-" + name);
                if (delentity == null)
                {
                    return(new OkObjectResult($"Resource {res}/{id} has no links to Identity {name} in directory {aadten}"));
                }
                Utils.deleteLinkEntity(table, delentity);
                return(new OkObjectResult($"Identity: {name} in directory {aadten} has been unlinked from {res}/{id}"));

            case "list":
                LinkEntity entity = Utils.getLinkEntity(table, res, aadten + "-" + name);
                if (entity != null)
                {
                    return(new OkObjectResult($"Resource {res}/{id} is linked to Identity: {name} in directory {aadten}"));
                }
                else
                {
                    return(new OkObjectResult($"Resource {res}/{id} has no links to Identity {name} in directory {aadten}"));
                }
            }
            return(new OkObjectResult($"No action taken Identity: {name}"));
        }
Пример #26
0
        /// <inheritdoc />
        public void Load(IServiceCollection services)
        {
            EnsureArg.IsNotNull(services, nameof(services));

            var jsonParser     = new FhirJsonParser(DefaultParserSettings.Settings);
            var jsonSerializer = new FhirJsonSerializer();

            var xmlParser     = new FhirXmlParser();
            var xmlSerializer = new FhirXmlSerializer();

            services.AddSingleton(jsonParser);
            services.AddSingleton(jsonSerializer);
            services.AddSingleton(xmlParser);
            services.AddSingleton(xmlSerializer);

            ResourceElement SetMetadata(Resource resource, string versionId, DateTimeOffset lastModified)
            {
                resource.VersionId        = versionId;
                resource.Meta.LastUpdated = lastModified;
                return(resource.ToResourceElement());
            }

            services.AddSingleton <IReadOnlyDictionary <FhirResourceFormat, Func <string, string, DateTimeOffset, ResourceElement> > >(_ =>
            {
                return(new Dictionary <FhirResourceFormat, Func <string, string, DateTimeOffset, ResourceElement> >
                {
                    {
                        FhirResourceFormat.Json, (str, version, lastModified) =>
                        {
                            var resource = jsonParser.Parse <Resource>(str);
                            return SetMetadata(resource, version, lastModified);
                        }
                    },
                    {
                        FhirResourceFormat.Xml, (str, version, lastModified) =>
                        {
                            var resource = xmlParser.Parse <Resource>(str);
                            return SetMetadata(resource, version, lastModified);
                        }
                    },
                });
            });

            services.AddSingleton <ResourceDeserializer>();

            services.Add <FormatterConfiguration>()
            .Singleton()
            .AsSelf()
            .AsService <IPostConfigureOptions <MvcOptions> >()
            .AsService <IProvideCapability>();

            services.AddSingleton <IContentTypeService, ContentTypeService>();
            services.AddSingleton <OperationOutcomeExceptionFilterAttribute>();
            services.AddSingleton <ValidateContentTypeFilterAttribute>();
            services.AddSingleton <ValidateExportRequestFilterAttribute>();

            // HTML
            // If UI is supported, then add the formatter so that the
            // document can be output in HTML view.
            if (_featureConfiguration.SupportsUI)
            {
                services.Add <HtmlOutputFormatter>()
                .Singleton()
                .AsSelf()
                .AsService <TextOutputFormatter>();
            }

            services.Add <FhirJsonInputFormatter>()
            .Singleton()
            .AsSelf()
            .AsService <TextInputFormatter>();

            services.Add <FhirJsonOutputFormatter>()
            .Singleton()
            .AsSelf()
            .AsService <TextOutputFormatter>();

            if (_featureConfiguration.SupportsXml)
            {
                services.Add <FhirXmlInputFormatter>()
                .Singleton()
                .AsSelf()
                .AsService <TextInputFormatter>();

                services.Add <FhirXmlOutputFormatter>()
                .Singleton()
                .AsSelf()
                .AsService <TextOutputFormatter>();
            }

            services.Add <FhirRequestContextAccessor>()
            .Singleton()
            .AsSelf()
            .AsService <IFhirRequestContextAccessor>();

            services.AddSingleton <CorrelationIdProvider>(_ => () => Guid.NewGuid().ToString());

            // Add conformance provider for implementation metadata.
            services.AddSingleton <IConfiguredConformanceProvider, DefaultConformanceProvider>();

            services.Add <ConformanceProvider>()
            .Singleton()
            .AsSelf()
            .AsService <IConformanceProvider>();

            services.Add <SystemConformanceProvider>()
            .Singleton()
            .AsSelf()
            .AsService <ISystemConformanceProvider>();

            services.Add <SecurityProvider>()
            .Singleton()
            .AsSelf()
            .AsService <IProvideCapability>();

            services.TypesInSameAssembly(KnownAssemblies.Core, KnownAssemblies.CoreVersionSpecific)
            .AssignableTo <IProvideCapability>()
            .Transient()
            .AsService <IProvideCapability>();

            services.AddSingleton <INarrativeHtmlSanitizer, NarrativeHtmlSanitizer>();

            services.AddSingleton <IModelAttributeValidator, ModelAttributeValidator>();

            services.AddSingleton <IClaimsExtractor, PrincipalClaimsExtractor>();

            ModelExtensions.SetModelInfoProvider();
            services.Add(_ => ModelInfoProvider.Instance).Singleton().AsSelf().AsImplementedInterfaces();

            // Register a factory to resolve a scope that returns all components that provide capabilities
            services.AddFactory <IScoped <IEnumerable <IProvideCapability> > >();

            services.AddLazy();
            services.AddScoped();
        }
Пример #27
0
        public Stream TerminzBatch()
        {
            string rv = string.Empty;

            string responseType = GetResponseType();
            string fhirVersion  = GetFhirVersion();

            // get Bundle from the Request Stream

            string       reqBody   = string.Empty;
            UTF8Encoding enc       = new UTF8Encoding();
            Stream       reqStream = OperationContext.Current.RequestContext.RequestMessage.GetBody <Stream>();

            using (StreamReader reader = new StreamReader(reqStream, enc))
            {
                reqBody = reader.ReadToEnd();
            }

            string reqType = WebOperationContext.Current.IncomingRequest.ContentType.ToLower();

            Resource fhirResource;

            if (reqType.Contains("json"))
            {
                FhirJsonParser fjp = new FhirJsonParser();
                fhirResource = fjp.Parse <Resource>(reqBody);
            }
            else
            {
                FhirXmlParser fxp = new FhirXmlParser();
                fhirResource = fxp.Parse <Resource>(reqBody);
            }

            if (fhirResource.ResourceType == ResourceType.Bundle)
            {
                Bundle fb = (Bundle)fhirResource;
                if (fb.Type == Bundle.BundleType.Batch)
                {
                    Bundle responseBundle = new Bundle();

                    responseBundle.Id   = Guid.NewGuid().ToString();
                    responseBundle.Type = Bundle.BundleType.BatchResponse;

                    foreach (Bundle.EntryComponent comp in fb.Entry)
                    {
                        Bundle.RequestComponent rc = comp.Request;

                        if (rc.Method == Bundle.HTTPVerb.GET)
                        {
                            if (rc.Url.IndexOf("$validate-code") > 0)
                            {
                                // extract and parse query string to get parameters
                                int    qsPos       = rc.Url.IndexOf('?');
                                string querystring = (qsPos < rc.Url.Length - 1) ? rc.Url.Substring(qsPos + 1) : String.Empty;
                                qParam = System.Web.HttpUtility.ParseQueryString(querystring);
                                // extract resource (CodeSystem or ValueSet) ID
                                string resourceID   = string.Empty;
                                string resourceName = resourceID.IndexOf("/ValueSet/") > 0 ? "ValueSet" : "CodeSystem";
                                try
                                {
                                    resourceID = rc.Url.Remove(qsPos);
                                    int resNamePos = resourceID.IndexOf("/" + resourceName + "/");
                                    resourceID = resourceID.Substring(resNamePos + 9).Replace("/", "").Replace("$validate-code", "");
                                }
                                catch { }
                                ServiceInterface appSi = new ServiceInterface();
                                responseBundle.AddResourceEntry(appSi.GetFhirResource(resourceName, resourceID, "$validate-code", qParam, fhirVersion), string.Empty);
                            }
                            else
                            {
                                responseBundle.AddResourceEntry(OperationOutcome.ForMessage("Unrecognised Operation in Request..." + rc.Url, OperationOutcome.IssueType.Unknown), string.Empty);
                            }
                        }
                        else if (rc.Method == Bundle.HTTPVerb.POST)
                        {
                            if (rc.Url.IndexOf("$translate") > 0 && comp.Resource.ResourceType == ResourceType.Parameters)
                            {
                                // extract ConceptMap ID
                                string cmID = string.Empty;
                                try
                                {
                                    cmID = rc.Url.Replace("ConceptMap/", "").Replace("$translate", "").Replace("/", "");
                                }
                                catch { }
                                // get parameters
                                Parameters fParam = (Parameters)comp.Resource;
                                SetQueryParameters(fParam);
                                ServiceInterface appSi = new ServiceInterface();
                                responseBundle.AddResourceEntry(appSi.GetFhirResource("ConceptMap", cmID, "$translate", qParam, fhirVersion), string.Empty);
                            }
                            else
                            {
                                responseBundle.AddResourceEntry(OperationOutcome.ForMessage("Unrecognised Operation in Request..." + rc.Url, OperationOutcome.IssueType.Unknown), string.Empty);
                            }
                        }
                        else
                        {
                            responseBundle.AddResourceEntry(OperationOutcome.ForMessage("Method Not Supported in Batch Mode '" + rc.Method.ToString() + "'", OperationOutcome.IssueType.NotSupported), string.Empty);
                        }
                    }

                    fhirResource = responseBundle;
                }
                else
                {
                    fhirResource = OperationOutcome.ForMessage("No module could be found to handle the bundle type '" + fb.TypeName + "'", OperationOutcome.IssueType.NotFound);
                }
            }
            else
            {
                fhirResource = OperationOutcome.ForMessage("No module could be found to handle the request '" + fhirResource.ResourceType.ToString() + "'", OperationOutcome.IssueType.NotFound);
            }

            if (fhirResource.ResourceType == ResourceType.OperationOutcome)
            {
                AddNarrativeToOperationOutcome(fhirResource);
                OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
                response.StatusCode = HttpStatusCode.BadRequest;
                // if wish for more granular response codes, need Issue Type
                //OperationOutcome oo = (OperationOutcome)fhirResource;
                //OperationOutcome.IssueType opOutcome = (OperationOutcome.IssueType)oo.Issue[0].Code;
            }

            // convert to stream to remove leading XML elements and json quotes
            rv = SerializeResponse(fhirResource, responseType, SummaryType.False);
            return(new System.IO.MemoryStream(UTF8Encoding.Default.GetBytes(rv)));
        }
 public ExportDataValidationTests(HttpIntegrationTestFixture fixture, ITestOutputHelper testOutputHelper)
 {
     _testFhirClient = fixture.TestFhirClient;
     _outputHelper   = testOutputHelper;
     _fhirJsonParser = new FhirJsonParser();
 }
Пример #29
0
 /// <inheritdoc />
 public ValidateResourceInteractor(IFhirRepository repository, FhirJsonParser fhirParser)
     : base(repository)
 {
     this.FhirParser = fhirParser;
 }
Пример #30
0
        /// <summary>Tests net API.</summary>
        /// <param name="filename">Filename of the file.</param>
        /// <param name="contents">The contents.</param>
        /// <param name="loops">   The loops.</param>
        /// <returns>A TimingResult.</returns>
        private static TimingResult TestNetApi(string filename, string contents, int loops)
        {
            Version version = System.Reflection.Assembly.GetAssembly(typeof(FhirJsonParser)).GetName().Version;

            TimingResult timingResult = new TimingResult(filename, contents.Length, $"FHIR Net API, R4: {version}", loops);

            Console.WriteLine($"Measuring {timingResult.Filename} with {timingResult.LibraryName}...");

            Stopwatch timer = Stopwatch.StartNew();

            FhirJsonParser jsonParser = new FhirJsonParser(
                new ParserSettings
            {
                AcceptUnknownMembers   = true,
                AllowUnrecognizedEnums = true,
            });

            FhirJsonSerializer jsonSerializer = new FhirJsonSerializer(
                new SerializerSettings
            {
                AppendNewLine = false,
                Pretty        = false,
            });

            timingResult.SetupTime = timer.ElapsedMilliseconds;

            timer.Restart();

            var firstParsed = jsonParser.Parse(contents);

            timingResult.FirstParseTime = timer.ElapsedMilliseconds;

            if (firstParsed == null)
            {
                Console.WriteLine($"Parse failed!");
                timingResult.FailureCount++;
            }

            timer.Restart();
            string firstSerialized = jsonSerializer.SerializeToString(firstParsed);

            timingResult.FirstSerializeTime = timer.ElapsedMilliseconds;

            if (string.IsNullOrEmpty(firstSerialized))
            {
                Console.WriteLine($"Serialize failed!");
                timingResult.FailureCount++;
            }

            timingResult.ResourceType = firstParsed.GetType().Name;

            firstSerialized = null;

            timer.Restart();
            for (int i = 0; i < loops; i++)
            {
                var typed = jsonParser.Parse(contents);
                if (typed == null)
                {
                    Console.WriteLine($"Parse failed!");
                    timingResult.FailureCount++;
                }
            }

            timingResult.LoopedParseTime = timer.ElapsedMilliseconds;

            timer.Restart();
            for (int i = 0; i < loops; i++)
            {
                string serialized = jsonSerializer.SerializeToString(firstParsed);
                if (string.IsNullOrEmpty(serialized))
                {
                    Console.WriteLine($"Serialize failed!");
                    timingResult.FailureCount++;
                }
            }

            timingResult.LoopedSerializeTime = timer.ElapsedMilliseconds;

            return(timingResult);
        }