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