001/*
002 * #%L
003 * HAPI FHIR Structures - DSTU2 (FHIR v1.0.0)
004 * %%
005 * Copyright (C) 2014 - 2024 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 jakarta.annotation.Nonnull;
041import org.hl7.fhir.instance.model.api.IBaseResource;
042import org.hl7.fhir.instance.model.api.IPrimitiveType;
043
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(
064                        List<IBaseResource> theResult,
065                        BundleTypeEnum theBundleType,
066                        String theServerBase,
067                        BundleInclusionRule theBundleInclusionRule,
068                        Set<Include> theIncludes) {
069                ensureBundle();
070
071                List<IResource> includedResources = new ArrayList<IResource>();
072                Set<IdDt> addedResourceIds = new HashSet<IdDt>();
073
074                for (IBaseResource next : theResult) {
075                        if (next.getIdElement().isEmpty() == false) {
076                                addedResourceIds.add((IdDt) next.getIdElement());
077                        }
078                }
079
080                for (IBaseResource nextBaseRes : theResult) {
081                        IResource next = (IResource) nextBaseRes;
082
083                        Set<String> containedIds = new HashSet<String>();
084                        for (IResource nextContained : next.getContained().getContainedResources()) {
085                                if (nextContained.getId().isEmpty() == false) {
086                                        containedIds.add(nextContained.getId().getValue());
087                                }
088                        }
089
090                        List<ResourceReferenceInfo> references = myContext.newTerser().getAllResourceReferences(next);
091                        do {
092                                List<IResource> addedResourcesThisPass = new ArrayList<IResource>();
093
094                                for (ResourceReferenceInfo nextRefInfo : references) {
095                                        if (theBundleInclusionRule != null
096                                                        && !theBundleInclusionRule.shouldIncludeReferencedResource(nextRefInfo, theIncludes)) {
097                                                continue;
098                                        }
099
100                                        IResource nextRes =
101                                                        (IResource) nextRefInfo.getResourceReference().getResource();
102                                        if (nextRes != null) {
103                                                if (nextRes.getId().hasIdPart()) {
104                                                        if (containedIds.contains(nextRes.getId().getValue())) {
105                                                                // Don't add contained IDs as top level resources
106                                                                continue;
107                                                        }
108
109                                                        IdDt id = nextRes.getId();
110                                                        if (id.hasResourceType() == false) {
111                                                                String resName = myContext.getResourceType(nextRes);
112                                                                id = id.withResourceType(resName);
113                                                        }
114
115                                                        if (!addedResourceIds.contains(id)) {
116                                                                addedResourceIds.add(id);
117                                                                addedResourcesThisPass.add(nextRes);
118                                                        }
119                                                }
120                                        }
121                                }
122
123                                includedResources.addAll(addedResourcesThisPass);
124
125                                // Linked resources may themselves have linked resources
126                                references = new ArrayList<ResourceReferenceInfo>();
127                                for (IResource iResource : addedResourcesThisPass) {
128                                        List<ResourceReferenceInfo> newReferences =
129                                                        myContext.newTerser().getAllResourceReferences(iResource);
130                                        references.addAll(newReferences);
131                                }
132                        } while (references.isEmpty() == false);
133
134                        Entry entry = myBundle.addEntry().setResource(next);
135                        BundleEntryTransactionMethodEnum httpVerb = ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(next);
136                        if (httpVerb != null) {
137                                entry.getRequest().getMethodElement().setValueAsString(httpVerb.getCode());
138                        }
139                        populateBundleEntryFullUrl(next, entry);
140
141                        BundleEntrySearchModeEnum searchMode = ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(next);
142                        if (searchMode != null) {
143                                entry.getSearch().getModeElement().setValue(searchMode.getCode());
144                        }
145                }
146
147                /*
148                 * Actually add the resources to the bundle
149                 */
150                for (IResource next : includedResources) {
151                        Entry entry = myBundle.addEntry();
152                        entry.setResource(next).getSearch().setMode(SearchEntryModeEnum.INCLUDE);
153                        populateBundleEntryFullUrl(next, entry);
154                }
155        }
156
157        @Override
158        public void addRootPropertiesToBundle(
159                        String theId,
160                        @Nonnull BundleLinks theBundleLinks,
161                        Integer theTotalResults,
162                        IPrimitiveType<Date> theLastUpdated) {
163                ensureBundle();
164
165                myBase = theBundleLinks.serverBase;
166
167                if (myBundle.getIdElement().isEmpty()) {
168                        myBundle.setId(theId);
169                }
170
171                if (ResourceMetadataKeyEnum.UPDATED.get(myBundle) == null) {
172                        ResourceMetadataKeyEnum.UPDATED.put(myBundle, (InstantDt) theLastUpdated);
173                }
174
175                if (!hasLink(Constants.LINK_SELF, myBundle) && isNotBlank(theBundleLinks.getSelf())) {
176                        myBundle.addLink().setRelation(Constants.LINK_SELF).setUrl(theBundleLinks.getSelf());
177                }
178                if (!hasLink(Constants.LINK_NEXT, myBundle) && isNotBlank(theBundleLinks.getNext())) {
179                        myBundle.addLink().setRelation(Constants.LINK_NEXT).setUrl(theBundleLinks.getNext());
180                }
181                if (!hasLink(Constants.LINK_PREVIOUS, myBundle) && isNotBlank(theBundleLinks.getPrev())) {
182                        myBundle.addLink().setRelation(Constants.LINK_PREVIOUS).setUrl(theBundleLinks.getPrev());
183                }
184
185                addTotalResultsToBundle(theTotalResults, theBundleLinks.bundleType);
186        }
187
188        @Override
189        public void addTotalResultsToBundle(Integer theTotalResults, BundleTypeEnum theBundleType) {
190                ensureBundle();
191
192                if (myBundle.getId().isEmpty()) {
193                        myBundle.setId(UUID.randomUUID().toString());
194                }
195
196                if (myBundle.getTypeElement().isEmpty() && theBundleType != null) {
197                        myBundle.getTypeElement().setValueAsString(theBundleType.getCode());
198                }
199
200                if (myBundle.getTotalElement().isEmpty() && theTotalResults != null) {
201                        myBundle.getTotalElement().setValue(theTotalResults);
202                }
203        }
204
205        private void ensureBundle() {
206                if (myBundle == null) {
207                        myBundle = new Bundle();
208                }
209        }
210
211        @Override
212        public IResource getResourceBundle() {
213                return myBundle;
214        }
215
216        private boolean hasLink(String theLinkType, Bundle theBundle) {
217                for (Link next : theBundle.getLink()) {
218                        if (theLinkType.equals(next.getRelation())) {
219                                return true;
220                        }
221                }
222                return false;
223        }
224
225        @Override
226        public void initializeWithBundleResource(IBaseResource theBundle) {
227                myBundle = (Bundle) theBundle;
228        }
229
230        private void populateBundleEntryFullUrl(IResource next, Entry entry) {
231                if (next.getId().hasBaseUrl()) {
232                        entry.setFullUrl(next.getId().toVersionless().getValue());
233                } else {
234                        if (isNotBlank(myBase) && next.getId().hasIdPart()) {
235                                IdDt id = next.getId().toVersionless();
236                                id = id.withServerBase(myBase, myContext.getResourceType(next));
237                                entry.setFullUrl(id.getValue());
238                        }
239                }
240        }
241
242        @Override
243        public List<IBaseResource> toListOfResources() {
244                ArrayList<IBaseResource> retVal = new ArrayList<IBaseResource>();
245                for (Entry next : myBundle.getEntry()) {
246                        if (next.getResource() != null) {
247                                retVal.add(next.getResource());
248                        } else if (next.getResponse().getLocationElement().isEmpty() == false) {
249                                IdDt id = new IdDt(next.getResponse().getLocation());
250                                String resourceType = id.getResourceType();
251                                if (isNotBlank(resourceType)) {
252                                        IResource res = (IResource)
253                                                        myContext.getResourceDefinition(resourceType).newInstance();
254                                        res.setId(id);
255                                        retVal.add(res);
256                                }
257                        }
258                }
259                return retVal;
260        }
261}