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