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