private static void convertResourceNav(string inputFile, string outputFile, IStructureDefinitionSummaryProvider provider) { //TODO: call validation after reading if (inputFile.Contains("expansions.") || inputFile.Contains("profiles-resources") || inputFile.Contains("profiles-others") || inputFile.Contains("valuesets.")) { return; } if (inputFile.EndsWith(".xml")) { var xml = File.ReadAllText(inputFile); var nav = XmlParsingHelpers.ParseToTypedElement(xml, provider); var json = nav.ToJson(); File.WriteAllText(outputFile, json); } else { var json = File.ReadAllText(inputFile); var nav = JsonParsingHelpers.ParseToTypedElement(json, provider, settings: new FhirJsonParsingSettings { AllowJsonComments = true }); var xml = nav.ToXml(); File.WriteAllText(outputFile, xml); } }
public static void TestProvidedOrder(IStructureDefinitionSummaryProvider provider) { hasCorrectOrder("Patient"); hasCorrectOrder("DomainResource"); hasCorrectOrder("HumanName"); hasCorrectOrder("Element"); hasCorrectOrder("string"); hasCorrectOrder("SimpleQuantity"); hasCorrectOrder("Distance"); hasCorrectOrder("xhtml"); void hasCorrectOrder(string typename) { var si = provider.Provide(typename); var children = si.GetElements(); var max = children.Aggregate(0, (a, i) => i.Order > a ? i.Order : fail($"Order of {i.ElementName} is out of order")); int fail(string message) { Assert.Fail(message); return(0); // will never be reached } } }
//[TestMethod] //public void TestResourceInfo() //{ // var ip = new PocoModelMetadataProvider(); // Assert.IsTrue(ip.IsResource("Patient")); // Assert.IsTrue(ip.IsResource("DomainResource")); // Assert.IsTrue(ip.IsResource("Resource")); // Assert.IsFalse(ip.IsResource("Identifier")); //} public static void TestCanLocateTypes(IStructureDefinitionSummaryProvider provider) { // Try getting a resource tryGetType("Patient"); // Try getting an abstract resource tryGetType("DomainResource", isAbstract: true); tryGetType("Resource", isAbstract: true); // Try a complex datatype tryGetType("HumanName"); // Try getting an abstract datatype tryGetType("Element", isAbstract: true); // Try a primitive tryGetType("string"); // Try constrained quantities tryGetType("SimpleQuantity", "Quantity"); tryGetType("Distance", "Quantity"); // The weird xhtml datatype tryGetType("xhtml"); void tryGetType(string typename, string baseTypeName = null, bool isAbstract = false) { var si = provider.Provide(typename); Assert.IsNotNull(si); Assert.AreEqual(baseTypeName ?? typename, si.TypeName); Assert.AreEqual(isAbstract, si.IsAbstract); } }
public static void TestValueIsNotAChild(IStructureDefinitionSummaryProvider provider) { var p = provider.Provide("string"); var children = p.GetElements(); Assert.IsFalse(children.Any(c => c.ElementName == "value")); }
public CustomResourcesInDocumentTests() { var customBasicStructureDefinitionJson = TestResourceReader.ReadTestData("CustomBasic-StructureDefinition-R3.json"); var customBasicStructureDefinition = new FhirJsonParser().Parse <StructureDefinition>(customBasicStructureDefinitionJson); _schemaProvider = SchemaProviders.CreateCustomSchemaProvider(customBasicStructureDefinition); _documentService = new DocumentService(_searchMock.Object, _changeMock.Object, _schemaProvider, _logger); }
/// <summary> /// Will update the child to reflect it being a child of this element, but will not yet add the child at any position within this element /// </summary> private void importChild(IStructureDefinitionSummaryProvider provider, ElementNode child, string name, int?position = null) { child.Name = name ?? child.Name; if (child.Name == null) { throw Error.Argument($"The ElementNode given should have its Name property set or the '{nameof(name)}' parameter should be given."); } // Remove this child from the current parent (if any), then reassign to me if (child.Parent != null) { Parent.Remove(child); } child.Parent = this; // If we add a child, we better overwrite it's definition with what // we think it should be - this way you can safely first create a node representing // an independently created root for a resource of datatype, and then add it to the tree. var childDefs = getChildDefinitions(provider ?? throw Error.ArgumentNull(nameof(provider))); var childDef = childDefs.Where(cd => cd.ElementName == child.Name).SingleOrDefault(); child.Definition = childDef ?? child.Definition; // if we don't know about the definition, stick with the old one (if any) if (child.InstanceType == null && child.Definition != null) { if (child.Definition.IsResource || child.Definition.Type.Length > 1) { // [EK20190822] This functionality has been removed since it heavily depends on knowledge about // FHIR types, it would automatically try to derive a *FHIR* type from the given child.Value, // however, this would not work correctly if the model used is something else than FHIR, // so this cannot be expected to work correctly in general, and I have chosen to remove // this. //// We are in a situation where we are on an polymorphic element, but the caller did not specify //// the instance type. We can try to auto-set it by deriving it from the instance's type, if it is a primitive //if (child.Value != null && IsSupportedValue(child.Value)) // child.InstanceType = TypeSpecifier.ForNativeType(child.Value.GetType()).Name; //else throw Error.Argument("The ElementNode given should have its InstanceType property set, since the element is a choice or resource."); } else { child.InstanceType = child.Definition.Type.Single().GetTypeName(); } } if (position == null || position >= ChildList.Count) { ChildList.Add(child); } else { ChildList.Insert(position.Value, child); } }
/// <summary> /// Will update the child to reflect it being a child of this element, but will not yet add the child at any position within this element /// </summary> /// <param name="provider"></param> /// <param name="child"></param> /// <param name="name"></param> /// <param name="position"></param> private void importChild(IStructureDefinitionSummaryProvider provider, ElementNode child, string name, int?position = null) { child.Name = name ?? child.Name; if (child.Name == null) { throw Error.Argument($"The ElementNode given should have its Name property set or the '{nameof(name)}' parameter should be given."); } // Remove this child from the current parent (if any), then reassign to me if (child.Parent != null) { Parent.Remove(child); } child.Parent = this; // If we add a child, we better overwrite it's definition with what // we think it should be - this way you can safely first create a node representing // an independently created root for a resource of datatype, and then add it to the tree. var childDefs = getChildDefinitions(provider ?? throw Error.ArgumentNull(nameof(provider))); var childDef = childDefs.Where(cd => cd.ElementName == child.Name).SingleOrDefault(); child.Definition = childDef ?? child.Definition; // if we don't know about the definition, stick with the old one (if any) if (child.InstanceType == null && child.Definition != null) { if (child.Definition.IsResource || child.Definition.Type.Length > 1) { // We are in a situation where we are on an polymorphic element, but the caller did not specify // the instance type. We can try to auto-set it by deriving it from the instance's type, if it is a primitive if (child.Value != null && Primitives.TryGetPrimitiveTypeName(child.Value.GetType(), out string instanceType)) { child.InstanceType = instanceType; } else { throw Error.Argument("The ElementNode given should have its InstanceType property set, since the element is a choice or resource."); } } else { child.InstanceType = child.Definition.Type.Single().GetTypeName(); } } if (position == null || position >= ChildList.Count) { ChildList.Add(child); } else { ChildList.Insert(position.Value, child); } }
public DocumentService(ISearchRepository searchRepository, IResourceChangeRepository changeRepository, IStructureDefinitionSummaryProvider schemaProvider, ILogger <DocumentService> logger) { Check.NotNull(searchRepository, nameof(searchRepository)); Check.NotNull(changeRepository, nameof(changeRepository)); Check.NotNull(logger, nameof(logger)); _searchRepository = searchRepository; _changeRepository = changeRepository; _schemaProvider = schemaProvider; _logger = logger; }
public static ITypedElement ParseToTypedElement(string xml, IStructureDefinitionSummaryProvider provider, FhirXmlParsingSettings settings = null, TypedElementSettings tnSettings = null) { if (xml == null) { throw Error.ArgumentNull(nameof(xml)); } if (provider == null) { throw Error.ArgumentNull(nameof(provider)); } return(FhirXmlNode.Parse(xml, settings).ToTypedElement(provider, null, tnSettings)); }
public static void TestCanGetElements(IStructureDefinitionSummaryProvider provider) { var p = provider.Provide("Patient"); // Simple element (repeating) checkType(p, "identifier", true, "Identifier"); // Simple element checkType(p, "active", false, "boolean"); // Element with multiple reference types checkType(p, "careProvider", true, "Reference"); // Backbone element (repeating) var bbe = checkBBType(p, "contact", "BackboneElement", true); // Navigate into the backbone element checkType(bbe, "relationship", true, "CodeableConcept"); // Choice type checkType(p, "deceased", false, "boolean", "dateTime"); // Get base elements checkType(p, "text", false, "Narrative"); checkType(p, "contained", true, "Resource"); checkType(p, "extension", true, "Extension"); checkType(p, "id", false, "id"); checkType(p, "meta", false, "Meta"); // Should not have the special "value" attribute Assert.IsFalse(p.GetElements().Any(c => c.ElementName == "value")); var b = provider.Provide("Bundle"); checkType(b, "total", false, "unsignedInt"); checkType(b, "type", false, "code"); // Test types using nameReference var q = provider.Provide("Questionnaire"); var qgroup = checkBBType(q, "group", "BackboneElement", false); checkType(qgroup, "linkId", false, "string"); var qgroupgroup = checkBBType(qgroup, "group", "BackboneElement", true); checkType(qgroupgroup, "linkId", false, "string"); // Backbone elements within datatypes var tm = provider.Provide("Timing"); checkBBType(tm, "repeat", "Element", false); }
internal static ITypedElement ParseToTypedElement(string json, IStructureDefinitionSummaryProvider provider, string rootName = null, FhirJsonParsingSettings settings = null, TypedElementSettings tnSettings = null) { if (json == null) { throw Error.ArgumentNull(nameof(json)); } if (provider == null) { throw Error.ArgumentNull(nameof(provider)); } return(FhirJsonNode.Parse(json, rootName, settings).ToTypedElement(provider, null, tnSettings)); }
public ElementNode Add(IStructureDefinitionSummaryProvider provider, ElementNode child, string name = null) { if (provider == null) { throw new ArgumentNullException(nameof(provider)); } if (child == null) { throw new ArgumentNullException(nameof(child)); } importChild(provider, child, name); return(child); }
public static void TestSpecialTypes(IStructureDefinitionSummaryProvider provider) { // Narrative.div var div = provider.Provide("Narrative"); Assert.IsNotNull(div); checkType(div, "div", false, "xhtml"); // Element.id checkType(div, "id", false, "id"); var ext = provider.Provide("Extension"); // Extension.url checkType(ext, "url", false, "uri"); }
public ElementNode Add(IStructureDefinitionSummaryProvider provider, string name, object value = null, string instanceType = null) { if (provider == null) { throw new ArgumentNullException(nameof(provider)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } var child = new ElementNode(name, value, instanceType, null); // Add() will supply the definition and the instanceType (if necessary) return(Add(provider, child)); }
public void ReplaceWith(IStructureDefinitionSummaryProvider provider, ElementNode node) { if (provider == null) { throw new ArgumentNullException(nameof(provider)); } if (node == null) { throw new ArgumentNullException(nameof(node)); } if (Parent == null) { throw Error.Argument("Current node is a root node and cannot be replaced."); } Parent.Replace(provider, this, node); }
public TypedElementNode(ISourceNode element, string type, IStructureDefinitionSummaryProvider provider, TypedElementSettings settings = null) { if (element == null) { throw Error.ArgumentNull(nameof(element)); } Provider = provider ?? throw Error.ArgumentNull(nameof(provider)); _settings = settings ?? new TypedElementSettings(); if (element is IExceptionSource ies && ies.ExceptionHandler == null) { ies.ExceptionHandler = (o, a) => ExceptionHandler.NotifyOrThrow(o, a); } ShortPath = element.Name; Current = buildRootPosition(element, type, provider); }
public TypedElementOnSourceNode(ISourceNode source, string type, IStructureDefinitionSummaryProvider provider, TypedElementSettings settings = null) { if (source == null) { throw Error.ArgumentNull(nameof(source)); } Provider = provider ?? throw Error.ArgumentNull(nameof(provider)); _settings = settings ?? new TypedElementSettings(); if (source is IExceptionSource ies && ies.ExceptionHandler == null) { ies.ExceptionHandler = (o, a) => ExceptionHandler.NotifyOrThrow(o, a); } ShortPath = source.Name; _source = source; (InstanceType, Definition) = buildRootPosition(type); }
public EverythingService(ISearchRepository searchRepository, IResourceChangeRepository changeRepository, IStructureDefinitionSummaryProvider schemaProvider, ILogger <EverythingService> logger, IModelService modelService) { Check.NotNull(searchRepository, nameof(searchRepository)); Check.NotNull(changeRepository, nameof(changeRepository)); Check.NotNull(logger, nameof(logger)); _searchRepository = searchRepository; _changeRepository = changeRepository; _schemaProvider = schemaProvider; _modelService = modelService; _logger = logger; _compartmentPatient = JObject.Parse(ReadResourceFile("CompartmentPatientR4.json")); //_compartmentPatient = JObject.Parse(File.ReadAllText("CompartmentPatientR4.json")); _patientSearchList = _compartmentPatient.SelectTokens("$.resource[?(@.param)]").ToList <JToken>(); _logger.LogInformation($"Loaded patient-related resources, count: {_patientSearchList.Count}"); }
private static void convertResourceNav(string inputFile, string outputFile, IStructureDefinitionSummaryProvider provider) { if (inputFile.EndsWith(".xml")) { var xml = File.ReadAllText(inputFile); var nav = XmlParsingHelpers.ParseToTypedElement(xml, provider, new FhirXmlParsingSettings { PermissiveParsing = true }); var json = nav.ToJson(); File.WriteAllText(outputFile, json); } else { var json = File.ReadAllText(inputFile); var nav = JsonParsingHelpers.ParseToTypedElement(json, provider, settings: new FhirJsonParsingSettings { AllowJsonComments = true, PermissiveParsing = true }); var xml = nav.ToXml(); File.WriteAllText(outputFile, xml); } }
public static ElementNode Root(IStructureDefinitionSummaryProvider provider, string type, string name = null, object value = null) { if (provider == null) { throw Error.ArgumentNull(nameof(provider)); } if (type == null) { throw Error.ArgumentNull(nameof(type)); } var sd = provider.Provide(type); IElementDefinitionSummary definition = null; // Should we throw if type is not found? if (sd != null) { definition = ElementDefinitionSummary.ForRoot(sd); } return(new ElementNode(name ?? type, value, type, definition)); }
public void Replace(IStructureDefinitionSummaryProvider provider, ElementNode oldChild, ElementNode newChild) { if (provider == null) { throw new ArgumentNullException(nameof(provider)); } if (oldChild == null) { throw new ArgumentNullException(nameof(oldChild)); } if (newChild == null) { throw new ArgumentNullException(nameof(newChild)); } int childIndex = ChildList.IndexOf(oldChild); if (childIndex == -1) { throw Error.Argument("Node to be replaced is not one of the children of this node"); } importChild(provider, newChild, oldChild.Name, childIndex); Remove(oldChild); }
private IReadOnlyCollection <IElementDefinitionSummary> getChildDefinitions(IStructureDefinitionSummaryProvider provider) { LazyInitializer.EnsureInitialized(ref _childDefinitions, () => this.ChildDefinitions(provider)); return(_childDefinitions); }
public static async Task <TypedEntryResponse> ToTypedEntryResponseAsync(this EntryResponse response, IStructureDefinitionSummaryProvider provider) { var result = new TypedEntryResponse { ContentType = response.ContentType, Body = response.Body, Etag = response.Etag, Headers = response.Headers, LastModified = response.LastModified, Location = response.Location, ResponseUri = response.ResponseUri, Status = response.Status }; var body = response.GetBodyAsText(); if (!string.IsNullOrEmpty(body)) { result.TypedElement = await parseResourceAsync(body, response.ContentType, provider, response.IsSuccessful()).ConfigureAwait(false); } return(result); }
private static async Task <ITypedElement> parseResourceAsync(string bodyText, string contentType, IStructureDefinitionSummaryProvider provider, bool throwOnFormatException) { if (bodyText == null) { throw Error.ArgumentNull(nameof(bodyText)); } if (provider == null) { throw Error.ArgumentNull(nameof(provider)); } var fhirType = ContentType.GetResourceFormatFromContentType(contentType); if (fhirType == ResourceFormat.Unknown) { throw new UnsupportedBodyTypeException( "Endpoint returned a body with contentType '{0}', while a valid FHIR xml/json body type was expected. Is this a FHIR endpoint?" .FormatWith(contentType), contentType, bodyText); } if (!SerializationUtil.ProbeIsJson(bodyText) && !SerializationUtil.ProbeIsXml(bodyText)) { throw new UnsupportedBodyTypeException( "Endpoint said it returned '{0}', but the body is not recognized as either xml or json.".FormatWith(contentType), contentType, bodyText); } try { return((fhirType == ResourceFormat.Json) ? (await FhirJsonNode.ParseAsync(bodyText).ConfigureAwait(false)).ToTypedElement(provider) : (await FhirXmlNode.ParseAsync(bodyText).ConfigureAwait(false)).ToTypedElement(provider)); } catch (FormatException) when(!throwOnFormatException) { return(null); } }
public static void FullRoundtripOfAllExamples(string zipname, string dirname, string label, bool usingPoco, IStructureDefinitionSummaryProvider provider) { ZipArchive examples = ReadTestZip(zipname); // Create an empty temporary directory for us to dump the roundtripped intermediary files in string baseTestPath = Path.Combine(Path.GetTempPath(), dirname); createEmptyDir(baseTestPath); Debug.WriteLine(label); createEmptyDir(baseTestPath); doRoundTrip(examples, baseTestPath, usingPoco, provider); }
public GoogleFhirClient(Uri endpoint, FhirClientSettings settings = null, HttpMessageHandler messageHandler = null, IStructureDefinitionSummaryProvider provider = null) : base(endpoint, settings, messageHandler, provider) { var creds = GoogleCredential.GetApplicationDefault().CreateScoped("https://www.googleapis.com/auth/cloud-platform"); var toks = creds.UnderlyingCredential.GetAccessTokenForRequestAsync("https://oauth2.googleapis.com/token"); RequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", toks.GetAwaiter().GetResult()); Settings.PreferredFormat = ResourceFormat.Json; }
private static void convertFiles(string inputPath, string outputPath, bool usingPoco, IStructureDefinitionSummaryProvider provider) { var files = Directory.EnumerateFiles(inputPath); if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } foreach (string file in files) { if (file.Contains(".profile")) { continue; } if (file.Contains(".schema")) { continue; } string exampleName = Path.GetFileNameWithoutExtension(file); string ext = Path.GetExtension(file); var toExt = ext == ".xml" ? ".json" : ".xml"; string outputFile = Path.Combine(outputPath, exampleName) + toExt; Debug.WriteLine("Converting {0} [{1}->{2}] ", exampleName, ext, toExt); if (file.Contains("expansions.") || file.Contains("profiles-resources") || file.Contains("profiles-others") || file.Contains("valuesets.")) { continue; } if (usingPoco) { convertResourcePoco(file, outputFile); } else { convertResourceNav(file, outputFile, provider); } } Debug.WriteLine("Done!"); }
private static void doRoundTrip(ZipArchive examplesZip, string baseTestPath, bool usingPoco, IStructureDefinitionSummaryProvider provider) { var examplePath = Path.Combine(baseTestPath, "input"); Directory.CreateDirectory(examplePath); // Unzip files into this path Debug.WriteLine("Unzipping example files from {0} to {1}", examplesZip, examplePath); examplesZip.ExtractToDirectory(examplePath); var intermediate1Path = Path.Combine(baseTestPath, "intermediate1"); Debug.WriteLine("Converting files in {0} to {1}", baseTestPath, intermediate1Path); var sw = new Stopwatch(); sw.Start(); convertFiles(examplePath, intermediate1Path, usingPoco, provider); sw.Stop(); Debug.WriteLine("Conversion took {0} seconds", sw.ElapsedMilliseconds / 1000); sw.Reset(); var intermediate2Path = Path.Combine(baseTestPath, "intermediate2"); Debug.WriteLine("Re-converting files in {0} back to original format in {1}", intermediate1Path, intermediate2Path); sw.Start(); convertFiles(intermediate1Path, intermediate2Path, usingPoco, provider); sw.Stop(); Debug.WriteLine("Conversion took {0} seconds", sw.ElapsedMilliseconds / 1000); sw.Reset(); Debug.WriteLine("Comparing files in {0} to files in {1}", baseTestPath, intermediate2Path); compareFiles(examplePath, intermediate2Path); }
private static long convertFiles(string inputPath, string outputPath, bool usingPoco, IStructureDefinitionSummaryProvider provider, List <string> errors) { int fileCount = 0; var files = Directory.EnumerateFiles(inputPath); if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } int filesProcessed = 0; foreach (string file in files) { if (SkipFile(file)) { continue; } string exampleName = Path.GetFileNameWithoutExtension(file); string ext = Path.GetExtension(file); var toExt = ext == ".xml" ? ".json" : ".xml"; string outputFile = Path.Combine(outputPath, exampleName) + toExt; Debug.WriteLine("Converting {0} [{1}->{2}] ", exampleName, ext, toExt); if (file.Contains("expansions.") || file.Contains("profiles-resources") || file.Contains("profiles-others") || file.Contains("valuesets.")) { continue; } fileCount++; try { if (usingPoco) { convertResourcePoco(file, outputFile); } else { convertResourceNav(file, outputFile, provider); } } catch (Exception ex) { errors.Add($"{exampleName}{ext}: " + ex.Message); } } Debug.WriteLine("Done!"); return(fileCount); }
private NavigatorPosition buildRootPosition(ISourceNode element, string type, IStructureDefinitionSummaryProvider provider) { var rootType = type ?? element.GetResourceTypeIndicator(); if (rootType == null) { if (_settings.ErrorMode == TypedElementSettings.TypeErrorMode.Report) { throw Error.Argument(nameof(type), $"Cannot determine the type of the root element at '{element.Location}', " + $"please supply a type argument."); } else { return(NavigatorPosition.ForRoot(element, null, element.Name)); } } var elementType = provider.Provide(rootType); if (elementType == null) { if (_settings.ErrorMode == TypedElementSettings.TypeErrorMode.Report) { throw Error.Argument(nameof(type), $"Cannot locate type information for type '{rootType}'"); } else { return(NavigatorPosition.ForRoot(element, null, element.Name)); } } return(NavigatorPosition.ForRoot(element, elementType, element.Name)); }