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.dstu3.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.dstu3.model.Bundle;
036import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent;
037import org.hl7.fhir.dstu3.model.Bundle.BundleLinkComponent;
038import org.hl7.fhir.dstu3.model.Bundle.SearchEntryMode;
039import org.hl7.fhir.dstu3.model.DomainResource;
040import org.hl7.fhir.dstu3.model.IdType;
041import org.hl7.fhir.dstu3.model.Resource;
042import org.hl7.fhir.instance.model.api.IAnyResource;
043import org.hl7.fhir.instance.model.api.IBaseResource;
044import org.hl7.fhir.instance.model.api.IIdType;
045import org.hl7.fhir.instance.model.api.IPrimitiveType;
046
047import java.math.BigDecimal;
048import java.util.ArrayList;
049import java.util.Date;
050import java.util.HashSet;
051import java.util.List;
052import java.util.Set;
053import java.util.UUID;
054
055import static org.apache.commons.lang3.StringUtils.isNotBlank;
056
057public class Dstu3BundleFactory implements IVersionSpecificBundleFactory {
058        private String myBase;
059        private Bundle myBundle;
060        private FhirContext myContext;
061
062        public Dstu3BundleFactory(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                        BundleEntryTransactionMethodEnum httpVerb =
144                                        ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(nextAsResource);
145                        if (httpVerb != null) {
146                                entry.getRequest().getMethodElement().setValueAsString(httpVerb.name());
147                                if (id != null) {
148                                        entry.getRequest().setUrl(id.toUnqualified().getValue());
149                                }
150                        }
151                        if (BundleEntryTransactionMethodEnum.DELETE.equals(httpVerb)) {
152                                entry.setResource(null);
153                        }
154
155                        // Populate Bundle.entry.response
156                        if (theBundleType != null) {
157                                switch (theBundleType) {
158                                        case BATCH_RESPONSE:
159                                        case TRANSACTION_RESPONSE:
160                                                if ("1".equals(id.getVersionIdPart())) {
161                                                        entry.getResponse().setStatus("201 Created");
162                                                } else if (isNotBlank(id.getVersionIdPart())) {
163                                                        entry.getResponse().setStatus("200 OK");
164                                                }
165                                                if (isNotBlank(id.getVersionIdPart())) {
166                                                        entry.getResponse().setEtag(RestfulServerUtils.createEtag(id.getVersionIdPart()));
167                                                }
168                                                break;
169                                }
170                        }
171
172                        // Populate Bundle.entry.search
173                        BundleEntrySearchModeEnum searchMode = ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(nextAsResource);
174                        if (searchMode != null) {
175                                entry.getSearch().getModeElement().setValueAsString(searchMode.getCode());
176                        }
177                        BigDecimal searchScore = ResourceMetadataKeyEnum.ENTRY_SEARCH_SCORE.get(nextAsResource);
178                        if (searchScore != null) {
179                                entry.getSearch().getScoreElement().setValue(searchScore);
180                        }
181                }
182
183                /*
184                 * Actually add the resources to the bundle
185                 */
186                for (IAnyResource next : includedResources) {
187                        BundleEntryComponent entry = myBundle.addEntry();
188                        entry.setResource((Resource) next).getSearch().setMode(SearchEntryMode.INCLUDE);
189                        populateBundleEntryFullUrl(next, entry);
190                }
191        }
192
193        @Override
194        public void addRootPropertiesToBundle(
195                        String theId,
196                        @Nonnull BundleLinks theBundleLinks,
197                        Integer theTotalResults,
198                        IPrimitiveType<Date> theLastUpdated) {
199                ensureBundle();
200
201                myBase = theBundleLinks.serverBase;
202
203                if (myBundle.getIdElement().isEmpty()) {
204                        myBundle.setId(theId);
205                }
206
207                if (myBundle.getMeta().getLastUpdated() == null && theLastUpdated != null) {
208                        myBundle.getMeta().getLastUpdatedElement().setValueAsString(theLastUpdated.getValueAsString());
209                }
210
211                if (!hasLink(Constants.LINK_SELF, myBundle) && isNotBlank(theBundleLinks.getSelf())) {
212                        myBundle.addLink().setRelation(Constants.LINK_SELF).setUrl(theBundleLinks.getSelf());
213                }
214                if (!hasLink(Constants.LINK_NEXT, myBundle) && isNotBlank(theBundleLinks.getNext())) {
215                        myBundle.addLink().setRelation(Constants.LINK_NEXT).setUrl(theBundleLinks.getNext());
216                }
217                if (!hasLink(Constants.LINK_PREVIOUS, myBundle) && isNotBlank(theBundleLinks.getPrev())) {
218                        myBundle.addLink().setRelation(Constants.LINK_PREVIOUS).setUrl(theBundleLinks.getPrev());
219                }
220
221                addTotalResultsToBundle(theTotalResults, theBundleLinks.bundleType);
222        }
223
224        @Override
225        public void addTotalResultsToBundle(Integer theTotalResults, BundleTypeEnum theBundleType) {
226                ensureBundle();
227
228                if (myBundle.getIdElement().isEmpty()) {
229                        myBundle.setId(UUID.randomUUID().toString());
230                }
231
232                if (myBundle.getTypeElement().isEmpty() && theBundleType != null) {
233                        myBundle.getTypeElement().setValueAsString(theBundleType.getCode());
234                }
235
236                if (myBundle.getTotalElement().isEmpty() && theTotalResults != null) {
237                        myBundle.getTotalElement().setValue(theTotalResults);
238                }
239        }
240
241        private void ensureBundle() {
242                if (myBundle == null) {
243                        myBundle = new Bundle();
244                }
245        }
246
247        @Override
248        public IBaseResource getResourceBundle() {
249                return myBundle;
250        }
251
252        private boolean hasLink(String theLinkType, Bundle theBundle) {
253                for (BundleLinkComponent next : theBundle.getLink()) {
254                        if (theLinkType.equals(next.getRelation())) {
255                                return true;
256                        }
257                }
258                return false;
259        }
260
261        @Override
262        public void initializeWithBundleResource(IBaseResource theBundle) {
263                myBundle = (Bundle) theBundle;
264        }
265
266        private IIdType populateBundleEntryFullUrl(IBaseResource next, BundleEntryComponent entry) {
267                IIdType idElement = null;
268                if (next.getIdElement().hasBaseUrl()) {
269                        idElement = next.getIdElement();
270                        entry.setFullUrl(idElement.toVersionless().getValue());
271                } else {
272                        if (isNotBlank(myBase) && next.getIdElement().hasIdPart()) {
273                                idElement = next.getIdElement();
274                                idElement = idElement.withServerBase(myBase, myContext.getResourceType(next));
275                                entry.setFullUrl(idElement.toVersionless().getValue());
276                        }
277                }
278                return idElement;
279        }
280
281        @Override
282        public List<IBaseResource> toListOfResources() {
283                ArrayList<IBaseResource> retVal = new ArrayList<IBaseResource>();
284                for (BundleEntryComponent next : myBundle.getEntry()) {
285                        if (next.getResource() != null) {
286                                retVal.add(next.getResource());
287                        } else if (next.getResponse().getLocationElement().isEmpty() == false) {
288                                IdType id = new IdType(next.getResponse().getLocation());
289                                String resourceType = id.getResourceType();
290                                if (isNotBlank(resourceType)) {
291                                        IAnyResource res = (IAnyResource)
292                                                        myContext.getResourceDefinition(resourceType).newInstance();
293                                        res.setId(id);
294                                        retVal.add(res);
295                                }
296                        }
297                }
298                return retVal;
299        }
300}