001package org.hl7.fhir.r4.utils.client;
002
003import java.io.IOException;
004import java.net.URI;
005import java.net.URISyntaxException;
006import java.util.*;
007
008import lombok.Getter;
009import lombok.Setter;
010import org.hl7.fhir.exceptions.FHIRException;
011import org.hl7.fhir.r4.model.Bundle;
012import org.hl7.fhir.r4.model.CapabilityStatement;
013import org.hl7.fhir.r4.model.CodeSystem;
014import org.hl7.fhir.r4.model.Coding;
015import org.hl7.fhir.r4.model.ConceptMap;
016import org.hl7.fhir.r4.model.OperationOutcome;
017import org.hl7.fhir.r4.model.Parameters;
018import org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent;
019import org.hl7.fhir.r4.model.PrimitiveType;
020import org.hl7.fhir.r4.model.Resource;
021import org.hl7.fhir.r4.model.StringType;
022import org.hl7.fhir.r4.model.TerminologyCapabilities;
023import org.hl7.fhir.r4.model.ValueSet;
024import org.hl7.fhir.r4.utils.client.network.ByteUtils;
025import org.hl7.fhir.r4.utils.client.network.Client;
026import org.hl7.fhir.r4.utils.client.network.ResourceRequest;
027import org.hl7.fhir.utilities.FHIRBaseToolingClient;
028import org.hl7.fhir.utilities.ITerminologyRequestIdProvider;
029import org.hl7.fhir.utilities.ToolingClientLogger;
030import org.hl7.fhir.utilities.Utilities;
031
032import org.hl7.fhir.utilities.http.HTTPHeader;
033
034/**
035 * Very Simple RESTful client. This is purely for use in the standalone tools
036 * jar packages. It doesn't support many features, only what the tools need.
037 * <p>
038 * To use, initialize class and set base service URI as follows:
039 *
040 * <pre>
041 * <code>
042 * FHIRSimpleClient fhirClient = new FHIRSimpleClient();
043 * fhirClient.initialize("http://my.fhir.domain/myServiceRoot");
044 * </code>
045 * </pre>
046 * <p>
047 * Default Accept and Content-Type headers are application/fhir+xml and
048 * application/fhir+json.
049 * <p>
050 * These can be changed by invoking the following setter functions:
051 *
052 * <pre>
053 * <code>
054 * setPreferredResourceFormat()
055 * setPreferredFeedFormat()
056 * </code>
057 * </pre>
058 * <p>
059 * TODO Review all sad paths.
060 *
061 * @author Claude Nanjo
062 */
063public class FHIRToolingClient extends FHIRBaseToolingClient {
064
065  public static final String DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssK";
066  public static final String DATE_FORMAT = "yyyy-MM-dd";
067  public static final String hostKey = "http.proxyHost";
068  public static final String portKey = "http.proxyPort";
069
070  private String base;
071  private ResourceAddress resourceAddress;
072  @Setter
073  private ResourceFormat preferredResourceFormat;
074  private int maxResultSetSize = -1;// _count
075  @Getter
076  @Setter
077  private Client client = new Client();
078  private List<HTTPHeader> headers = new ArrayList<>();
079
080  @Getter @Setter
081  private String userAgent;
082  @Setter
083  private String acceptLanguage;
084
085  @Getter @Setter
086  private ITerminologyRequestIdProvider requestIdProvider;
087
088  @Setter
089  private String contentLanguage;
090  private int useCount;
091  
092  // Pass endpoint for client - URI
093  public FHIRToolingClient(String baseServiceUrl, String userAgent) throws URISyntaxException {
094    preferredResourceFormat = ResourceFormat.RESOURCE_JSON;
095    this.userAgent = userAgent;
096    initialize(baseServiceUrl);
097  }
098
099  public void initialize(String baseServiceUrl) throws URISyntaxException {
100    base = baseServiceUrl;
101    client.setBase(base);
102    resourceAddress = new ResourceAddress(baseServiceUrl);
103    this.maxResultSetSize = -1;
104  }
105
106  public String getPreferredResourceFormat() {
107    return preferredResourceFormat.getHeader();
108  }
109
110  public int getMaximumRecordCount() {
111    return maxResultSetSize;
112  }
113
114  public void setMaximumRecordCount(int maxResultSetSize) {
115    this.maxResultSetSize = maxResultSetSize;
116  }
117
118  public TerminologyCapabilities getTerminologyCapabilities() {
119    TerminologyCapabilities capabilities = null;
120    try {
121      capabilities = (TerminologyCapabilities) client.issueGetResourceRequest(resourceAddress.resolveMetadataTxCaps(),
122          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(false), "TerminologyCapabilities", timeoutNormal).getReference();
123    } catch (Exception e) {
124      throw new FHIRException("Error fetching the server's terminology capabilities: "+e.getMessage(), e);
125    }
126    return capabilities;
127  }
128
129  public CapabilityStatement getCapabilitiesStatementQuick() {
130    CapabilityStatement conformance = null;
131    try {
132      conformance = (CapabilityStatement) client.issueGetResourceRequest(resourceAddress.resolveMetadataUri(true),
133          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(false), "CapabilitiesStatement", timeoutNormal).getReference();
134    } catch (Exception e) {
135      throw new FHIRException("Error fetching the server's conformance statement", e);
136    }
137    return conformance;
138  }
139
140  public CapabilityStatement getCapabilitiesStatement() throws EFhirClientException {
141   try {
142     return (CapabilityStatement) client.issueGetResourceRequest(resourceAddress.resolveMetadataUri(false),
143         withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(false), "CapabilitiesStatement-Quick", timeoutNormal)
144         .getReference();
145   } catch (Exception e) {
146     throw new FHIRException("Error fetching the server's capability statement: " + e.getMessage(), e);
147   }
148 }
149
150  public Resource read(String resourceClass, String id) {// TODO Change this to AddressableResource
151    recordUse();
152    ResourceRequest<Resource> result = null;
153    try {
154      result = client.issueGetResourceRequest(resourceAddress.resolveGetUriFromResourceClassAndId(resourceClass, id),
155          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(false), "Read " + resourceClass + "/" + id,
156          timeoutNormal);
157      if (result.isUnsuccessfulRequest()) {
158        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
159            (OperationOutcome) result.getPayload());
160      }
161    } catch (Exception e) {
162      throw new FHIRException(e);
163    }
164    return result.getPayload();
165  }
166
167  public <T extends Resource> T read(Class<T> resourceClass, String id) {// TODO Change this to AddressableResource
168    recordUse();
169    ResourceRequest<T> result = null;
170    try {
171      result = client.issueGetResourceRequest(resourceAddress.resolveGetUriFromResourceClassAndId(resourceClass, id),
172          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(false), "Read " + resourceClass.getName() + "/" + id,
173          timeoutNormal);
174      if (result.isUnsuccessfulRequest()) {
175        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
176            (OperationOutcome) result.getPayload());
177      }
178    } catch (Exception e) {
179      throw new FHIRException(e);
180    }
181    return result.getPayload();
182  }
183
184  public <T extends Resource> T vread(Class<T> resourceClass, String id, String version) {
185    recordUse();
186    ResourceRequest<T> result = null;
187    try {
188      result = client.issueGetResourceRequest(
189          resourceAddress.resolveGetUriFromResourceClassAndIdAndVersion(resourceClass, id, version),
190          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(false),
191          "VRead " + resourceClass.getName() + "/" + id + "/?_history/" + version, timeoutNormal);
192      if (result.isUnsuccessfulRequest()) {
193        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
194            (OperationOutcome) result.getPayload());
195      }
196    } catch (Exception e) {
197      throw new FHIRException("Error trying to read this version of the resource", e);
198    }
199    return result.getPayload();
200  }
201
202  public <T extends Resource> T getCanonical(Class<T> resourceClass, String canonicalURL) {
203    recordUse();
204    ResourceRequest<T> result = null;
205    try {
206      result = client.issueGetResourceRequest(
207          resourceAddress.resolveGetUriFromResourceClassAndCanonical(resourceClass, canonicalURL),
208          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(false), "Read " + resourceClass.getName() + "?url=" + canonicalURL,
209          timeoutNormal);
210      if (result.isUnsuccessfulRequest()) {
211        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
212            (OperationOutcome) result.getPayload());
213      }
214    } catch (Exception e) {
215      handleException(0, "An error has occurred while trying to read this version of the resource", e);
216    }
217    Bundle bnd = (Bundle) result.getPayload();
218    if (bnd.getEntry().size() == 0)
219      throw new EFhirClientException("No matching resource found for canonical URL '" + canonicalURL + "'");
220    if (bnd.getEntry().size() > 1)
221      throw new EFhirClientException("Multiple matching resources found for canonical URL '" + canonicalURL + "'");
222    return (T) bnd.getEntry().get(0).getResource();
223  }
224
225  public Resource update(Resource resource) {
226    recordUse();
227    org.hl7.fhir.r4.utils.client.network.ResourceRequest<Resource> result = null;
228    try {
229      result = client.issuePutRequest(
230          resourceAddress.resolveGetUriFromResourceClassAndId(resource.getClass(), resource.getId()),
231          ByteUtils.resourceToByteArray(resource, false, isJson(getPreferredResourceFormat()), false),
232          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true), "Update " + resource.fhirType() + "/" + resource.getId(),
233          timeoutOperation);
234      if (result.isUnsuccessfulRequest()) {
235        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
236            (OperationOutcome) result.getPayload());
237      }
238    } catch (Exception e) {
239      throw new EFhirClientException(0, "An error has occurred while trying to update this resource", e);
240    }
241    // TODO oe 26.1.2015 could be made nicer if only OperationOutcome locationheader
242    // is returned with an operationOutcome would be returned (and not the resource
243    // also) we make another read
244    try {
245      OperationOutcome operationOutcome = (OperationOutcome) result.getPayload();
246      ResourceAddress.ResourceVersionedIdentifier resVersionedIdentifier = ResourceAddress
247          .parseCreateLocation(result.getLocation());
248      return this.vread(resource.getClass(), resVersionedIdentifier.getId(), resVersionedIdentifier.getVersionId());
249    } catch (ClassCastException e) {
250      // if we fall throught we have the correct type already in the create
251    }
252
253    return result.getPayload();
254  }
255
256  public <T extends Resource> T update(Class<T> resourceClass, T resource, String id) {
257    recordUse();
258    ResourceRequest<T> result = null;
259    try {
260      result = client.issuePutRequest(resourceAddress.resolveGetUriFromResourceClassAndId(resourceClass, id),
261          ByteUtils.resourceToByteArray(resource, false, isJson(getPreferredResourceFormat()), false),
262          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true), "Update " + resource.fhirType() + "/" + id,
263          timeoutOperation);
264      if (result.isUnsuccessfulRequest()) {
265        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
266            (OperationOutcome) result.getPayload());
267      }
268    } catch (Exception e) {
269      throw new EFhirClientException(0, "An error has occurred while trying to update this resource", e);
270    }
271    // TODO oe 26.1.2015 could be made nicer if only OperationOutcome locationheader
272    // is returned with an operationOutcome would be returned (and not the resource
273    // also) we make another read
274    try {
275      OperationOutcome operationOutcome = (OperationOutcome) result.getPayload();
276      ResourceAddress.ResourceVersionedIdentifier resVersionedIdentifier = ResourceAddress
277          .parseCreateLocation(result.getLocation());
278      return this.vread(resourceClass, resVersionedIdentifier.getId(), resVersionedIdentifier.getVersionId());
279    } catch (ClassCastException e) {
280      // if we fall through we have the correct type already in the create
281    }
282
283    return result.getPayload();
284  }
285
286  public <T extends Resource> Parameters operateType(Class<T> resourceClass, String name, Parameters params) throws IOException {
287    recordUse();
288    boolean complex = false;
289    for (ParametersParameterComponent p : params.getParameter())
290      complex = complex || !(p.getValue() instanceof PrimitiveType);
291    String ps = "";
292    if (!complex)
293      for (ParametersParameterComponent p : params.getParameter())
294        if (p.getValue() instanceof PrimitiveType)
295          ps += Utilities.encodeUriParam(p.getName(), ((PrimitiveType) p.getValue()).asStringValue()) + "&";
296    ResourceRequest<T> result;
297    URI url = resourceAddress.resolveOperationURLFromClass(resourceClass, name, ps);
298    if (complex) {
299      byte[] body = ByteUtils.resourceToByteArray(params, false, isJson(getPreferredResourceFormat()), true);
300      result = client.issuePostRequest(url, body, withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true),
301          "POST " + resourceClass.getName() + "/$" + name, timeoutLong);
302    } else {
303      result = client.issueGetResourceRequest(url, withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(false),
304          "GET " + resourceClass.getName() + "/$" + name, timeoutLong);
305    }
306    if (result.isUnsuccessfulRequest()) {
307      throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
308          (OperationOutcome) result.getPayload());
309    }
310    if (result.getPayload() instanceof Parameters) {
311      return (Parameters) result.getPayload();
312    } else {
313      Parameters p_out = new Parameters();
314      p_out.addParameter().setName("return").setResource(result.getPayload());
315      return p_out;
316    }
317  }
318
319  public Bundle transaction(Bundle batch) {
320    recordUse();
321    Bundle transactionResult = null;
322    try {
323      transactionResult = client.postBatchRequest(resourceAddress.getBaseServiceUri(),
324          ByteUtils.resourceToByteArray(batch, false, isJson(getPreferredResourceFormat()), false),
325          withVer(getPreferredResourceFormat(), "4.0"), "transaction", timeoutOperation + (timeoutEntry * batch.getEntry().size()));
326    } catch (Exception e) {
327      handleException(0, "An error occurred trying to process this transaction request", e);
328    }
329    return transactionResult;
330  }
331
332  @SuppressWarnings("unchecked")
333  public <T extends Resource> OperationOutcome validate(Class<T> resourceClass, T resource, String id) {
334    recordUse();
335    ResourceRequest<T> result = null;
336    try {
337      result = client.issuePostRequest(resourceAddress.resolveValidateUri(resourceClass, id),
338          ByteUtils.resourceToByteArray(resource, false, isJson(getPreferredResourceFormat()), false),
339          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true),
340          "POST " + resourceClass.getName() + (id != null ? "/" + id : "") + "/$validate", timeoutLong);
341      if (result.isUnsuccessfulRequest()) {
342        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
343            (OperationOutcome) result.getPayload());
344      }
345    } catch (Exception e) {
346      handleException(0, "An error has occurred while trying to validate this resource", e);
347    }
348    return (OperationOutcome) result.getPayload();
349  }
350
351  @SuppressWarnings("unchecked")
352  public <T extends Resource> OperationOutcome validate(Resource resource, String id) {
353    recordUse();
354    ResourceRequest<T> result = null;
355    try {
356      result = client.issuePostRequest(resourceAddress.resolveValidateUri(resource.fhirType(), id),
357          ByteUtils.resourceToByteArray(resource, false, isJson(getPreferredResourceFormat()), false),
358          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true),
359          "POST " + resource.fhirType() + (id != null ? "/" + id : "") + "/$validate", timeoutLong);
360      if (result.isUnsuccessfulRequest()) {
361        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
362            (OperationOutcome) result.getPayload());
363      }
364    } catch (Exception e) {
365      handleException(0, "An error has occurred while trying to validate this resource", e);
366    }
367    return (OperationOutcome) result.getPayload();
368  }
369
370  /**
371   * Helper method to prevent nesting of previously thrown EFhirClientExceptions. If the e param is an instance of
372   * EFhirClientException, it will be rethrown. Otherwise, a new EFhirClientException will be thrown with e as the
373   * cause.
374   *
375   * @param code The EFhirClientException code.
376   * @param message The EFhirClientException message.
377   * @param e The exception.
378   * @throws EFhirClientException representing the exception.
379   */
380  protected void handleException(int code, String message, Exception e) throws EFhirClientException {
381    if (e instanceof EFhirClientException) {
382      throw (EFhirClientException) e;
383    } else {
384      throw new EFhirClientException(code, message, e);
385    }
386  }
387
388  /**
389   * Helper method to determine whether desired resource representation
390   * is Json or XML.
391   *
392   * @param format The format
393   * @return true if the format is JSON, false otherwise
394   */
395  protected boolean isJson(String format) {
396    boolean isJson = false;
397    if (format.toLowerCase().contains("json")) {
398      isJson = true;
399    }
400    return isJson;
401  }
402
403  public Bundle fetchFeed(String url) {
404    recordUse();
405    Bundle feed = null;
406    try {
407      feed = client.issueGetFeedRequest(new URI(url), withVer(getPreferredResourceFormat(), "4.0"), timeoutLong);
408    } catch (Exception e) {
409      handleException(0, "An error has occurred while trying to read a bundle", e);
410    }
411    return feed;
412  }
413
414  public Parameters lookupCode(Map<String, String> params) {
415    recordUse();
416    org.hl7.fhir.r4.utils.client.network.ResourceRequest<Resource> result = null;
417    try {
418      result = client.issueGetResourceRequest(resourceAddress.resolveOperationUri(CodeSystem.class, "lookup", params),
419          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(false), "CodeSystem/$lookup", timeoutNormal);
420    } catch (IOException e) {
421      throw new FHIRException(e);
422    }
423    if (result.isUnsuccessfulRequest()) {
424      throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
425          (OperationOutcome) result.getPayload());
426    }
427    return (Parameters) result.getPayload();
428  }
429
430  public Parameters lookupCode(Parameters p) {
431    recordUse();
432    org.hl7.fhir.r4.utils.client.network.ResourceRequest<Resource> result = null;
433    try {
434      result = client.issuePostRequest(resourceAddress.resolveOperationUri(CodeSystem.class, "lookup"),
435          ByteUtils.resourceToByteArray(p, false, isJson(getPreferredResourceFormat()), true),
436          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true), "CodeSystem/$lookup", timeoutNormal);
437    } catch (IOException e) {
438      throw new FHIRException(e);
439    }
440    if (result.isUnsuccessfulRequest()) {
441      throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
442          (OperationOutcome) result.getPayload());
443    }
444    return (Parameters) result.getPayload();
445  }
446
447  public Parameters translate(Parameters p) {
448    recordUse();
449    org.hl7.fhir.r4.utils.client.network.ResourceRequest<Resource> result = null;
450    try {
451      result = client.issuePostRequest(resourceAddress.resolveOperationUri(ConceptMap.class, "translate"),
452        ByteUtils.resourceToByteArray(p, false, isJson(getPreferredResourceFormat()), true),
453        withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true), "ConceptMap/$translate", timeoutNormal);
454    } catch (IOException e) {
455      throw new FHIRException(e);
456    }
457    if (result.isUnsuccessfulRequest()) {
458      throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
459        (OperationOutcome) result.getPayload());
460    }
461    return (Parameters) result.getPayload();
462  }
463
464  public Parameters doRelated(Parameters p) {
465    recordUse();
466    org.hl7.fhir.r4.utils.client.network.ResourceRequest<Resource> result = null;
467    try {
468      result = client.issuePostRequest(resourceAddress.resolveOperationUri(ValueSet.class, "related"),
469        ByteUtils.resourceToByteArray(p, false, isJson(getPreferredResourceFormat()), true),
470        withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true), "ValueSet/related", timeoutNormal);
471    } catch (IOException e) {
472      throw new FHIRException(e);
473    }
474    if (result.isUnsuccessfulRequest()) {
475      throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
476        (OperationOutcome) result.getPayload());
477    }
478    return (Parameters) result.getPayload();
479  }
480
481  public ValueSet expandValueset(ValueSet source, Parameters expParams) {
482    recordUse();
483    Parameters p = expParams == null ? new Parameters() : expParams.copy();
484    if (source != null) {
485      p.addParameter().setName("valueSet").setResource(source);
486    }
487    org.hl7.fhir.r4.utils.client.network.ResourceRequest<Resource> result = null;
488    try {
489      result = client.issuePostRequest(resourceAddress.resolveOperationUri(ValueSet.class, "expand"),
490          ByteUtils.resourceToByteArray(p, false, isJson(getPreferredResourceFormat()), true), withVer(getPreferredResourceFormat(), "4.0"),
491          generateHeaders(true), source == null ? "ValueSet/$expand" : "ValueSet/$expand?url=" + source.getUrl(),
492              timeoutExpand);
493      if (result.isUnsuccessfulRequest()) {
494        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
495            (OperationOutcome) result.getPayload());
496      }
497    } catch (EFhirClientException e) {
498      if (e.getServerErrors().size() > 0) {
499        throw new EFhirClientException(e.getCode(), e.getMessage(), e.getServerErrors().get(0));
500      } else {
501        throw new EFhirClientException(e.getCode(), e.getMessage(), e);
502      }
503    } catch (Exception e) {
504      throw new EFhirClientException(0, e.getMessage(), e);
505    }
506    return result == null ? null : (ValueSet) result.getPayload();
507  }
508
509  public String getAddress() {
510    return base;
511  }
512
513  public ConceptMap initializeClosure(String name) {
514    recordUse();
515    Parameters params = new Parameters();
516    params.addParameter().setName("name").setValue(new StringType(name));
517    ResourceRequest<Resource> result = null;
518    try {
519      result = client.issuePostRequest(
520          resourceAddress.resolveOperationUri(null, "closure", new HashMap<String, String>()),
521          ByteUtils.resourceToByteArray(params, false, isJson(getPreferredResourceFormat()), true),
522          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true), "Closure?name=" + name, timeoutNormal);
523      if (result.isUnsuccessfulRequest()) {
524        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
525            (OperationOutcome) result.getPayload());
526      }
527    } catch (IOException e) {
528      throw new FHIRException(e);
529    }
530    return result == null ? null : (ConceptMap) result.getPayload();
531  }
532
533  public ConceptMap updateClosure(String name, Coding coding) {
534    recordUse();
535    Parameters params = new Parameters();
536    params.addParameter().setName("name").setValue(new StringType(name));
537    params.addParameter().setName("concept").setValue(coding);
538    org.hl7.fhir.r4.utils.client.network.ResourceRequest<Resource> result = null;
539    try {
540      result = client.issuePostRequest(
541          resourceAddress.resolveOperationUri(null, "closure", new HashMap<String, String>()),
542          ByteUtils.resourceToByteArray(params, false, isJson(getPreferredResourceFormat()), true),
543          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true), "UpdateClosure?name=" + name, timeoutOperation);
544      if (result.isUnsuccessfulRequest()) {
545        throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
546            (OperationOutcome) result.getPayload());
547      }
548    } catch (IOException e) {
549      throw new FHIRException(e);
550    }
551    return result == null ? null : (ConceptMap) result.getPayload();
552  }
553
554  public ToolingClientLogger getLogger() {
555    return client.getLogger();
556  }
557
558  public void setLogger(ToolingClientLogger logger) {
559    client.setLogger(logger);
560  }
561
562  public int getRetryCount() {
563    return client.getRetryCount();
564  }
565
566  public void setRetryCount(int retryCount) {
567    client.setRetryCount(retryCount);
568  }
569
570  public void setClientHeaders(Iterable<HTTPHeader> headers) {
571    this.headers = new ArrayList<>();
572    headers.forEach(this.headers::add);
573  }
574
575  private Iterable<HTTPHeader> generateHeaders(boolean hasBody) {
576    // Add any other headers
577    List<HTTPHeader> headers = new ArrayList<>(this.headers);
578    if (!Utilities.noString(userAgent)) {
579      headers.add(new HTTPHeader("User-Agent",userAgent));
580    }
581
582    if (!Utilities.noString(acceptLanguage)) {
583      headers.add(new HTTPHeader("Accept-Language", acceptLanguage));
584    }
585
586    if (hasBody && !Utilities.noString(contentLanguage)) {
587      headers.add(new HTTPHeader("Content-Language",contentLanguage));
588    }
589    if (requestIdProvider != null) {
590      String header = requestIdProvider.getRequestId();
591      if (header != null) {
592        headers.add(new HTTPHeader("X-Request-Id", header));
593      }
594    }
595
596    return headers;
597  }
598
599  public String getServerVersion() {
600    return getCapabilitiesStatementQuick().getSoftware().getVersion();
601  }
602
603  public Bundle search(String type, String criteria) {
604    recordUse();
605    return fetchFeed(Utilities.pathURL(base, type+criteria));
606  }
607
608  public <T extends Resource> T fetchResource(Class<T> resourceClass, String id) {
609    recordUse();
610    org.hl7.fhir.r4.utils.client.network.ResourceRequest<Resource> result = null;
611    try {
612      result = client.issueGetResourceRequest(resourceAddress.resolveGetResource(resourceClass, id),
613          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(true), resourceClass.getName()+"/"+id, timeoutNormal);
614    } catch (IOException e) {
615      throw new FHIRException(e);
616    }
617    if (result.isUnsuccessfulRequest()) {
618      throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
619          (OperationOutcome) result.getPayload());
620    }
621    return (T) result.getPayload();
622  }
623
624  public int getUseCount() {
625    return useCount;
626  }
627
628  private void recordUse() {
629    useCount++;    
630  }
631
632  public Parameters subsumes(Map<String, String> params) {
633    recordUse();
634    org.hl7.fhir.r4.utils.client.network.ResourceRequest<Resource> result = null;
635    try {
636      result = client.issueGetResourceRequest(resourceAddress.resolveOperationUri(CodeSystem.class, "subsumes", params),
637          withVer(getPreferredResourceFormat(), "4.0"), generateHeaders(false), "CodeSystem/$subsumes", timeoutNormal);
638    } catch (IOException e) {
639      throw new FHIRException(e);
640    }
641    if (result.isUnsuccessfulRequest()) {
642      throw new EFhirClientException(result.getHttpStatus(), "Server returned error code " + result.getHttpStatus(),
643          (OperationOutcome) result.getPayload());
644    }
645    return (Parameters) result.getPayload();
646  }
647
648  
649}