001/*
002 * #%L
003 * HAPI FHIR Structures - DSTU2 (FHIR v1.0.0)
004 * %%
005 * Copyright (C) 2014 - 2015 University Health Network
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 org.hl7.fhir.r4.hapi.rest.server;
021
022import ca.uhn.fhir.context.FhirContext;
023import ca.uhn.fhir.context.api.BundleInclusionRule;
024import ca.uhn.fhir.model.api.Include;
025import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
026import ca.uhn.fhir.model.valueset.BundleEntrySearchModeEnum;
027import ca.uhn.fhir.model.valueset.BundleEntryTransactionMethodEnum;
028import ca.uhn.fhir.model.valueset.BundleTypeEnum;
029import ca.uhn.fhir.rest.api.BundleLinks;
030import ca.uhn.fhir.rest.api.Constants;
031import ca.uhn.fhir.rest.api.IVersionSpecificBundleFactory;
032import ca.uhn.fhir.rest.server.RestfulServerUtils;
033import ca.uhn.fhir.util.ResourceReferenceInfo;
034import jakarta.annotation.Nonnull;
035import jakarta.annotation.Nullable;
036import org.hl7.fhir.instance.model.api.IAnyResource;
037import org.hl7.fhir.instance.model.api.IBaseResource;
038import org.hl7.fhir.instance.model.api.IIdType;
039import org.hl7.fhir.instance.model.api.IPrimitiveType;
040import org.hl7.fhir.r4.model.Bundle;
041import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent;
042import org.hl7.fhir.r4.model.Bundle.BundleLinkComponent;
043import org.hl7.fhir.r4.model.Bundle.SearchEntryMode;
044import org.hl7.fhir.r4.model.DomainResource;
045import org.hl7.fhir.r4.model.IdType;
046import org.hl7.fhir.r4.model.Resource;
047
048import java.math.BigDecimal;
049import java.util.ArrayList;
050import java.util.Date;
051import java.util.HashSet;
052import java.util.List;
053import java.util.Set;
054import java.util.UUID;
055
056import static org.apache.commons.lang3.StringUtils.isNotBlank;
057
058@SuppressWarnings("Duplicates")
059public class R4BundleFactory implements IVersionSpecificBundleFactory {
060        private String myBase;
061        private Bundle myBundle;
062        private final FhirContext myContext;
063
064        public R4BundleFactory(FhirContext theContext) {
065                myContext = theContext;
066        }
067
068        @Override
069        public void addResourcesToBundle(
070                        List<IBaseResource> theResult,
071                        BundleTypeEnum theBundleType,
072                        String theServerBase,
073                        BundleInclusionRule theBundleInclusionRule,
074                        Set<Include> theIncludes) {
075                ensureBundle();
076
077                List<IAnyResource> includedResources = new ArrayList<>();
078                Set<IIdType> addedResourceIds = new HashSet<>();
079
080                for (IBaseResource next : theResult) {
081                        if (!next.getIdElement().isEmpty()) {
082                                addedResourceIds.add(next.getIdElement());
083                        }
084                }
085
086                for (IBaseResource next : theResult) {
087                        Set<String> containedIds = new HashSet<>();
088
089                        if (next instanceof DomainResource) {
090                                for (Resource nextContained : ((DomainResource) next).getContained()) {
091                                        if (isNotBlank(nextContained.getId())) {
092                                                containedIds.add(nextContained.getId());
093                                        }
094                                }
095                        }
096
097                        List<ResourceReferenceInfo> references = myContext.newTerser().getAllResourceReferences(next);
098                        do {
099                                List<IAnyResource> addedResourcesThisPass = new ArrayList<>();
100
101                                for (ResourceReferenceInfo nextRefInfo : references) {
102                                        if (theBundleInclusionRule != null
103                                                        && !theBundleInclusionRule.shouldIncludeReferencedResource(nextRefInfo, theIncludes)) {
104                                                continue;
105                                        }
106
107                                        IAnyResource nextRes =
108                                                        (IAnyResource) nextRefInfo.getResourceReference().getResource();
109                                        if (nextRes != null) {
110                                                if (nextRes.getIdElement().hasIdPart()) {
111                                                        if (containedIds.contains(nextRes.getIdElement().getValue())) {
112                                                                // Don't add contained IDs as top level resources
113                                                                continue;
114                                                        }
115
116                                                        IIdType id = nextRes.getIdElement();
117                                                        if (!id.hasResourceType()) {
118                                                                String resName = myContext.getResourceType(nextRes);
119                                                                id = id.withResourceType(resName);
120                                                        }
121
122                                                        if (!addedResourceIds.contains(id)) {
123                                                                addedResourceIds.add(id);
124                                                                addedResourcesThisPass.add(nextRes);
125                                                        }
126                                                }
127                                        }
128                                }
129
130                                includedResources.addAll(addedResourcesThisPass);
131
132                                // Linked resources may themselves have linked resources
133                                references = new ArrayList<>();
134                                for (IAnyResource iResource : addedResourcesThisPass) {
135                                        List<ResourceReferenceInfo> newReferences =
136                                                        myContext.newTerser().getAllResourceReferences(iResource);
137                                        references.addAll(newReferences);
138                                }
139                        } while (!references.isEmpty());
140
141                        BundleEntryComponent entry = myBundle.addEntry().setResource((Resource) next);
142                        Resource nextAsResource = (Resource) next;
143                        IIdType id = populateBundleEntryFullUrl(next, entry);
144
145                        // Populate Request
146                        BundleEntryTransactionMethodEnum httpVerb =
147                                        ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(nextAsResource);
148                        if (httpVerb != null) {
149                                entry.getRequest().getMethodElement().setValueAsString(httpVerb.name());
150                                if (id != null) {
151                                        entry.getRequest().setUrl(id.toUnqualified().getValue());
152                                }
153                        }
154                        if (BundleEntryTransactionMethodEnum.DELETE.equals(httpVerb)) {
155                                entry.setResource(null);
156                        }
157
158                        // Populate Bundle.entry.response
159                        if (theBundleType != null) {
160                                switch (theBundleType) {
161                                        case BATCH_RESPONSE:
162                                        case TRANSACTION_RESPONSE:
163                                        case HISTORY:
164                                                if (id != null) {
165                                                        String version = id.getVersionIdPart();
166                                                        if ("1".equals(version)) {
167                                                                entry.getResponse().setStatus("201 Created");
168                                                        } else if (isNotBlank(version)) {
169                                                                entry.getResponse().setStatus("200 OK");
170                                                        }
171                                                        if (isNotBlank(version)) {
172                                                                entry.getResponse().setEtag(RestfulServerUtils.createEtag(version));
173                                                        }
174                                                }
175                                                break;
176                                }
177                        }
178
179                        // Populate Bundle.entry.search
180                        BundleEntrySearchModeEnum searchMode = ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(nextAsResource);
181                        if (searchMode != null) {
182                                entry.getSearch().getModeElement().setValueAsString(searchMode.getCode());
183                        }
184                        BigDecimal searchScore = ResourceMetadataKeyEnum.ENTRY_SEARCH_SCORE.get(nextAsResource);
185                        if (searchScore != null) {
186                                entry.getSearch().getScoreElement().setValue(searchScore);
187                        }
188                }
189
190                /*
191                 * Actually add the resources to the bundle
192                 */
193                for (IAnyResource next : includedResources) {
194                        BundleEntryComponent entry = myBundle.addEntry();
195                        entry.setResource((Resource) next).getSearch().setMode(SearchEntryMode.INCLUDE);
196                        populateBundleEntryFullUrl(next, entry);
197                }
198        }
199
200        @Override
201        public void addRootPropertiesToBundle(
202                        String theId,
203                        @Nonnull BundleLinks theBundleLinks,
204                        Integer theTotalResults,
205                        IPrimitiveType<Date> theLastUpdated) {
206                ensureBundle();
207
208                myBase = theBundleLinks.serverBase;
209
210                if (myBundle.getIdElement().isEmpty()) {
211                        myBundle.setId(theId);
212                }
213
214                if (myBundle.getMeta().getLastUpdated() == null && theLastUpdated != null) {
215                        myBundle.getMeta().getLastUpdatedElement().setValueAsString(theLastUpdated.getValueAsString());
216                }
217
218                if (hasNoLinkOfType(Constants.LINK_SELF, myBundle) && isNotBlank(theBundleLinks.getSelf())) {
219                        myBundle.addLink().setRelation(Constants.LINK_SELF).setUrl(theBundleLinks.getSelf());
220                }
221                if (hasNoLinkOfType(Constants.LINK_NEXT, myBundle) && isNotBlank(theBundleLinks.getNext())) {
222                        myBundle.addLink().setRelation(Constants.LINK_NEXT).setUrl(theBundleLinks.getNext());
223                }
224                if (hasNoLinkOfType(Constants.LINK_PREVIOUS, myBundle) && isNotBlank(theBundleLinks.getPrev())) {
225                        myBundle.addLink().setRelation(Constants.LINK_PREVIOUS).setUrl(theBundleLinks.getPrev());
226                }
227
228                addTotalResultsToBundle(theTotalResults, theBundleLinks.bundleType);
229        }
230
231        @Override
232        public void addTotalResultsToBundle(Integer theTotalResults, BundleTypeEnum theBundleType) {
233                ensureBundle();
234
235                if (myBundle.getIdElement().isEmpty()) {
236                        myBundle.setId(UUID.randomUUID().toString());
237                }
238
239                if (myBundle.getTypeElement().isEmpty() && theBundleType != null) {
240                        myBundle.getTypeElement().setValueAsString(theBundleType.getCode());
241                }
242
243                if (myBundle.getTotalElement().isEmpty() && theTotalResults != null) {
244                        myBundle.getTotalElement().setValue(theTotalResults);
245                }
246        }
247
248        private void ensureBundle() {
249                if (myBundle == null) {
250                        myBundle = new Bundle();
251                }
252        }
253
254        @Override
255        public IBaseResource getResourceBundle() {
256                return myBundle;
257        }
258
259        private boolean hasNoLinkOfType(String theLinkType, Bundle theBundle) {
260                for (BundleLinkComponent next : theBundle.getLink()) {
261                        if (theLinkType.equals(next.getRelation())) {
262                                return false;
263                        }
264                }
265                return true;
266        }
267
268        @Override
269        public void initializeWithBundleResource(IBaseResource theBundle) {
270                myBundle = (Bundle) theBundle;
271        }
272
273        @Nullable
274        private IIdType populateBundleEntryFullUrl(IBaseResource theResource, BundleEntryComponent theEntry) {
275                final IIdType idElement;
276                if (theResource.getIdElement().hasBaseUrl()) {
277                        idElement = theResource.getIdElement();
278                        theEntry.setFullUrl(idElement.toVersionless().getValue());
279                } else {
280                        if (isNotBlank(myBase) && theResource.getIdElement().hasIdPart()) {
281                                idElement = theResource.getIdElement().withServerBase(myBase, myContext.getResourceType(theResource));
282                                theEntry.setFullUrl(idElement.toVersionless().getValue());
283                        } else {
284                                idElement = null;
285                        }
286                }
287                return idElement;
288        }
289
290        @Override
291        public List<IBaseResource> toListOfResources() {
292                ArrayList<IBaseResource> retVal = new ArrayList<>();
293                for (BundleEntryComponent next : myBundle.getEntry()) {
294                        if (next.getResource() != null) {
295                                retVal.add(next.getResource());
296                        } else if (!next.getResponse().getLocationElement().isEmpty()) {
297                                IdType id = new IdType(next.getResponse().getLocation());
298                                String resourceType = id.getResourceType();
299                                if (isNotBlank(resourceType)) {
300                                        IAnyResource res = (IAnyResource)
301                                                        myContext.getResourceDefinition(resourceType).newInstance();
302                                        res.setId(id);
303                                        retVal.add(res);
304                                }
305                        }
306                }
307                return retVal;
308        }
309}