001package ca.uhn.fhir.rest.server.provider.dstu2;
002
003/*
004 * #%L
005 * HAPI FHIR Structures - DSTU2 (FHIR v1.0.0)
006 * %%
007 * Copyright (C) 2014 - 2020 University Health Network
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 * http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022import static org.apache.commons.lang3.StringUtils.isNotBlank;
023
024import java.util.*;
025
026import org.hl7.fhir.instance.model.api.*;
027
028import ca.uhn.fhir.context.FhirContext;
029import ca.uhn.fhir.context.api.BundleInclusionRule;
030import ca.uhn.fhir.model.api.*;
031import ca.uhn.fhir.model.dstu2.resource.Bundle;
032import ca.uhn.fhir.model.dstu2.resource.Bundle.Entry;
033import ca.uhn.fhir.model.dstu2.resource.Bundle.Link;
034import ca.uhn.fhir.model.dstu2.valueset.SearchEntryModeEnum;
035import ca.uhn.fhir.model.primitive.IdDt;
036import ca.uhn.fhir.model.primitive.InstantDt;
037import ca.uhn.fhir.model.valueset.*;
038import ca.uhn.fhir.rest.api.Constants;
039import ca.uhn.fhir.rest.api.IVersionSpecificBundleFactory;
040import ca.uhn.fhir.util.ResourceReferenceInfo;
041
042public class Dstu2BundleFactory implements IVersionSpecificBundleFactory {
043        private String myBase;
044        private Bundle myBundle;
045        private FhirContext myContext;
046
047        public Dstu2BundleFactory(FhirContext theContext) {
048                myContext = theContext;
049        }
050
051        @Override
052        public void addResourcesToBundle(List<IBaseResource> theResult, BundleTypeEnum theBundleType, String theServerBase, BundleInclusionRule theBundleInclusionRule, Set<Include> theIncludes) {
053                ensureBundle();
054
055                List<IResource> includedResources = new ArrayList<IResource>();
056                Set<IdDt> addedResourceIds = new HashSet<IdDt>();
057
058                for (IBaseResource next : theResult) {
059                        if (next.getIdElement().isEmpty() == false) {
060                                addedResourceIds.add((IdDt) next.getIdElement());
061                        }
062                }
063
064                for (IBaseResource nextBaseRes : theResult) {
065                        IResource next = (IResource) nextBaseRes;
066
067                        Set<String> containedIds = new HashSet<String>();
068                        for (IResource nextContained : next.getContained().getContainedResources()) {
069                                if (nextContained.getId().isEmpty() == false) {
070                                        containedIds.add(nextContained.getId().getValue());
071                                }
072                        }
073
074                        List<ResourceReferenceInfo> references = myContext.newTerser().getAllResourceReferences(next);
075                        do {
076                                List<IResource> addedResourcesThisPass = new ArrayList<IResource>();
077
078                                for (ResourceReferenceInfo nextRefInfo : references) {
079                                        if (theBundleInclusionRule != null && !theBundleInclusionRule.shouldIncludeReferencedResource(nextRefInfo, theIncludes)) {
080                                                continue;
081                                        }
082
083                                        IResource nextRes = (IResource) nextRefInfo.getResourceReference().getResource();
084                                        if (nextRes != null) {
085                                                if (nextRes.getId().hasIdPart()) {
086                                                        if (containedIds.contains(nextRes.getId().getValue())) {
087                                                                // Don't add contained IDs as top level resources
088                                                                continue;
089                                                        }
090
091                                                        IdDt id = nextRes.getId();
092                                                        if (id.hasResourceType() == false) {
093                                                                String resName = myContext.getResourceType(nextRes);
094                                                                id = id.withResourceType(resName);
095                                                        }
096
097                                                        if (!addedResourceIds.contains(id)) {
098                                                                addedResourceIds.add(id);
099                                                                addedResourcesThisPass.add(nextRes);
100                                                        }
101
102                                                }
103                                        }
104                                }
105
106                                includedResources.addAll(addedResourcesThisPass);
107
108                                // Linked resources may themselves have linked resources
109                                references = new ArrayList<ResourceReferenceInfo>();
110                                for (IResource iResource : addedResourcesThisPass) {
111                                        List<ResourceReferenceInfo> newReferences = myContext.newTerser().getAllResourceReferences(iResource);
112                                        references.addAll(newReferences);
113                                }
114                        } while (references.isEmpty() == false);
115
116                        Entry entry = myBundle.addEntry().setResource(next);
117                        BundleEntryTransactionMethodEnum httpVerb = ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(next);
118                        if (httpVerb != null) {
119                                entry.getRequest().getMethodElement().setValueAsString(httpVerb.getCode());
120                        }
121                        populateBundleEntryFullUrl(next, entry);
122
123                        BundleEntrySearchModeEnum searchMode = ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(next);
124                        if (searchMode != null) {
125                                entry.getSearch().getModeElement().setValue(searchMode.getCode());
126                        }
127                }
128
129                /*
130                 * Actually add the resources to the bundle
131                 */
132                for (IResource next : includedResources) {
133                        Entry entry = myBundle.addEntry();
134                        entry.setResource(next).getSearch().setMode(SearchEntryModeEnum.INCLUDE);
135                        populateBundleEntryFullUrl(next, entry);
136                }
137
138        }
139
140        @Override
141        public void addRootPropertiesToBundle(String theId, String theServerBase, String theLinkSelf, String theLinkPrev, String theLinkNext, Integer theTotalResults, BundleTypeEnum theBundleType,
142                                                                                                          IPrimitiveType<Date> theLastUpdated) {
143                ensureBundle();
144
145                myBase = theServerBase;
146
147                if (myBundle.getIdElement().isEmpty()) {
148                        myBundle.setId(theId);
149                }
150                if (myBundle.getId().isEmpty()) {
151                        myBundle.setId(UUID.randomUUID().toString());
152                }
153
154                if (ResourceMetadataKeyEnum.UPDATED.get(myBundle) == null) {
155                        ResourceMetadataKeyEnum.UPDATED.put(myBundle, (InstantDt) theLastUpdated);
156                }
157
158                if (!hasLink(Constants.LINK_SELF, myBundle) && isNotBlank(theLinkSelf)) {
159                        myBundle.addLink().setRelation(Constants.LINK_SELF).setUrl(theLinkSelf);
160                }
161                if (!hasLink(Constants.LINK_NEXT, myBundle) && isNotBlank(theLinkNext)) {
162                        myBundle.addLink().setRelation(Constants.LINK_NEXT).setUrl(theLinkNext);
163                }
164                if (!hasLink(Constants.LINK_PREVIOUS, myBundle) && isNotBlank(theLinkPrev)) {
165                        myBundle.addLink().setRelation(Constants.LINK_PREVIOUS).setUrl(theLinkPrev);
166                }
167
168                if (myBundle.getTypeElement().isEmpty() && theBundleType != null) {
169                        myBundle.getTypeElement().setValueAsString(theBundleType.getCode());
170                }
171
172                if (myBundle.getTotalElement().isEmpty() && theTotalResults != null) {
173                        myBundle.getTotalElement().setValue(theTotalResults);
174                }
175        }
176
177        private void ensureBundle() {
178                if (myBundle == null) {
179                        myBundle = new Bundle();
180                }
181        }
182
183        @Override
184        public IResource getResourceBundle() {
185                return myBundle;
186        }
187
188        private boolean hasLink(String theLinkType, Bundle theBundle) {
189                for (Link next : theBundle.getLink()) {
190                        if (theLinkType.equals(next.getRelation())) {
191                                return true;
192                        }
193                }
194                return false;
195        }
196
197        @Override
198        public void initializeWithBundleResource(IBaseResource theBundle) {
199                myBundle = (Bundle) theBundle;
200        }
201
202        private void populateBundleEntryFullUrl(IResource next, Entry entry) {
203                if (next.getId().hasBaseUrl()) {
204                        entry.setFullUrl(next.getId().toVersionless().getValue());
205                } else {
206                        if (isNotBlank(myBase) && next.getId().hasIdPart()) {
207                                IdDt id = next.getId().toVersionless();
208                                id = id.withServerBase(myBase, myContext.getResourceType(next));
209                                entry.setFullUrl(id.getValue());
210                        }
211                }
212        }
213
214        @Override
215        public List<IBaseResource> toListOfResources() {
216                ArrayList<IBaseResource> retVal = new ArrayList<IBaseResource>();
217                for (Entry next : myBundle.getEntry()) {
218                        if (next.getResource() != null) {
219                                retVal.add(next.getResource());
220                        } else if (next.getResponse().getLocationElement().isEmpty() == false) {
221                                IdDt id = new IdDt(next.getResponse().getLocation());
222                                String resourceType = id.getResourceType();
223                                if (isNotBlank(resourceType)) {
224                                        IResource res = (IResource) myContext.getResourceDefinition(resourceType).newInstance();
225                                        res.setId(id);
226                                        retVal.add(res);
227                                }
228                        }
229                }
230                return retVal;
231        }
232
233}