View Javadoc
1   /*
2    * Copyright 2016 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *       http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.openehealth.ipf.commons.ihe.fhir;
18  
19  import org.hl7.fhir.instance.model.api.IBaseResource;
20  
21  import java.util.List;
22  import java.util.Map;
23  
24  /**
25   * Simple Bundle provider that fetches ALL results and caches them as soon as one
26   * of {@link #size()} or {@link #getResources(int, int)} is called.
27   * <p>
28   * Note: instances of this class is neither thread-safe nor can they be reused across requests
29   * </p>
30   */
31  public class EagerBundleProvider extends AbstractBundleProvider {
32  
33      private transient List<IBaseResource> resources;
34  
35      public EagerBundleProvider(RequestConsumer consumer, Object payload, Map<String, Object> headers) {
36          super(consumer, payload, headers);
37      }
38  
39      @Override
40      public List<IBaseResource> getResources(int fromIndex, int toIndex) {
41          List<IBaseResource> resources = fetchResources();
42          return resources.subList(fromIndex, Math.min(toIndex, resources.size()));
43      }
44  
45      @Override
46      public Integer size() {
47          return fetchResources().size();
48      }
49  
50      /**
51       * @return all matching resources, regardless of from/toIndex
52       */
53      private List<IBaseResource> fetchResources() {
54          if (resources == null) {
55              resources = obtainResources(getPayload(), getHeaders());
56          }
57          return resources;
58      }
59  }