001package org.hl7.fhir.dstu3.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.Constants;
029import ca.uhn.fhir.rest.api.IVersionSpecificBundleFactory;
030import ca.uhn.fhir.util.ResourceReferenceInfo;
031import org.hl7.fhir.dstu3.model.Bundle;
032import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent;
033import org.hl7.fhir.dstu3.model.Bundle.BundleLinkComponent;
034import org.hl7.fhir.dstu3.model.Bundle.HTTPVerb;
035import org.hl7.fhir.dstu3.model.Bundle.SearchEntryMode;
036import org.hl7.fhir.dstu3.model.DomainResource;
037import org.hl7.fhir.dstu3.model.IdType;
038import org.hl7.fhir.dstu3.model.Resource;
039import org.hl7.fhir.instance.model.api.*;
040
041import java.util.*;
042
043import static org.apache.commons.lang3.StringUtils.isNotBlank;
044
045public class Dstu3BundleFactory implements IVersionSpecificBundleFactory {
046  private String myBase;
047  private Bundle myBundle;
048  private FhirContext myContext;
049
050  public Dstu3BundleFactory(FhirContext theContext) {
051    myContext = theContext;
052  }
053
054  private void addResourcesForSearch(List<? extends IBaseResource> theResult) {
055    List<IBaseResource> includedResources = new ArrayList<IBaseResource>();
056    Set<IIdType> addedResourceIds = new HashSet<IIdType>();
057
058    for (IBaseResource next : theResult) {
059      if (next.getIdElement().isEmpty() == false) {
060        addedResourceIds.add(next.getIdElement());
061      }
062    }
063
064    for (IBaseResource nextBaseRes : theResult) {
065      Resource next = (Resource) nextBaseRes;
066      Set<String> containedIds = new HashSet<String>();
067      if (next instanceof DomainResource) {
068        for (Resource nextContained : ((DomainResource) next).getContained()) {
069          if (nextContained.getIdElement().isEmpty() == false) {
070            containedIds.add(nextContained.getIdElement().getValue());
071          }
072        }
073      }
074
075      List<IBaseReference> references = myContext.newTerser().getAllPopulatedChildElementsOfType(next, IBaseReference.class);
076      do {
077        List<IAnyResource> addedResourcesThisPass = new ArrayList<IAnyResource>();
078
079        for (IBaseReference nextRef : references) {
080          IAnyResource nextRes = (IAnyResource) nextRef.getResource();
081          if (nextRes != null) {
082            if (nextRes.getIdElement().hasIdPart()) {
083              if (containedIds.contains(nextRes.getIdElement().getValue())) {
084                // Don't add contained IDs as top level resources
085                continue;
086              }
087
088              IIdType id = nextRes.getIdElement();
089              if (id.hasResourceType() == false) {
090                String resName = myContext.getResourceDefinition(nextRes).getName();
091                id = id.withResourceType(resName);
092              }
093
094              if (!addedResourceIds.contains(id)) {
095                addedResourceIds.add(id);
096                addedResourcesThisPass.add(nextRes);
097              }
098
099            }
100          }
101        }
102
103        // Linked resources may themselves have linked resources
104        references = new ArrayList<IBaseReference>();
105        for (IAnyResource iResource : addedResourcesThisPass) {
106          List<IBaseReference> newReferences = myContext.newTerser().getAllPopulatedChildElementsOfType(iResource, IBaseReference.class);
107          references.addAll(newReferences);
108        }
109
110        includedResources.addAll(addedResourcesThisPass);
111
112      } while (references.isEmpty() == false);
113
114      BundleEntryComponent entry = myBundle.addEntry().setResource(next);
115      if (next.getIdElement().hasBaseUrl()) {
116        entry.setFullUrl(next.getId());
117      }
118
119      String httpVerb = ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(next);
120      if (httpVerb != null) {
121        entry.getRequest().getMethodElement().setValueAsString(httpVerb);
122        entry.getRequest().getUrlElement().setValue(next.getId());
123      }
124      if ("DELETE".equals(httpVerb)) {
125        entry.setResource(null);
126      }
127
128    }
129
130                /*
131       * Actually add the resources to the bundle
132                 */
133    for (IBaseResource next : includedResources) {
134      BundleEntryComponent entry = myBundle.addEntry();
135      entry.setResource((Resource) next).getSearch().setMode(SearchEntryMode.INCLUDE);
136      if (next.getIdElement().hasBaseUrl()) {
137        entry.setFullUrl(next.getIdElement().getValue());
138      }
139    }
140  }
141
142  @Override
143  public void addResourcesToBundle(List<IBaseResource> theResult, BundleTypeEnum theBundleType, String theServerBase, BundleInclusionRule theBundleInclusionRule, Set<Include> theIncludes) {
144    ensureBundle();
145
146    List<IAnyResource> includedResources = new ArrayList<IAnyResource>();
147    Set<IIdType> addedResourceIds = new HashSet<IIdType>();
148
149    for (IBaseResource next : theResult) {
150      if (next.getIdElement().isEmpty() == false) {
151        addedResourceIds.add(next.getIdElement());
152      }
153    }
154
155    for (IBaseResource next : theResult) {
156
157      Set<String> containedIds = new HashSet<String>();
158
159      if (next instanceof DomainResource) {
160        for (Resource nextContained : ((DomainResource) next).getContained()) {
161          if (isNotBlank(nextContained.getId())) {
162            containedIds.add(nextContained.getId());
163          }
164        }
165      }
166
167      List<ResourceReferenceInfo> references = myContext.newTerser().getAllResourceReferences(next);
168      do {
169        List<IAnyResource> addedResourcesThisPass = new ArrayList<IAnyResource>();
170
171        for (ResourceReferenceInfo nextRefInfo : references) {
172          if (!theBundleInclusionRule.shouldIncludeReferencedResource(nextRefInfo, theIncludes)) {
173            continue;
174          }
175
176          IAnyResource nextRes = (IAnyResource) nextRefInfo.getResourceReference().getResource();
177          if (nextRes != null) {
178            if (nextRes.getIdElement().hasIdPart()) {
179              if (containedIds.contains(nextRes.getIdElement().getValue())) {
180                // Don't add contained IDs as top level resources
181                continue;
182              }
183
184              IIdType id = nextRes.getIdElement();
185              if (id.hasResourceType() == false) {
186                String resName = myContext.getResourceDefinition(nextRes).getName();
187                id = id.withResourceType(resName);
188              }
189
190              if (!addedResourceIds.contains(id)) {
191                addedResourceIds.add(id);
192                addedResourcesThisPass.add(nextRes);
193              }
194
195            }
196          }
197        }
198
199        includedResources.addAll(addedResourcesThisPass);
200
201        // Linked resources may themselves have linked resources
202        references = new ArrayList<ResourceReferenceInfo>();
203        for (IAnyResource iResource : addedResourcesThisPass) {
204          List<ResourceReferenceInfo> newReferences = myContext.newTerser().getAllResourceReferences(iResource);
205          references.addAll(newReferences);
206        }
207      } while (references.isEmpty() == false);
208
209      BundleEntryComponent entry = myBundle.addEntry().setResource((Resource) next);
210      Resource nextAsResource = (Resource) next;
211      IIdType id = populateBundleEntryFullUrl(next, entry);
212      String httpVerb = ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(nextAsResource);
213      if (httpVerb != null) {
214        entry.getRequest().getMethodElement().setValueAsString(httpVerb);
215        if (id != null) {
216          entry.getRequest().setUrl(id.getValue());
217        }
218      }
219      if ("DELETE".equals(httpVerb)) {
220        entry.setResource(null);
221      }
222
223      String searchMode = ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(nextAsResource);
224      if (searchMode != null) {
225        entry.getSearch().getModeElement().setValueAsString(searchMode);
226      }
227    }
228
229                /*
230                 * Actually add the resources to the bundle
231                 */
232    for (IAnyResource next : includedResources) {
233      BundleEntryComponent entry = myBundle.addEntry();
234      entry.setResource((Resource) next).getSearch().setMode(SearchEntryMode.INCLUDE);
235      populateBundleEntryFullUrl(next, entry);
236    }
237
238  }
239
240  @Override
241  public void addRootPropertiesToBundle(String theId, String theServerBase, String theLinkSelf, String theLinkPrev, String theLinkNext, Integer theTotalResults, BundleTypeEnum theBundleType,
242                                        IPrimitiveType<Date> theLastUpdated) {
243    ensureBundle();
244
245    myBase = theServerBase;
246
247    if (myBundle.getIdElement().isEmpty()) {
248      myBundle.setId(theId);
249    }
250    if (myBundle.getIdElement().isEmpty()) {
251      myBundle.setId(UUID.randomUUID().toString());
252    }
253
254    if (myBundle.getMeta().getLastUpdated() == null && theLastUpdated != null) {
255      myBundle.getMeta().getLastUpdatedElement().setValueAsString(theLastUpdated.getValueAsString());
256    }
257
258    if (!hasLink(Constants.LINK_SELF, myBundle) && isNotBlank(theLinkSelf)) {
259      myBundle.addLink().setRelation(Constants.LINK_SELF).setUrl(theLinkSelf);
260    }
261    if (!hasLink(Constants.LINK_NEXT, myBundle) && isNotBlank(theLinkNext)) {
262      myBundle.addLink().setRelation(Constants.LINK_NEXT).setUrl(theLinkNext);
263    }
264    if (!hasLink(Constants.LINK_PREVIOUS, myBundle) && isNotBlank(theLinkPrev)) {
265      myBundle.addLink().setRelation(Constants.LINK_PREVIOUS).setUrl(theLinkPrev);
266    }
267
268    if (myBundle.getTypeElement().isEmpty() && theBundleType != null) {
269      myBundle.getTypeElement().setValueAsString(theBundleType.getCode());
270    }
271
272    if (myBundle.getTotalElement().isEmpty() && theTotalResults != null) {
273      myBundle.getTotalElement().setValue(theTotalResults);
274    }
275  }
276
277  private void ensureBundle() {
278    if (myBundle == null) {
279      myBundle = new Bundle();
280    }
281  }
282
283  @Override
284  public IBaseResource getResourceBundle() {
285    return myBundle;
286  }
287
288  private boolean hasLink(String theLinkType, Bundle theBundle) {
289    for (BundleLinkComponent next : theBundle.getLink()) {
290      if (theLinkType.equals(next.getRelation())) {
291        return true;
292      }
293    }
294    return false;
295  }
296
297  @Override
298  public void initializeBundleFromResourceList(String theAuthor, List<? extends IBaseResource> theResources, String theServerBase, String theCompleteUrl, int theTotalResults,
299                                               BundleTypeEnum theBundleType) {
300    myBundle = new Bundle();
301
302    myBundle.setId(UUID.randomUUID().toString());
303
304    myBundle.getMeta().setLastUpdated(new Date());
305
306    myBundle.addLink().setRelation(Constants.LINK_FHIR_BASE).setUrl(theServerBase);
307    myBundle.addLink().setRelation(Constants.LINK_SELF).setUrl(theCompleteUrl);
308    myBundle.getTypeElement().setValueAsString(theBundleType.getCode());
309
310    if (theBundleType.equals(BundleTypeEnum.TRANSACTION)) {
311      for (IBaseResource nextBaseRes : theResources) {
312        Resource next = (Resource) nextBaseRes;
313        BundleEntryComponent nextEntry = myBundle.addEntry();
314
315        nextEntry.setResource(next);
316        if (next.getIdElement().isEmpty()) {
317          nextEntry.getRequest().setMethod(HTTPVerb.POST);
318        } else {
319          nextEntry.getRequest().setMethod(HTTPVerb.PUT);
320          if (next.getIdElement().isAbsolute()) {
321            nextEntry.getRequest().setUrl(next.getId());
322          } else {
323            String resourceType = myContext.getResourceDefinition(next).getName();
324            nextEntry.getRequest().setUrl(new IdType(theServerBase, resourceType, next.getIdElement().getIdPart(), next.getIdElement().getVersionIdPart()).getValue());
325          }
326        }
327      }
328    } else {
329      addResourcesForSearch(theResources);
330    }
331
332    myBundle.getTotalElement().setValue(theTotalResults);
333  }
334
335  @Override
336  public void initializeWithBundleResource(IBaseResource theBundle) {
337    myBundle = (Bundle) theBundle;
338  }
339
340  private IIdType populateBundleEntryFullUrl(IBaseResource next, BundleEntryComponent entry) {
341    IIdType idElement = null;
342    if (next.getIdElement().hasBaseUrl()) {
343      idElement = next.getIdElement();
344      entry.setFullUrl(idElement.toVersionless().getValue());
345    } else {
346      if (isNotBlank(myBase) && next.getIdElement().hasIdPart()) {
347        idElement = next.getIdElement();
348        idElement = idElement.withServerBase(myBase, myContext.getResourceDefinition(next).getName());
349        entry.setFullUrl(idElement.toVersionless().getValue());
350      }
351    }
352    return idElement;
353  }
354
355  @Override
356  public List<IBaseResource> toListOfResources() {
357    ArrayList<IBaseResource> retVal = new ArrayList<IBaseResource>();
358    for (BundleEntryComponent next : myBundle.getEntry()) {
359      if (next.getResource() != null) {
360        retVal.add(next.getResource());
361      } else if (next.getResponse().getLocationElement().isEmpty() == false) {
362        IdType id = new IdType(next.getResponse().getLocation());
363        String resourceType = id.getResourceType();
364        if (isNotBlank(resourceType)) {
365          IAnyResource res = (IAnyResource) myContext.getResourceDefinition(resourceType).newInstance();
366          res.setId(id);
367          retVal.add(res);
368        }
369      }
370    }
371    return retVal;
372  }
373
374}