001/*
002 * #%L
003 * HAPI FHIR Structures - HL7.org DSTU2
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 ca.uhn.fhir.rest.server.provider.dstu2hl7org;
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.dstu2.model.Bundle;
036import org.hl7.fhir.dstu2.model.Bundle.BundleEntryComponent;
037import org.hl7.fhir.dstu2.model.Bundle.BundleLinkComponent;
038import org.hl7.fhir.dstu2.model.Bundle.SearchEntryMode;
039import org.hl7.fhir.dstu2.model.DomainResource;
040import org.hl7.fhir.dstu2.model.IdType;
041import org.hl7.fhir.dstu2.model.InstantType;
042import org.hl7.fhir.dstu2.model.Resource;
043import org.hl7.fhir.instance.model.api.IAnyResource;
044import org.hl7.fhir.instance.model.api.IBaseResource;
045import org.hl7.fhir.instance.model.api.IIdType;
046import org.hl7.fhir.instance.model.api.IPrimitiveType;
047
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.isBlank;
056import static org.apache.commons.lang3.StringUtils.isNotBlank;
057
058public class Dstu2Hl7OrgBundleFactory implements IVersionSpecificBundleFactory {
059
060        private String myBase;
061        private Bundle myBundle;
062        private FhirContext myContext;
063
064        public Dstu2Hl7OrgBundleFactory(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<IAnyResource>();
078                Set<IIdType> addedResourceIds = new HashSet<IIdType>();
079
080                for (IBaseResource next : theResult) {
081                        if (next.getIdElement().isEmpty() == false) {
082                                addedResourceIds.add(next.getIdElement());
083                        }
084                }
085
086                for (IBaseResource next : theResult) {
087
088                        Set<String> containedIds = new HashSet<String>();
089
090                        if (next instanceof DomainResource) {
091                                for (Resource nextContained : ((DomainResource) next).getContained()) {
092                                        if (isNotBlank(nextContained.getId())) {
093                                                containedIds.add(nextContained.getId());
094                                        }
095                                }
096                        }
097
098                        List<ResourceReferenceInfo> references = myContext.newTerser().getAllResourceReferences(next);
099                        do {
100                                List<IAnyResource> addedResourcesThisPass = new ArrayList<IAnyResource>();
101
102                                for (ResourceReferenceInfo nextRefInfo : references) {
103                                        if (theBundleInclusionRule != null
104                                                        && !theBundleInclusionRule.shouldIncludeReferencedResource(nextRefInfo, theIncludes)) {
105                                                continue;
106                                        }
107
108                                        IAnyResource nextRes =
109                                                        (IAnyResource) nextRefInfo.getResourceReference().getResource();
110                                        if (nextRes != null) {
111                                                if (nextRes.getIdElement().hasIdPart()) {
112                                                        if (containedIds.contains(nextRes.getIdElement().getValue())) {
113                                                                // Don't add contained IDs as top level resources
114                                                                continue;
115                                                        }
116
117                                                        IIdType id = nextRes.getIdElement();
118                                                        if (id.hasResourceType() == false) {
119                                                                String resName = myContext.getResourceType(nextRes);
120                                                                id = id.withResourceType(resName);
121                                                        }
122
123                                                        if (!addedResourceIds.contains(id)) {
124                                                                addedResourceIds.add(id);
125                                                                addedResourcesThisPass.add(nextRes);
126                                                        }
127                                                }
128                                        }
129                                }
130
131                                includedResources.addAll(addedResourcesThisPass);
132
133                                // Linked resources may themselves have linked resources
134                                references = new ArrayList<>();
135                                for (IAnyResource iResource : addedResourcesThisPass) {
136                                        List<ResourceReferenceInfo> newReferences =
137                                                        myContext.newTerser().getAllResourceReferences(iResource);
138                                        references.addAll(newReferences);
139                                }
140                        } while (references.isEmpty() == false);
141
142                        BundleEntryComponent entry = myBundle.addEntry().setResource((Resource) next);
143                        Resource nextAsResource = (Resource) next;
144                        IIdType id = populateBundleEntryFullUrl(next, entry);
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.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                                                if (id != null) {
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                                                }
172                                                break;
173                                }
174                        }
175
176                        // Populate Bundle.entry.search
177                        BundleEntrySearchModeEnum searchMode = ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(nextAsResource);
178                        if (searchMode != null) {
179                                entry.getSearch().getModeElement().setValueAsString(searchMode.getCode());
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                if (myBundle.getIdElement().isEmpty()) {
202                        myBundle.setId(theId);
203                }
204
205                if (myBundle.getMeta().getLastUpdated() == null && theLastUpdated != null) {
206                        InstantType instantType = new InstantType();
207                        instantType.setValueAsString(theLastUpdated.getValueAsString());
208                        myBundle.getMeta().setLastUpdatedElement(instantType);
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_SELF, myBundle) && isNotBlank(theBundleLinks.getPrev())) {
218                        myBundle.addLink().setRelation(Constants.LINK_PREVIOUS).setUrl(theBundleLinks.getPrev());
219                }
220
221                myBase = theBundleLinks.serverBase;
222
223                addTotalResultsToBundle(theTotalResults, theBundleLinks.bundleType);
224        }
225
226        @Override
227        public void addTotalResultsToBundle(Integer theTotalResults, BundleTypeEnum theBundleType) {
228                ensureBundle();
229
230                if (isBlank(myBundle.getId())) {
231                        myBundle.setId(UUID.randomUUID().toString());
232                }
233
234                if (myBundle.getTypeElement().isEmpty() && theBundleType != null) {
235                        myBundle.getTypeElement().setValueAsString(theBundleType.getCode());
236                }
237
238                if (myBundle.getTotalElement().isEmpty() && theTotalResults != null) {
239                        myBundle.getTotalElement().setValue(theTotalResults);
240                }
241        }
242
243        private void ensureBundle() {
244                if (myBundle == null) {
245                        myBundle = new Bundle();
246                }
247        }
248
249        @Override
250        public IBaseResource getResourceBundle() {
251                return myBundle;
252        }
253
254        private boolean hasLink(String theLinkType, Bundle theBundle) {
255                for (BundleLinkComponent next : theBundle.getLink()) {
256                        if (theLinkType.equals(next.getRelation())) {
257                                return true;
258                        }
259                }
260                return false;
261        }
262
263        @Override
264        public void initializeWithBundleResource(IBaseResource theBundle) {
265                myBundle = (Bundle) theBundle;
266        }
267
268        private IIdType populateBundleEntryFullUrl(IBaseResource next, BundleEntryComponent entry) {
269                IIdType idElement = null;
270                if (next.getIdElement().hasBaseUrl()) {
271                        idElement = next.getIdElement();
272                        entry.setFullUrl(idElement.toVersionless().getValue());
273                } else {
274                        if (isNotBlank(myBase) && next.getIdElement().hasIdPart()) {
275                                idElement = next.getIdElement();
276                                idElement = idElement.withServerBase(myBase, myContext.getResourceType(next));
277                                entry.setFullUrl(idElement.toVersionless().getValue());
278                        }
279                }
280                return idElement;
281        }
282
283        @Override
284        public List<IBaseResource> toListOfResources() {
285                ArrayList<IBaseResource> retVal = new ArrayList<IBaseResource>();
286                for (BundleEntryComponent next : myBundle.getEntry()) {
287                        if (next.getResource() != null) {
288                                retVal.add(next.getResource());
289                        } else if (next.getResponse().getLocationElement().isEmpty() == false) {
290                                IdType id = new IdType(next.getResponse().getLocation());
291                                String resourceType = id.getResourceType();
292                                if (isNotBlank(resourceType)) {
293                                        IBaseResource res = (IBaseResource)
294                                                        myContext.getResourceDefinition(resourceType).newInstance();
295                                        res.setId(id);
296                                        retVal.add(res);
297                                }
298                        }
299                }
300                return retVal;
301        }
302}