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