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