001/*
002 * #%L
003 * HAPI FHIR Structures - DSTU2 (FHIR v1.0.0)
004 * %%
005 * Copyright (C) 2014 - 2023 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 * http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.rest.server.provider.dstu2;
021
022import ca.uhn.fhir.context.FhirContext;
023import ca.uhn.fhir.context.api.BundleInclusionRule;
024import ca.uhn.fhir.model.api.IResource;
025import ca.uhn.fhir.model.api.Include;
026import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
027import ca.uhn.fhir.model.dstu2.resource.Bundle;
028import ca.uhn.fhir.model.dstu2.resource.Bundle.Entry;
029import ca.uhn.fhir.model.dstu2.resource.Bundle.Link;
030import ca.uhn.fhir.model.dstu2.valueset.SearchEntryModeEnum;
031import ca.uhn.fhir.model.primitive.IdDt;
032import ca.uhn.fhir.model.primitive.InstantDt;
033import ca.uhn.fhir.model.valueset.BundleEntrySearchModeEnum;
034import ca.uhn.fhir.model.valueset.BundleEntryTransactionMethodEnum;
035import ca.uhn.fhir.model.valueset.BundleTypeEnum;
036import ca.uhn.fhir.rest.api.BundleLinks;
037import ca.uhn.fhir.rest.api.Constants;
038import ca.uhn.fhir.rest.api.IVersionSpecificBundleFactory;
039import ca.uhn.fhir.util.ResourceReferenceInfo;
040import org.hl7.fhir.instance.model.api.IBaseResource;
041import org.hl7.fhir.instance.model.api.IPrimitiveType;
042
043import javax.annotation.Nonnull;
044import java.util.ArrayList;
045import java.util.Date;
046import java.util.HashSet;
047import java.util.List;
048import java.util.Set;
049import java.util.UUID;
050
051import static org.apache.commons.lang3.StringUtils.isNotBlank;
052
053public class Dstu2BundleFactory implements IVersionSpecificBundleFactory {
054        private String myBase;
055        private Bundle myBundle;
056        private FhirContext myContext;
057
058        public Dstu2BundleFactory(FhirContext theContext) {
059                myContext = theContext;
060        }
061
062        @Override
063        public void addResourcesToBundle(List<IBaseResource> theResult, BundleTypeEnum theBundleType, String theServerBase, BundleInclusionRule theBundleInclusionRule, Set<Include> theIncludes) {
064                ensureBundle();
065
066                List<IResource> includedResources = new ArrayList<IResource>();
067                Set<IdDt> addedResourceIds = new HashSet<IdDt>();
068
069                for (IBaseResource next : theResult) {
070                        if (next.getIdElement().isEmpty() == false) {
071                                addedResourceIds.add((IdDt) next.getIdElement());
072                        }
073                }
074
075                for (IBaseResource nextBaseRes : theResult) {
076                        IResource next = (IResource) nextBaseRes;
077
078                        Set<String> containedIds = new HashSet<String>();
079                        for (IResource nextContained : next.getContained().getContainedResources()) {
080                                if (nextContained.getId().isEmpty() == false) {
081                                        containedIds.add(nextContained.getId().getValue());
082                                }
083                        }
084
085                        List<ResourceReferenceInfo> references = myContext.newTerser().getAllResourceReferences(next);
086                        do {
087                                List<IResource> addedResourcesThisPass = new ArrayList<IResource>();
088
089                                for (ResourceReferenceInfo nextRefInfo : references) {
090                                        if (theBundleInclusionRule != null && !theBundleInclusionRule.shouldIncludeReferencedResource(nextRefInfo, theIncludes)) {
091                                                continue;
092                                        }
093
094                                        IResource nextRes = (IResource) nextRefInfo.getResourceReference().getResource();
095                                        if (nextRes != null) {
096                                                if (nextRes.getId().hasIdPart()) {
097                                                        if (containedIds.contains(nextRes.getId().getValue())) {
098                                                                // Don't add contained IDs as top level resources
099                                                                continue;
100                                                        }
101
102                                                        IdDt id = nextRes.getId();
103                                                        if (id.hasResourceType() == false) {
104                                                                String resName = myContext.getResourceType(nextRes);
105                                                                id = id.withResourceType(resName);
106                                                        }
107
108                                                        if (!addedResourceIds.contains(id)) {
109                                                                addedResourceIds.add(id);
110                                                                addedResourcesThisPass.add(nextRes);
111                                                        }
112
113                                                }
114                                        }
115                                }
116
117                                includedResources.addAll(addedResourcesThisPass);
118
119                                // Linked resources may themselves have linked resources
120                                references = new ArrayList<ResourceReferenceInfo>();
121                                for (IResource iResource : addedResourcesThisPass) {
122                                        List<ResourceReferenceInfo> newReferences = myContext.newTerser().getAllResourceReferences(iResource);
123                                        references.addAll(newReferences);
124                                }
125                        } while (references.isEmpty() == false);
126
127                        Entry entry = myBundle.addEntry().setResource(next);
128                        BundleEntryTransactionMethodEnum httpVerb = ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(next);
129                        if (httpVerb != null) {
130                                entry.getRequest().getMethodElement().setValueAsString(httpVerb.getCode());
131                        }
132                        populateBundleEntryFullUrl(next, entry);
133
134                        BundleEntrySearchModeEnum searchMode = ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(next);
135                        if (searchMode != null) {
136                                entry.getSearch().getModeElement().setValue(searchMode.getCode());
137                        }
138                }
139
140                /*
141                 * Actually add the resources to the bundle
142                 */
143                for (IResource next : includedResources) {
144                        Entry entry = myBundle.addEntry();
145                        entry.setResource(next).getSearch().setMode(SearchEntryModeEnum.INCLUDE);
146                        populateBundleEntryFullUrl(next, entry);
147                }
148
149        }
150
151        @Override
152        public void addRootPropertiesToBundle(String theId, @Nonnull BundleLinks theBundleLinks, Integer theTotalResults,
153                                                                                                          IPrimitiveType<Date> theLastUpdated) {
154                ensureBundle();
155
156                myBase = theBundleLinks.serverBase;
157
158                if (myBundle.getIdElement().isEmpty()) {
159                        myBundle.setId(theId);
160                }
161
162                if (ResourceMetadataKeyEnum.UPDATED.get(myBundle) == null) {
163                        ResourceMetadataKeyEnum.UPDATED.put(myBundle, (InstantDt) theLastUpdated);
164                }
165
166                if (!hasLink(Constants.LINK_SELF, myBundle) && isNotBlank(theBundleLinks.getSelf())) {
167                        myBundle.addLink().setRelation(Constants.LINK_SELF).setUrl(theBundleLinks.getSelf());
168                }
169                if (!hasLink(Constants.LINK_NEXT, myBundle) && isNotBlank(theBundleLinks.getNext())) {
170                        myBundle.addLink().setRelation(Constants.LINK_NEXT).setUrl(theBundleLinks.getNext());
171                }
172                if (!hasLink(Constants.LINK_PREVIOUS, myBundle) && isNotBlank(theBundleLinks.getPrev())) {
173                        myBundle.addLink().setRelation(Constants.LINK_PREVIOUS).setUrl(theBundleLinks.getPrev());
174                }
175
176                addTotalResultsToBundle(theTotalResults, theBundleLinks.bundleType);
177        }
178
179        @Override
180        public void addTotalResultsToBundle(Integer theTotalResults, BundleTypeEnum theBundleType) {
181                ensureBundle();
182
183                if (myBundle.getId().isEmpty()) {
184                        myBundle.setId(UUID.randomUUID().toString());
185                }
186
187                if (myBundle.getTypeElement().isEmpty() && theBundleType != null) {
188                        myBundle.getTypeElement().setValueAsString(theBundleType.getCode());
189                }
190
191                if (myBundle.getTotalElement().isEmpty() && theTotalResults != null) {
192                        myBundle.getTotalElement().setValue(theTotalResults);
193                }
194        }
195
196        private void ensureBundle() {
197                if (myBundle == null) {
198                        myBundle = new Bundle();
199                }
200        }
201
202        @Override
203        public IResource getResourceBundle() {
204                return myBundle;
205        }
206
207        private boolean hasLink(String theLinkType, Bundle theBundle) {
208                for (Link next : theBundle.getLink()) {
209                        if (theLinkType.equals(next.getRelation())) {
210                                return true;
211                        }
212                }
213                return false;
214        }
215
216        @Override
217        public void initializeWithBundleResource(IBaseResource theBundle) {
218                myBundle = (Bundle) theBundle;
219        }
220
221        private void populateBundleEntryFullUrl(IResource next, Entry entry) {
222                if (next.getId().hasBaseUrl()) {
223                        entry.setFullUrl(next.getId().toVersionless().getValue());
224                } else {
225                        if (isNotBlank(myBase) && next.getId().hasIdPart()) {
226                                IdDt id = next.getId().toVersionless();
227                                id = id.withServerBase(myBase, myContext.getResourceType(next));
228                                entry.setFullUrl(id.getValue());
229                        }
230                }
231        }
232
233        @Override
234        public List<IBaseResource> toListOfResources() {
235                ArrayList<IBaseResource> retVal = new ArrayList<IBaseResource>();
236                for (Entry next : myBundle.getEntry()) {
237                        if (next.getResource() != null) {
238                                retVal.add(next.getResource());
239                        } else if (next.getResponse().getLocationElement().isEmpty() == false) {
240                                IdDt id = new IdDt(next.getResponse().getLocation());
241                                String resourceType = id.getResourceType();
242                                if (isNotBlank(resourceType)) {
243                                        IResource res = (IResource) myContext.getResourceDefinition(resourceType).newInstance();
244                                        res.setId(id);
245                                        retVal.add(res);
246                                }
247                        }
248                }
249                return retVal;
250        }
251
252}