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