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);
        }
Пример #2
0
 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);
 }
Пример #3
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;
        }
Пример #4
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);
        }
Пример #5
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);
 }
Пример #6
0
        public Resource Create(Resource entry)
        {
            var resourceJson = FHIRbaseHelper.FhirResourceToJson(entry);
            var resource = FHIRbase.Call("fhir.create")
                .WithJsonb(resourceJson)
                .Cast<string>();

            return FHIRbaseHelper.JsonToFhirResource(resource);
        }
Пример #7
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;
        }
Пример #8
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);
     }
     
 }
Пример #9
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);
 }
Пример #10
0
 public static BsonDocument CreateDocument(Resource resource)
 {
     if (resource != null)
     {
         string json = FhirSerializer.SerializeResourceToJson(resource);
         return BsonDocument.Parse(json);
     }
     else
     {
         return new BsonDocument();
     }
 }
Пример #11
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;
        }
Пример #12
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);
            }

        }
Пример #13
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);
         }
     }
 }
Пример #14
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);
        }
Пример #15
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;
 }
Пример #16
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();
        }
Пример #17
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;
            */
        }
Пример #18
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);
            }
        }
Пример #19
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);
        }
Пример #20
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;
        }
Пример #21
0
        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);
        }
Пример #22
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);
        }
Пример #23
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);
        }
Пример #24
0
 public FhirResponse ConditionalUpdate(Key key, Resource resource, SearchParams _params)
 {
     Key existing = fhirIndex.FindSingle(key.TypeName, _params).WithoutVersion();
     return this.Update(existing, resource);
 }
Пример #25
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);
        }
Пример #26
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);
     }
 }
Пример #27
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);
        }
Пример #28
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");
 }
Пример #29
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);
        }
Пример #30
0
 public static void SerializeResource(Resource resource, XmlWriter writer, bool summary=false)
 {
     FhirSerializer.Serialize(resource, new XmlFhirWriter(writer), summary);
 }