public Resource Create(Resource entry)
        {
            var resourceJson = FHIRbaseHelper.FhirResourceToJson(entry);
            var resource = FHIRbase.Call("fhir.create")
                .WithJsonb(resourceJson)
                .Cast<string>();

            return FHIRbaseHelper.JsonToFhirResource(resource);
        }
Beispiel #2
0
        private async Task <int> CreateResourceIfNotExistsAsync(string databaseName, Resource r)
        {
            var retstatus = -1;             //Error

            try
            {
                if (r == null)
                {
                    return(retstatus);
                }
                var fh = HistoryStore.InsertResourceHistoryItem(r);
                if (fh == null)
                {
                    return(retstatus);
                }
                //Overflow remove attachments or error
                if (fh.Length > 500000)
                {
                    return(retstatus);
                }
                var obj      = JObject.Parse(fh);
                var inserted = await client.UpsertDocumentAsync(
                    UriFactory.CreateDocumentCollectionUri(databaseName, Enum.GetName(typeof(ResourceType), r.ResourceType)), obj).ConfigureAwait(false);

                retstatus = inserted.StatusCode == HttpStatusCode.Created ? 1 : 0;
                return(retstatus);
            }
            catch (DocumentClientException)
            {
                //Trace.TraceError("Error creating resource: {0}-{1}-{2} Message: {3}", databaseName,Enum.GetName(typeof(Hl7.Fhir.Model.ResourceType),r.ResourceType),r.Id,de.Message);
                HistoryStore.DeleteResourceHistoryItem(r);
                //Trace.TraceInformation("Resource history entry for {0}-{1} version {2} rolledback due to document creation error.", Enum.GetName(typeof(Hl7.Fhir.Model.ResourceType), r.ResourceType), r.Id, r.Meta.VersionId);
                return(retstatus);
            }
        }
 public static void Append(this Bundle bundle, Resource resource)
 {
     var entry = new Bundle.BundleEntryComponent();
     entry.Resource = resource;
     entry.Base = bundle.Base;
     bundle.Entry.Add(entry);
 }
Beispiel #4
0
        public HttpResponseMessage OperationPostBaseWithParameters(string operation, [FromBody] FhirModel.Resource Resource)
        {
            string BaseRequestUri = this.CalculateBaseURI("${operation}");
            IResourceServiceOutcome ResourceServiceOutcome = IPyroService.OperationPostBaseWithParameters(BaseRequestUri, Request, operation, Resource);

            return(IFhirRestResponse.GetHttpResponseMessage(ResourceServiceOutcome, Request, ResourceServiceOutcome.SummaryType));
        }
Beispiel #5
0
        public HttpResponseMessage Base([FromBody] FhirModel.Resource resource)
        {
            string BaseRequestUri = this.CalculateBaseURI("");
            IResourceServiceOutcome ResourceServiceOutcome = IPyroService.Base(BaseRequestUri, Request, resource);

            return(IFhirRestResponse.GetHttpResponseMessage(ResourceServiceOutcome, Request, ResourceServiceOutcome.SummaryType));
        }
        public static bool TryValidate(Resource resource, ICollection<ValidationResult> validationResults=null)
        {
            if(resource == null) throw new ArgumentNullException("resource");

            var results = validationResults ?? new List<ValidationResult>();
            return Validator.TryValidateObject(resource, ValidationContextFactory.Create(resource, null), results, true);
        }
Beispiel #7
0
        public List <Hl7.Fhir.Model.Observation> observationsByID(string id)
        {
            List <Hl7.Fhir.Model.Observation> observations = new List <Observation>();

            try
            {
                //Attempt to send the resource to the server endpoint
                UriBuilder UriBuilderx = new UriBuilder(FhirClientEndPoint);
                UriBuilderx.Path = "Patient/" + id;
                Hl7.Fhir.Model.Resource ReturnedResource = _client.InstanceOperation(UriBuilderx.Uri, "everything");

                if (ReturnedResource is Hl7.Fhir.Model.Bundle)
                {
                    Hl7.Fhir.Model.Bundle ReturnedBundle = ReturnedResource as Hl7.Fhir.Model.Bundle;
                    foreach (var Entry in ReturnedBundle.Entry)
                    {
                        if (Entry.Resource is Observation)
                        {
                            observations.Add((Observation)Entry.Resource);
                        }
                    }
                }
                else
                {
                    throw new Exception("Operation call must return a bundle resource");
                }
            }
            catch (Hl7.Fhir.Rest.FhirOperationException FhirOpExec)
            {
                Console.WriteLine("An error message: " + FhirOpExec.Message);
            }
            return(observations);
        }
Beispiel #8
0
        public Hl7.Fhir.Model.Bundle everythingById(string id)
        {
            Hl7.Fhir.Model.Bundle ReturnedBundle = null;

            try
            {
                //Attempt to send the resource to the server endpoint
                UriBuilder UriBuilderx = new UriBuilder(FhirClientEndPoint);
                UriBuilderx.Path = "Patient/" + id;
                Hl7.Fhir.Model.Resource ReturnedResource = _client.InstanceOperation(UriBuilderx.Uri, "everything");

                if (ReturnedResource is Hl7.Fhir.Model.Bundle)
                {
                    ReturnedBundle = ReturnedResource as Hl7.Fhir.Model.Bundle;
                    Console.WriteLine("Received: " + ReturnedBundle.Total + " results. ");
                }
                else
                {
                    throw new Exception("Operation call must return a bundle resource");
                }
                Console.WriteLine();
            }
            catch (Hl7.Fhir.Rest.FhirOperationException FhirOpExec)
            {
                //Process any Fhir Errors returned as OperationOutcome resource
                Console.WriteLine();
                Console.WriteLine("An error message: " + FhirOpExec.Message);
                Console.WriteLine();
                string    xml  = Hl7.Fhir.Serialization.FhirSerializer.SerializeResourceToXml(FhirOpExec.Outcome);
                XDocument xDoc = XDocument.Parse(xml);
                Console.WriteLine(xDoc.ToString());
            }
            return(ReturnedBundle);
        }
        // @SuppressWarnings("deprecation")
        private void testBoolean(Model.Resource resource, Model.Base focus, String focusType, String expression, boolean value)
        {
            var input     = focus.ToTypedElement();
            var container = resource?.ToTypedElement();

            Assert.True(input.IsBoolean(expression, value, new EvaluationContext(container)));
        }
Beispiel #10
0
 private void testInvalid(Model.Resource resource, ErrorType type, String expression)
 {
     try
     {
         var resourceNav = new PocoNavigator(resource);
         resourceNav.Select(expression);
         throw new Exception();
     }
     catch (FormatException)
     {
         if (type != ErrorType.Syntax)
         {
             throw new Exception();
         }
     }
     catch (InvalidCastException)
     {
         if (type != ErrorType.Semantics)
         {
             throw new Exception();
         }
     }
     catch (InvalidOperationException)
     {
         if (type != ErrorType.Semantics)
         {
             throw new Exception();
         }
     }
 }
Beispiel #11
0
        public HttpResponseMessage ConditionalPut(string ResourceName, [FromBody] FhirModel.Resource resource)
        {
            string BaseRequestUri = this.CalculateBaseURI("{ResourceName}");
            IResourceServiceOutcome ResourceServiceOutcome = IPyroService.ConditionalPut(BaseRequestUri, Request, ResourceName, resource);

            return(IFhirRestResponse.GetHttpResponseMessage(ResourceServiceOutcome, Request, ResourceServiceOutcome.SummaryType));
        }
Beispiel #12
0
        // @SuppressWarnings("deprecation")
        private void testBoolean(Model.Resource resource, Model.Base focus, String focusType, String expression, boolean value)
        {
            var input     = new PocoNavigator(focus);
            var container = resource != null ? new PocoNavigator(resource) : null;

            Assert.True(input.IsBoolean(expression, value, container));
        }
Beispiel #13
0
        private static Bundle.BundleEntryComponent CreateEntryForResource(Resource resource)
        {
            var entry = new Bundle.BundleEntryComponent();
            entry.Resource = resource;
//            entry.FullUrl = resource.ResourceIdentity().ToString();
            entry.FullUrl = resource.ExtractKey().ToUriString();
            return entry;
        }
Beispiel #14
0
        public static void Append(this Bundle bundle, Bundle.HTTPVerb method, Resource resource)
        {
            Bundle.BundleEntryComponent entry = CreateEntryForResource(resource);

            if (entry.Request == null) entry.Request = new Bundle.BundleEntryRequestComponent();
            entry.Request.Method = method;
            bundle.Entry.Add(entry);
        }
Beispiel #15
0
        public async Task <int> UpsertFhirResourceAsync(Resource r)
        {
            await CreateDocumentCollectionIfNotExistsAsync(DbName, Enum.GetName(typeof(ResourceType), r.ResourceType)).ConfigureAwait(false);

            var x = await CreateResourceIfNotExistsAsync(DbName, r).ConfigureAwait(false);

            return(x);
        }
Beispiel #16
0
        internal static ResourceEntry CreateFromResource(Resource resource, Uri id, DateTimeOffset updated, string title = null)
        {
            var result = ResourceEntry.Create(resource);
            initializeResourceEntry(result, id, updated, title);

            result.Resource = resource;

            return result;
        }
Beispiel #17
0
 public static void Append(this Bundle bundle, Bundle.HTTPVerb method, Resource resource)
 {
     var entry = new Bundle.BundleEntryComponent();
     entry.Resource = resource;
     entry.Base = bundle.Base;
     if (entry.Transaction == null) entry.Transaction = new Bundle.BundleEntryTransactionComponent();
     entry.Transaction.Method = method;
     bundle.Entry.Add(entry);
 }
Beispiel #18
0
 private void put(IKey key, int level, Resource resource)
 {
     if (resource is DomainResource)
     {
         DomainResource d = resource as DomainResource;
         put(key, level, d);
         put(key, level + 1, d.Contained);
     }
     
 }
Beispiel #19
0
 public static Uri ConstructSelfLink(string baseuri, Resource resource)
 {
     // you must assume the resource has a verion id, otherwise a selflink is not possible
     string s = baseuri + "/" + resource.TypeName + "/" + resource.Id;
     if (resource.HasVersionId)
     {
         s += "/_history/" + resource.VersionId;
     }
     return new Uri(s);
 }
Beispiel #20
0
 public static BsonDocument CreateDocument(Resource resource)
 {
     if (resource != null)
     {
         string json = FhirSerializer.SerializeResourceToJson(resource);
         return BsonDocument.Parse(json);
     }
     else
     {
         return new BsonDocument();
     }
 }
Beispiel #21
0
        private void test(Model.Resource resource, String expression, IEnumerable <XElement> expected)
        {
            var tpXml = FhirSerializer.SerializeToXml(resource);
            var npoco = new PocoNavigator(resource);
            //       FhirPathEvaluatorTest.Render(npoco);

            IEnumerable <IElementNavigator> actual = npoco.Select(expression);

            Assert.Equal(expected.Count(), actual.Count());

            expected.Zip(actual, compare).Count();
        }
        private void test(Model.Resource resource, String expression, IEnumerable <XElement> expected)
        {
            var tpXml = new FhirXmlSerializer().SerializeToString(resource);
            var npoco = resource.ToTypedElement();
            //       FhirPathEvaluatorTest.Render(npoco);

            IEnumerable <ITypedElement> actual = npoco.Select(expression);

            Assert.Equal(expected.Count(), actual.Count());

            expected.Zip(actual, compare).Count();
        }
Beispiel #23
0
        public static void ResourceType(IKey key, Resource resource)
        {
            if (resource == null)
                throw Error.BadRequest("Request did not contain a body");

            if (key.TypeName != resource.TypeName)
            {
                throw Error.BadRequest(
                    "Received a body with a '{0}' resource, which does not match the indicated collection '{1}' in the url.",
                    resource.TypeName, key.TypeName);
            }

        }
Beispiel #24
0
        public Resource Create(Resource resource)
        {
            var resourceJson = ResourceDataHelper.FhirResourceToJson(resource);

            var createdResourceJson = _context
                .Call(FhirSchema.Name, FhirSchema.Func.Create)
                .WithJson(resourceJson)
                .Cast<String>();

            var createdResource = ResourceDataHelper.JsonToFhirResource(createdResourceJson);

            return createdResource;
        }
Beispiel #25
0
        public FhirModel4.Bundle CreateTransactionBundle(
            FhirModel.Resource resource,
            string requestUrl,
            FhirModel.HTTPVerb requestMethod
            )
        {
            var bundle = new FhirModel4.Bundle {
                Type = FhirModel.BundleType.Transaction
            };

            bundle.Entry.Add(CreateTransactionBundleEntry(resource, requestUrl, requestMethod));
            return(bundle);
        }
Beispiel #26
0
 // HACK: json extensions
 // Since WGM Chicago, extensions in json have their url in the json-name.
 // because MongoDB doesn't allow dots in the json-name, this hack will remove all extensions for now.
 public static void RemoveExtensions(Resource resource)
 {
     if (resource is DomainResource)
     {
         DomainResource domain = (DomainResource)resource;
         domain.Extension = null;
         domain.ModifierExtension = null;
         RemoveExtensionsFromElements(resource);
         foreach (Resource r in domain.Contained)
         {
             Hack.RemoveExtensions(r);
         }
     }
 }
Beispiel #27
0
 private Interaction(Bundle.HTTPVerb method, IKey key, DateTimeOffset? when, Resource resource)
 {
     if (resource != null)
     {
         key.ApplyTo(resource);
     }
     else
     {
         this.Key = key;
     }
     this.Resource = resource;
     this.Method = method;
     this.When = when ?? DateTimeOffset.Now;
     this.State = InteractionState.Undefined;
 }
Beispiel #28
0
        public Resource Deserialize(Resource existing=null)
        {
            // If there's no a priori knowledge of the type of Resource we will encounter,
            // we'll have to determine from the data itself. 
            var resourceTypeName = _reader.GetResourceTypeName();
            var mapping = _inspector.FindClassMappingForResource(resourceTypeName);

            if (mapping == null)
                throw Error.Format("Asked to deserialize unknown resource '" + resourceTypeName + "'", _reader);
             
            // Delegate the actual work to the ComplexTypeReader, since
            // the serialization of Resources and ComplexTypes are virtually the same
            var cplxReader = new ComplexTypeReader(_reader);
            return (Resource)cplxReader.Deserialize(mapping, existing);
        }
Beispiel #29
0
 public static FhirModel4.Bundle.EntryComponent CreateTransactionBundleEntry(
     FhirModel.Resource resource,
     string requestUrl,
     FhirModel.HTTPVerb requestMethod
     )
 {
     return(new FhirModel4.Bundle.EntryComponent
     {
         Request = new FhirModel4.Bundle.RequestComponent {
             Url = requestUrl, Method = requestMethod
         },
         FullUrl = "urn:uuid:" + Guid.NewGuid(),
         Resource = resource
     });
 }
Beispiel #30
0
        public static OperationOutcome AgainstProfile(Resource resource)
        {
            throw new NotImplementedException();

            /*
            // Phase 3, validate against a profile, if present
            var profileTags = entry.GetAssertedProfiles();
            if (profileTags.Count() == 0)
            {
                // If there's no profile specified, at least compare it to the "base" profile
                string baseProfile = CoreZipArtifactSource.CORE_SPEC_PROFILE_URI_PREFIX + entry.Resource.GetCollectionName();
                profileTags = new Uri[] { new Uri(baseProfile, UriKind.Absolute) };
            }

            var artifactSource = ArtifactResolver.CreateOffline();
            var specProvider = new SpecificationProvider(artifactSource);

            foreach (var profileTag in profileTags)
            {
                var specBuilder = new SpecificationBuilder(specProvider);
                specBuilder.Add(StructureFactory.PrimitiveTypes());
                specBuilder.Add(StructureFactory.MetaTypes());
                specBuilder.Add(StructureFactory.NonFhirNamespaces());
                specBuilder.Add(profileTag.ToString());
                specBuilder.Expand();

                string path = Directory.GetCurrentDirectory();

                var spec = specBuilder.ToSpecification();
                var nav = doc.CreateNavigator();
                nav.MoveToFirstChild();

                Report report = spec.Validate(nav);
                var errors = report.Errors;
                foreach (var error in errors)
                {
                    result.Issue.Add(createValidationResult("[Profile validator] " + error.Message, null));
                }
            }

            if(result.Issue.Count == 0)
                return null;
            else
                return result;
            */
        }
Beispiel #31
0
        public static OperationOutcome AgainstModel(Resource resource)
        {
            // Phase 1, validate against low-level rules built into the FHIR datatypes

            /*
            (!FhirValidator.TryValidate(entry.Resource, vresults, recurse: true))
            {
                foreach (var vresult in vresults)
                    result.Issue.Add(createValidationResult("[.NET validation] " + vresult.ErrorMessage, vresult.MemberNames));
            }
            //doc.Validate(SchemaCollection.ValidationSchemaSet,
            //    (source, args) => result.Issue.Add( createValidationResult("[XSD validation] " + args.Message,null))
            //);

            */
            throw new NotImplementedException();
        }
Beispiel #32
0
        public async Task <bool> DeleteFhirResourceAsync(Resource r)
        {
            //TODO Implement Delete by Identity
            await CreateDocumentCollectionIfNotExistsAsync(DbName, Enum.GetName(typeof(ResourceType), r.ResourceType)).ConfigureAwait(false);

            try
            {
                await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DbName,
                                                                              Enum.GetName(typeof(ResourceType), r.ResourceType), r.Id)).ConfigureAwait(false);

                return(true);
            }
            catch (DocumentClientException)
            {
                //Trace.TraceError("Error deleting resource type: {0} Id: {1} Message: {2}", r.ResourceType, r.Id, de.Message);
                return(false);
            }
        }
Beispiel #33
0
        public void SetBody(Resource resource, ResourceFormat format)
        {
            if (resource == null) throw Error.ArgumentNull("resource");

            if (resource is Binary)
            {
                var bin = (Binary)resource;
                _body = bin.Content;
                _contentType = bin.ContentType;
            }
            else
            {
                _body = format == ResourceFormat.Xml ?
                    FhirSerializer.SerializeResourceToXmlBytes(resource, summary: false) :
                    FhirSerializer.SerializeResourceToJsonBytes(resource, summary: false);

                _contentType = ContentType.BuildContentType(format, forBundle: false);
            }
        }
        public void AddEntryAct(Composition.SectionComponent section, XElement element)
        {
            if (section == null || element == null)
            {
                return;
            }

            Hl7.Fhir.Model.Resource resource = null;
            switch (section.Code.Coding[0].Code)
            {
            case "48765-2":
                resource = FromXml(new AllergyIntoleranceParser(Bundle), element);
                break;
            }

            if (resource != null)
            {
                section.Entry.Add(resource.GetResourceReference());
            }
        }
Beispiel #35
0
        public void WriteMetaData(ResourceEntry entry, int level, Resource resource)
        {
            if (level == 0)
            {
                Write(InternalField.ID, container_id);

                string selflink = entry.Links.SelfLink.ToString();
                Write(InternalField.SELFLINK, selflink);

                var resloc = new ResourceIdentity(container_id);
                Write(InternalField.JUSTID, resloc.Id);

                /*
                    //For testing purposes:
                    string term = resloc.Id;
                    List<Tag> tags = new List<Tag>() { new Tag(term, "http://tags.hl7.org", "labello"+term) } ;
                    tags.ForEach(Collect);
                /* */
                
                if (entry.Tags != null)
                {
                    entry.Tags.ToList().ForEach(Collect);
                }
                
            }
            else
            {
                
                string id = resource.Id;
                Write(InternalField.ID, container_id + "#" + id);
            }

            string category = resource.GetCollectionName();
                //ModelInfo.GetResourceNameForType(resource.GetType()).ToLower();
            Write(InternalField.RESOURCE, category);
            Write(InternalField.LEVEL, level);
        }
Beispiel #36
0
        /// <summary>
        /// The id of a contained resource is only unique in the context of its 'parent'. 
        /// We want to allow the indexStore implementation to treat the IndexValue that comes from the contained resources just like a regular resource.
        /// Therefore we make the id's globally unique, and adjust the references that point to it from its 'parent' accordingly.
        /// This method trusts on the knowledge that contained resources cannot contain any further nested resources. So one level deep only.
        /// </summary>
        /// <param name="resource"></param>
        /// <returns>A copy of resource, with id's of contained resources and references in resource adjusted to unique values.</returns>
        private Resource MakeContainedReferencesUnique(Resource resource)
        {
            //We may change id's of contained resources, and don't want that to influence other code. So we make a copy for our own needs.
            //Resource result = (dynamic)resource.DeepCopy(); //CK: This is how it should work, but unfortunately there is an error in the API (#146). So we invent a method of our own. 
            Resource result = CloneResource(resource);

            if (resource is DomainResource)
            {
                var domainResource = (DomainResource)result;
                if (domainResource.Contained != null && domainResource.Contained.Any())
                {
                    var refMap = new Dictionary<string, string>();

                    //Create a unique id for each contained resource.
                    foreach (var containedResource in domainResource.Contained)
                    {
                        var oldRef = "#" + containedResource.Id;
                        var newId = Guid.NewGuid().ToString();
                        containedResource.Id = newId;
                        var newRef = containedResource.TypeName + "/" + newId;
                        refMap.Add(oldRef, newRef);
                    }

                    //Replace references to these contained resources with the newly created id's.
                    A.ResourceVisitor.VisitByType(domainResource,
                         (el, path) =>
                         { var currentRef = (el as ResourceReference);
                             string replacementId;
                             refMap.TryGetValue(currentRef.Reference, out replacementId);
                             if (replacementId != null)
                                 currentRef.Reference = replacementId;
                         }
                        , typeof(ResourceReference));
                }
            }
            return result;
        }
        public void Resource_CRUD(Resource resource)
        {
            resource.Id = null;

            var createdResource = FHIRbase.Create(resource);

            Assert.That(createdResource, Is.Not.Null);
            Assert.That(createdResource.Id, Is.Not.Null.Or.Empty);
            Assert.That(createdResource.HasVersionId, Is.True);

            var readedResource = FHIRbase.Read(new ResourceKey
            {
                ResourceId = createdResource.Id,
                TypeName = createdResource.TypeName
            });

            Assert.That(readedResource, Is.Not.Null);
            Assert.That(readedResource.Id, Is.Not.Null.Or.Empty);
            Assert.That(readedResource.HasVersionId, Is.True);

            readedResource.Meta.Security.Add(new Coding("http://ehr.acme.org/identifiers/collections", "23234352356"));

            var updatedResource = FHIRbase.Update(readedResource);

            Assert.That(updatedResource, Is.Not.Null);
            Assert.That(updatedResource.Id, Is.Not.Null.Or.Empty);
            Assert.That(updatedResource.HasVersionId, Is.True);
            Assert.That(updatedResource.Meta.Security.First().Code == "23234352356");
            Assert.That(updatedResource.Meta.Security.First().System == "http://ehr.acme.org/identifiers/collections");

            FHIRbase.Delete(updatedResource);

            Assert.That(FHIRbase.IsDeleted(createdResource), Is.True);
            Assert.That(FHIRbase.IsDeleted(readedResource), Is.True);
            Assert.That(FHIRbase.IsDeleted(updatedResource), Is.True);
        }
Beispiel #38
0
        public void SetProtectedMetaTag(FhirModel.Resource Resource)
        {
            if (Resource.Meta == null)
            {
                Resource.Meta = new FhirModel.Meta();
            }
            if (Resource.Meta.Tag == null)
            {
                Resource.Meta.Tag = new List <FhirModel.Coding>();
            }

            var ProotectedCodes = Resource.Meta.Tag.Where(x => x.System == GetSystem() && x.Code == GetCode(Codes.Protected));

            if (ProotectedCodes.Count() == 0)
            {
                Resource.Meta.Tag.Add(GetCoding(Codes.Protected));
            }
            else if (ProotectedCodes.Count() > 1)
            {
                //Remove the many replace with just one
                Resource.Meta.Tag.RemoveAll(x => x.System == GetSystem() && x.Code == GetCode(Codes.Protected));
                Resource.Meta.Tag.Add(GetCoding(Codes.Protected));
            }
        }
Beispiel #39
0
        private void importResource(string filename, Resource resource)
        {
            Match match = Regex.Match(filename, @"\w+\(([^\)]+)\)\..*");

			string id = null;

            if (match.Success)
                id = match.Groups[1].Value;

            if (id == null) id = Guid.NewGuid().ToString();

            System.Console.Out.WriteLine(filename + " is a single resource with id " + id);

            ResourceEntry newEntry = ResourceEntry.Create(resource);

            string collection = resource.GetCollectionName();
            
            // klopt het dat hier een hl7.org uri voor moet?
            Uri identity = ResourceIdentity.Build(new Uri("http://hl7.org/fhir") ,collection, id);

            newEntry.Resource = resource;
            newEntry.AuthorName = "(imported from file)";
            newEntry.Id = identity;


            identity = ResourceIdentity.Build(new Uri("http://hl7.org/fhir"), collection, id, "1");
            // identity.VersionId = "1";

            newEntry.Links.SelfLink = identity;

            newEntry.LastUpdated = File.GetLastWriteTimeUtc(filename);
            newEntry.Published = File.GetCreationTimeUtc(filename);
            newEntry.Title = String.Format("{0} with id {1}", collection, id);

            add(newEntry);
        }
Beispiel #40
0
        void ExternalizeReferences(Resource resource)
        {
            Visitor action = (element, name) =>
            {
                if (element == null) return;

                if (element is ResourceReference)
                {
                    ResourceReference reference = (ResourceReference)element;
                    reference.Url = ExternalizeReference(reference.Url);
                }
                else if (element is FhirUri)
                {
                    FhirUri uri = (FhirUri)element;
                    uri.Value = ExternalizeReference(uri.Value);
                    //((FhirUri)element).Value = LocalizeReference(new Uri(((FhirUri)element).Value, UriKind.RelativeOrAbsolute)).ToString();
                }
                else if (element is Narrative)
                {
                    Narrative n = (Narrative)element;
                    n.Div = FixXhtmlDiv(n.Div);
                }

            };

            Type[] types = { typeof(ResourceReference), typeof(FhirUri), typeof(Narrative) };

            Engine.Auxiliary.ResourceVisitor.VisitByType(resource, action, types);
        }
Beispiel #41
0
        public FhirResponse Put(IKey key, Resource resource)
        {
            Validate.Key(key);
            Validate.ResourceType(key, resource);
            Validate.HasTypeName(key);
            Validate.HasResourceId(key);
            Validate.HasResourceId(resource);
            Validate.IsResourceIdEqual(key, resource);

            Interaction current = fhirStore.Get(key);

            Interaction interaction = Interaction.PUT(key, resource);
            transfer.Internalize(interaction);


            Store(interaction);

            // API: The api demands a body. This is wrong
            //CCR: The documentations specifies that servers should honor the Http return preference header
            Interaction result = fhirStore.Get(interaction.Key);
            transfer.Externalize(result);

            return Respond.WithResource(current != null ? HttpStatusCode.OK : HttpStatusCode.Created, result);
        }
 public static void SerializeResource(Resource resource, XmlWriter writer, bool summary=false)
 {
     FhirSerializer.Serialize(resource, new XmlFhirWriter(writer), summary);
 }
Beispiel #43
0
 public FhirResponse ConditionalCreate(IKey key, Resource resource, IEnumerable<Tuple<string, string>> query)
 {
     // DSTU2: search
     throw new NotImplementedException("This will be implemented after search is DSTU2");
 }
Beispiel #44
0
        /*
        public TagList TagsFromServer()
        {
            IEnumerable<Tag> tags = tagstore.Tags();
            return new TagList(tags);
        }
        
        public TagList TagsFromResource(string resourcetype)
        {
            RequestValidator.ValidateCollectionName(resourcetype);
            IEnumerable<Tag> tags = tagstore.Tags(resourcetype);
            return new TagList(tags);
        }


        public TagList TagsFromInstance(string collection, string id)
        {
            Uri key = BuildKey(collection, id);
            BundleEntry entry = store.Get(key);

            if (entry == null)
                throwNotFound("Cannot retrieve tags because entry {0}/{1} does not exist", collection, id);

            return new TagList(entry.Tags);
         }


        public TagList TagsFromHistory(string collection, string id, string vid)
        {
            Uri key = BuildKey(collection, id, vid);
            BundleEntry entry = store.Get(key);

            if (entry == null)
                throwNotFound("Cannot retrieve tags because entry {0}/{1} does not exist", collection, id, vid); 
           
            else if (entry is DeletedEntry)
            {
                throw new SparkException(HttpStatusCode.Gone,
                    "A {0} resource with version {1} and id {2} exists, but it is a deletion (deleted on {3}).",
                    collection, vid, id, (entry as DeletedEntry).When);
            }

            return new TagList(entry.Tags);
        }

        public void AffixTags(string collection, string id, IEnumerable<Tag> tags)
        {
            if (tags == null) throw new SparkException("No tags specified on the request");
            Uri key = BuildKey(collection, id);
            BundleEntry entry = store.Get(key);
            
            if (entry == null)
                throw new SparkException(HttpStatusCode.NotFound, "Could not set tags. The resource was not found.");

            entry.AffixTags(tags);
            store.Add(entry);
        }

        public void AffixTags(string collection, string id, string vid, IEnumerable<Tag> tags)
        {
            Uri key = BuildKey(collection, id, vid);
            if (tags == null) throw new SparkException("No tags specified on the request");

            BundleEntry entry = store.Get(key);
            if (entry == null)
                throw new SparkException(HttpStatusCode.NotFound, "Could not set tags. The resource was not found.");

            entry.AffixTags(tags);
            store.Replace(entry);   
        }

        public void RemoveTags(string collection, string id, IEnumerable<Tag> tags)
        {
            if (tags == null) throw new SparkException("No tags specified on the request");

            Uri key = BuildKey(collection, id);
            BundleEntry entry = store.Get(key);
            if (entry == null)
                throw new SparkException(HttpStatusCode.NotFound, "Could not set tags. The resource was not found.");

            if (entry.Tags != null)
            {
                entry.Tags = entry.Tags.Exclude(tags).ToList();
            }
            
            store.Replace(entry);
        }

        public void RemoveTags(string collection, string id, string vid, IEnumerable<Tag> tags)
        {
            if (tags == null) throw new SparkException("Can not delete tags if no tags specified were specified");

            Uri key = BuildKey(collection, id, vid);

            ResourceEntry entry = (ResourceEntry)store.Get(key);
            if (entry == null)
                throw new SparkException(HttpStatusCode.NotFound, "Could not set tags. The resource was not found.");


            if (entry.Tags != null)
                entry.Tags = entry.Tags.Exclude(tags).ToList();

            store.Replace(entry);
        }
        */

        public FhirResponse ValidateOperation(Key key, Resource resource)
        {
            if (resource == null) throw Error.BadRequest("Validate needs a Resource in the body payload");
            //if (entry.Resource == null) throw new SparkException("Validate needs a Resource in the body payload");

            //  DSTU2: validation
            // entry.Resource.Title = "Validation test entity";
            // entry.LastUpdated = DateTime.Now;
            // entry.Id = id != null ? ResourceIdentity.Build(Endpoint, collection, id) : null;

            Validate.ResourceType(key, resource);

            // DSTU2: validation
            var outcome = Validate.AgainstSchema(resource);

            if (outcome == null)
                return Respond.WithCode(HttpStatusCode.OK);
            else
                return Respond.WithResource(422, outcome);
        }
Beispiel #45
0
 public FhirResponse ConditionalUpdate(Key key, Resource resource, SearchParams _params)
 {
     Key existing = fhirIndex.FindSingle(key.TypeName, _params).WithoutVersion();
     return this.Update(existing, resource);
 }
Beispiel #46
0
 /// <summary>
 /// Updates a resource if it exist on the given id, or creates the resource if it is new.
 /// If a VersionId is included a version specific update will be attempted.
 /// </summary>
 /// <returns>200 OK (on success)</returns>
 public FhirResponse Update(IKey key, Resource resource)
 {
     if (key.HasVersionId())
     {
         return this.VersionSpecificUpdate(key, resource);
     }
     else
     {
         return this.Put(key, resource);
     }
 }
Beispiel #47
0
        //public FhirResponse Search(string type, IEnumerable<Tuple<string, string>> parameters, int pageSize, string sortby)
        //{
        //    Validate.TypeName(type);
        //    Uri link = localhost.Uri(type);

        //    IEnumerable<string> keys = store.List(type);
        //    var snapshot = pager.CreateSnapshot(Bundle.BundleType.Searchset, link, keys, );
        //    Bundle bundle = pager.GetFirstPage(snapshot);
        //    return Respond.WithBundle(bundle, localhost.Base);
        // DSTU2: search
        /*
        Query query = FhirParser.ParseQueryFromUriParameters(collection, parameters);
        ICollection<string> includes = query.Includes;

        SearchResults results = index.Search(query);

        if (results.HasErrors)
        {
            throw new SparkException(HttpStatusCode.BadRequest, results.Outcome);
        }

        Uri link = localhost.Uri(type).AddPath(results.UsedParameters);

        Bundle bundle = pager.GetFirstPage(link, keys, sortby);

        /*
        if (results.HasIssues)
        {
            var outcomeEntry = BundleEntryFactory.CreateFromResource(results.Outcome, new Uri("outcome/1", UriKind.Relative), DateTimeOffset.Now);
            outcomeEntry.SelfLink = outcomeEntry.Id;
            bundle.Entries.Add(outcomeEntry);
        }
        return Respond.WithBundle(bundle);
        */
        //}

        //public FhirResponse Update(IKey key, Resource resource)
        //{
        //    Validate.HasTypeName(key);
        //    Validate.HasNoVersion(key);
        //    Validate.ResourceType(key, resource);

        //    Interaction original = store.Get(key);

        //    if (original == null)
        //    {
        //        return Respond.WithError(HttpStatusCode.MethodNotAllowed,
        //            "Cannot update resource {0}/{1}, because it doesn't exist on this server",
        //            key.TypeName, key.ResourceId);
        //    }   

        //    Interaction interaction = Interaction.PUT(key, resource);
        //    interaction.Resource.AffixTags(original.Resource);

        //    transfer.Internalize(interaction);
        //    Store(interaction);

        //    // todo: does this require a response?
        //    transfer.Externalize(interaction);
        //    return Respond.WithEntry(HttpStatusCode.OK, interaction);
        //}

        public FhirResponse VersionSpecificUpdate(IKey versionedkey, Resource resource)
        {
            Validate.HasTypeName(versionedkey);
            Validate.HasVersion(versionedkey);

            Key key = versionedkey.WithoutVersion();
            Interaction current = fhirStore.Get(key);
            Validate.IsSameVersion(current.Key, versionedkey);

            return this.Put(key, resource);
        }