001package ca.uhn.fhir.rest.server.provider.dstu2; 002 003/* 004 * #%L 005 * HAPI FHIR Structures - DSTU2 (FHIR v1.0.0) 006 * %% 007 * Copyright (C) 2014 - 2016 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 */ 022import static org.apache.commons.lang3.StringUtils.isNotBlank; 023 024import java.util.ArrayList; 025import java.util.Collections; 026import java.util.Date; 027import java.util.HashSet; 028import java.util.List; 029import java.util.Set; 030import java.util.UUID; 031 032import org.apache.commons.lang3.Validate; 033import org.hl7.fhir.instance.model.api.IBaseResource; 034import org.hl7.fhir.instance.model.api.IIdType; 035import org.hl7.fhir.instance.model.api.IPrimitiveType; 036 037import ca.uhn.fhir.context.FhirContext; 038import ca.uhn.fhir.model.api.IResource; 039import ca.uhn.fhir.model.api.Include; 040import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum; 041import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt; 042import ca.uhn.fhir.model.base.resource.BaseOperationOutcome; 043import ca.uhn.fhir.model.dstu2.resource.Bundle; 044import ca.uhn.fhir.model.dstu2.resource.Bundle.Entry; 045import ca.uhn.fhir.model.dstu2.resource.Bundle.Link; 046import ca.uhn.fhir.model.dstu2.valueset.HTTPVerbEnum; 047import ca.uhn.fhir.model.dstu2.valueset.SearchEntryModeEnum; 048import ca.uhn.fhir.model.primitive.IdDt; 049import ca.uhn.fhir.model.primitive.InstantDt; 050import ca.uhn.fhir.model.valueset.BundleEntrySearchModeEnum; 051import ca.uhn.fhir.model.valueset.BundleEntryTransactionMethodEnum; 052import ca.uhn.fhir.model.valueset.BundleTypeEnum; 053import ca.uhn.fhir.rest.server.BundleInclusionRule; 054import ca.uhn.fhir.rest.server.Constants; 055import ca.uhn.fhir.rest.server.EncodingEnum; 056import ca.uhn.fhir.rest.server.IBundleProvider; 057import ca.uhn.fhir.rest.server.IPagingProvider; 058import ca.uhn.fhir.rest.server.IRestfulServer; 059import ca.uhn.fhir.rest.server.IVersionSpecificBundleFactory; 060import ca.uhn.fhir.rest.server.RestfulServerUtils; 061import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; 062import ca.uhn.fhir.util.ResourceReferenceInfo; 063 064public class Dstu2BundleFactory implements IVersionSpecificBundleFactory { 065 066 private Bundle myBundle; 067 private FhirContext myContext; 068 private String myBase; 069 070 public Dstu2BundleFactory(FhirContext theContext) { 071 myContext = theContext; 072 } 073 074 private void addResourcesForSearch(List<? extends IBaseResource> theResult) { 075 List<IBaseResource> includedResources = new ArrayList<IBaseResource>(); 076 Set<IIdType> addedResourceIds = new HashSet<IIdType>(); 077 078 for (IBaseResource next : theResult) { 079 if (next.getIdElement().isEmpty() == false) { 080 addedResourceIds.add(next.getIdElement()); 081 } 082 } 083 084 for (IBaseResource nextBaseRes : theResult) { 085 IResource next = (IResource) nextBaseRes; 086 Set<String> containedIds = new HashSet<String>(); 087 for (IResource nextContained : next.getContained().getContainedResources()) { 088 if (nextContained.getId().isEmpty() == false) { 089 containedIds.add(nextContained.getId().getValue()); 090 } 091 } 092 093 List<BaseResourceReferenceDt> references = myContext.newTerser().getAllPopulatedChildElementsOfType(next, BaseResourceReferenceDt.class); 094 do { 095 List<IResource> addedResourcesThisPass = new ArrayList<IResource>(); 096 097 for (BaseResourceReferenceDt nextRef : references) { 098 IResource nextRes = (IResource) nextRef.getResource(); 099 if (nextRes != null) { 100 if (nextRes.getId().hasIdPart()) { 101 if (containedIds.contains(nextRes.getId().getValue())) { 102 // Don't add contained IDs as top level resources 103 continue; 104 } 105 106 IdDt id = nextRes.getId(); 107 if (id.hasResourceType() == false) { 108 String resName = myContext.getResourceDefinition(nextRes).getName(); 109 id = id.withResourceType(resName); 110 } 111 112 if (!addedResourceIds.contains(id)) { 113 addedResourceIds.add(id); 114 addedResourcesThisPass.add(nextRes); 115 } 116 117 } 118 } 119 } 120 121 // Linked resources may themselves have linked resources 122 references = new ArrayList<BaseResourceReferenceDt>(); 123 for (IResource iResource : addedResourcesThisPass) { 124 List<BaseResourceReferenceDt> newReferences = myContext.newTerser().getAllPopulatedChildElementsOfType(iResource, BaseResourceReferenceDt.class); 125 references.addAll(newReferences); 126 } 127 128 includedResources.addAll(addedResourcesThisPass); 129 130 } while (references.isEmpty() == false); 131 132 Entry entry = myBundle.addEntry().setResource(next); 133 if (next.getId().hasBaseUrl()) { 134 entry.setFullUrl(next.getId().getValue()); 135 } 136 BundleEntryTransactionMethodEnum httpVerb = ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(next); 137 if (httpVerb != null) { 138 entry.getRequest().getMethodElement().setValueAsString(httpVerb.getCode()); 139 } 140 } 141 142 /* 143 * Actually add the resources to the bundle 144 */ 145 for (IBaseResource next : includedResources) { 146 Entry entry = myBundle.addEntry(); 147 entry.setResource((IResource) next).getSearch().setMode(SearchEntryModeEnum.INCLUDE); 148 if (next.getIdElement().hasBaseUrl()) { 149 entry.setFullUrl(next.getIdElement().getValue()); 150 } 151 } 152 } 153 154 @Override 155 public void addResourcesToBundle(List<IBaseResource> theResult, BundleTypeEnum theBundleType, String theServerBase, BundleInclusionRule theBundleInclusionRule, Set<Include> theIncludes) { 156 if (myBundle == null) { 157 myBundle = new Bundle(); 158 } 159 160 List<IResource> includedResources = new ArrayList<IResource>(); 161 Set<IdDt> addedResourceIds = new HashSet<IdDt>(); 162 163 for (IBaseResource next : theResult) { 164 if (next.getIdElement().isEmpty() == false) { 165 addedResourceIds.add((IdDt) next.getIdElement()); 166 } 167 } 168 169 for (IBaseResource nextBaseRes : theResult) { 170 IResource next = (IResource) nextBaseRes; 171 172 Set<String> containedIds = new HashSet<String>(); 173 for (IResource nextContained : next.getContained().getContainedResources()) { 174 if (nextContained.getId().isEmpty() == false) { 175 containedIds.add(nextContained.getId().getValue()); 176 } 177 } 178 179 List<ResourceReferenceInfo> references = myContext.newTerser().getAllResourceReferences(next); 180 do { 181 List<IResource> addedResourcesThisPass = new ArrayList<IResource>(); 182 183 for (ResourceReferenceInfo nextRefInfo : references) { 184 if (!theBundleInclusionRule.shouldIncludeReferencedResource(nextRefInfo, theIncludes)) 185 continue; 186 187 IResource nextRes = (IResource) nextRefInfo.getResourceReference().getResource(); 188 if (nextRes != null) { 189 if (nextRes.getId().hasIdPart()) { 190 if (containedIds.contains(nextRes.getId().getValue())) { 191 // Don't add contained IDs as top level resources 192 continue; 193 } 194 195 IdDt id = nextRes.getId(); 196 if (id.hasResourceType() == false) { 197 String resName = myContext.getResourceDefinition(nextRes).getName(); 198 id = id.withResourceType(resName); 199 } 200 201 if (!addedResourceIds.contains(id)) { 202 addedResourceIds.add(id); 203 addedResourcesThisPass.add(nextRes); 204 } 205 206 } 207 } 208 } 209 210 includedResources.addAll(addedResourcesThisPass); 211 212 // Linked resources may themselves have linked resources 213 references = new ArrayList<ResourceReferenceInfo>(); 214 for (IResource iResource : addedResourcesThisPass) { 215 List<ResourceReferenceInfo> newReferences = myContext.newTerser().getAllResourceReferences(iResource); 216 references.addAll(newReferences); 217 } 218 } while (references.isEmpty() == false); 219 220 Entry entry = myBundle.addEntry().setResource(next); 221 BundleEntryTransactionMethodEnum httpVerb = ResourceMetadataKeyEnum.ENTRY_TRANSACTION_METHOD.get(next); 222 if (httpVerb != null) { 223 entry.getRequest().getMethodElement().setValueAsString(httpVerb.getCode()); 224 } 225 populateBundleEntryFullUrl(next, entry); 226 227 BundleEntrySearchModeEnum searchMode = ResourceMetadataKeyEnum.ENTRY_SEARCH_MODE.get(next); 228 if (searchMode != null) { 229 entry.getSearch().getModeElement().setValue(searchMode.getCode()); 230 } 231 } 232 233 /* 234 * Actually add the resources to the bundle 235 */ 236 for (IResource next : includedResources) { 237 Entry entry = myBundle.addEntry(); 238 entry.setResource(next).getSearch().setMode(SearchEntryModeEnum.INCLUDE); 239 populateBundleEntryFullUrl(next, entry); 240 } 241 242 } 243 244 private void populateBundleEntryFullUrl(IResource next, Entry entry) { 245 if (next.getId().hasBaseUrl()) { 246 entry.setFullUrl(next.getId().toVersionless().getValue()); 247 } else { 248 if (isNotBlank(myBase) && next.getId().hasIdPart()) { 249 IdDt id = next.getId().toVersionless(); 250 id = id.withServerBase(myBase, myContext.getResourceDefinition(next).getName()); 251 entry.setFullUrl(id.getValue()); 252 } 253 } 254 } 255 256 @Override 257 public void addRootPropertiesToBundle(String theAuthor, String theServerBase, String theCompleteUrl, Integer theTotalResults, BundleTypeEnum theBundleType, IPrimitiveType<Date> theLastUpdated) { 258 259 myBase = theServerBase; 260 261 if (myBundle.getId().isEmpty()) { 262 myBundle.setId(UUID.randomUUID().toString()); 263 } 264 265 if (ResourceMetadataKeyEnum.UPDATED.get(myBundle) == null) { 266 ResourceMetadataKeyEnum.UPDATED.put(myBundle, (InstantDt) theLastUpdated); 267 } 268 269 if (!hasLink(Constants.LINK_SELF, myBundle) && isNotBlank(theCompleteUrl)) { 270 myBundle.addLink().setRelation("self").setUrl(theCompleteUrl); 271 } 272 273 if (myBundle.getTypeElement().isEmpty() && theBundleType != null) { 274 myBundle.getTypeElement().setValueAsString(theBundleType.getCode()); 275 } 276 277 if (myBundle.getTotalElement().isEmpty() && theTotalResults != null) { 278 myBundle.getTotalElement().setValue(theTotalResults); 279 } 280 } 281 282 @Override 283 public ca.uhn.fhir.model.api.Bundle getDstu1Bundle() { 284 return null; 285 } 286 287 @Override 288 public IResource getResourceBundle() { 289 return myBundle; 290 } 291 292 private boolean hasLink(String theLinkType, Bundle theBundle) { 293 for (Link next : theBundle.getLink()) { 294 if (theLinkType.equals(next.getRelation())) { 295 return true; 296 } 297 } 298 return false; 299 } 300 301 @Override 302 public void initializeBundleFromBundleProvider(IRestfulServer<?> theServer, IBundleProvider theResult, EncodingEnum theResponseEncoding, String theServerBase, String theCompleteUrl, 303 boolean thePrettyPrint, int theOffset, Integer theLimit, String theSearchId, BundleTypeEnum theBundleType, Set<Include> theIncludes) { 304 myBase = theServerBase; 305 306 int numToReturn; 307 String searchId = null; 308 List<IBaseResource> resourceList; 309 if (theServer.getPagingProvider() == null) { 310 numToReturn = theResult.size(); 311 if (numToReturn > 0) { 312 resourceList = theResult.getResources(0, numToReturn); 313 } else { 314 resourceList = Collections.emptyList(); 315 } 316 RestfulServerUtils.validateResourceListNotNull(resourceList); 317 318 } else { 319 IPagingProvider pagingProvider = theServer.getPagingProvider(); 320 if (theLimit == null) { 321 numToReturn = pagingProvider.getDefaultPageSize(); 322 } else { 323 numToReturn = Math.min(pagingProvider.getMaximumPageSize(), theLimit); 324 } 325 326 numToReturn = Math.min(numToReturn, theResult.size() - theOffset); 327 if (numToReturn > 0) { 328 resourceList = theResult.getResources(theOffset, numToReturn + theOffset); 329 } else { 330 resourceList = Collections.emptyList(); 331 } 332 RestfulServerUtils.validateResourceListNotNull(resourceList); 333 334 if (theSearchId != null) { 335 searchId = theSearchId; 336 } else { 337 if (theResult.size() > numToReturn) { 338 searchId = pagingProvider.storeResultList(theResult); 339 Validate.notNull(searchId, "Paging provider returned null searchId"); 340 } 341 } 342 } 343 344 for (IBaseResource next : resourceList) { 345 if (next.getIdElement() == null || next.getIdElement().isEmpty()) { 346 if (!(next instanceof BaseOperationOutcome)) { 347 throw new InternalErrorException("Server method returned resource of type[" + next.getClass().getSimpleName() + "] with no ID specified (IResource#setId(IdDt) must be called)"); 348 } 349 } 350 } 351 352 addResourcesToBundle(new ArrayList<IBaseResource>(resourceList), theBundleType, theServerBase, theServer.getBundleInclusionRule(), theIncludes); 353 addRootPropertiesToBundle(null, theServerBase, theCompleteUrl, theResult.size(), theBundleType, theResult.getPublished()); 354 355 if (theServer.getPagingProvider() != null) { 356 int limit; 357 limit = theLimit != null ? theLimit : theServer.getPagingProvider().getDefaultPageSize(); 358 limit = Math.min(limit, theServer.getPagingProvider().getMaximumPageSize()); 359 360 if (searchId != null) { 361 if (theOffset + numToReturn < theResult.size()) { 362 myBundle.addLink().setRelation(Constants.LINK_NEXT) 363 .setUrl(RestfulServerUtils.createPagingLink(theIncludes, theServerBase, searchId, theOffset + numToReturn, numToReturn, theResponseEncoding, thePrettyPrint, theBundleType)); 364 } 365 if (theOffset > 0) { 366 int start = Math.max(0, theOffset - limit); 367 myBundle.addLink().setRelation(Constants.LINK_PREVIOUS) 368 .setUrl(RestfulServerUtils.createPagingLink(theIncludes, theServerBase, searchId, start, limit, theResponseEncoding, thePrettyPrint, theBundleType)); 369 } 370 } 371 } 372 } 373 374 @Override 375 public void initializeBundleFromResourceList(String theAuthor, List<? extends IBaseResource> theResources, String theServerBase, String theCompleteUrl, int theTotalResults, 376 BundleTypeEnum theBundleType) { 377 myBundle = new Bundle(); 378 379 myBundle.setId(UUID.randomUUID().toString()); 380 381 ResourceMetadataKeyEnum.PUBLISHED.put(myBundle, InstantDt.withCurrentTime()); 382 383 myBundle.addLink().setRelation(Constants.LINK_FHIR_BASE).setUrl(theServerBase); 384 myBundle.addLink().setRelation(Constants.LINK_SELF).setUrl(theCompleteUrl); 385 myBundle.getTypeElement().setValueAsString(theBundleType.getCode()); 386 387 if (theBundleType.equals(BundleTypeEnum.TRANSACTION)) { 388 for (IBaseResource nextBaseRes : theResources) { 389 IResource next = (IResource) nextBaseRes; 390 Entry nextEntry = myBundle.addEntry(); 391 392 nextEntry.setResource(next); 393 if (next.getId().isEmpty()) { 394 nextEntry.getRequest().setMethod(HTTPVerbEnum.POST); 395 } else { 396 nextEntry.getRequest().setMethod(HTTPVerbEnum.PUT); 397 if (next.getId().isAbsolute()) { 398 nextEntry.getRequest().setUrl(next.getId()); 399 } else { 400 String resourceType = myContext.getResourceDefinition(next).getName(); 401 nextEntry.getRequest().setUrl(new IdDt(theServerBase, resourceType, next.getId().getIdPart(), next.getId().getVersionIdPart()).getValue()); 402 } 403 } 404 } 405 } else { 406 addResourcesForSearch(theResources); 407 } 408 409 myBundle.getTotalElement().setValue(theTotalResults); 410 } 411 412 @Override 413 public void initializeWithBundleResource(IBaseResource theBundle) { 414 myBundle = (Bundle) theBundle; 415 } 416 417 @Override 418 public List<IBaseResource> toListOfResources() { 419 ArrayList<IBaseResource> retVal = new ArrayList<IBaseResource>(); 420 for (Entry next : myBundle.getEntry()) { 421 if (next.getResource() != null) { 422 retVal.add(next.getResource()); 423 } else if (next.getResponse().getLocationElement().isEmpty() == false) { 424 IdDt id = new IdDt(next.getResponse().getLocation()); 425 String resourceType = id.getResourceType(); 426 if (isNotBlank(resourceType)) { 427 IResource res = (IResource) myContext.getResourceDefinition(resourceType).newInstance(); 428 res.setId(id); 429 retVal.add(res); 430 } 431 } 432 } 433 return retVal; 434 } 435 436}