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