hl7-fhirhapi-fhirdstu2-fhir

loadPage().next(bundle).execute() would lead to infinite loop


I am trying to get all the entries in a paginated bundle.

The working code is as follow:

Bundle bundle = fhirClient.search()
            .forResource(...)
            .where(...)
            .returnBundle(Bundle.class)
            .execute();

    if (bundle == null){
        return null;
    }

    // Keep adding entries until the last page
    Bundle tempBundle = fhirClient.loadPage().next(bundle).execute();

    // Put all the new entries into a separated list so that we do not modify the iterator
    List<Bundle.Entry> entries = new ArrayList<>();

    while(tempBundle != null){
        entries.addAll(tempBundle.getEntry());
        if(tempBundle.getLink(Bundle.LINK_NEXT) != null) {
            tempBundle = fhirClient.loadPage().next(tempBundle).execute();
        }
        else{
            tempBundle = null;
        }
    }

    entries.forEach(bundle::addEntry);

    return bundle;

However, I was doing something like this in the while loop and it would end up in infinite loop:

while(tempBundle != null){
    entries.addAll(tempBundle.getEntry());
    tempBundle = fhirClient.loadPage().next(tempBundle).execute();
}

I was expecting the tempBundle would end up with null for a bundle without the next page, but it would never happen. Any idea?


Solution

  • You might want to take a look at this Example: BundleFetcher.java

    Especially the part where you populate the results with the following pages:

    while (bundle.getLink(IBaseBundle.LINK_NEXT) != null) {
            bundle = client
                .loadPage()
                .next(bundle)
                .execute();
    patients.addAll(BundleUtil.toListOfResources(ctx, bundle));
        }
    

    I think the offending part in your code is

    // Keep adding entries until the last page
    Bundle tempBundle = fhirClient.loadPage().next(bundle).execute();