Example #1
0
  @Override
  public <T extends IResource> Bundle search(
      final Class<T> theType, Map<String, List<IQueryParameterType>> theParams) {
    LinkedHashMap<String, List<String>> params = new LinkedHashMap<String, List<String>>();
    for (Entry<String, List<IQueryParameterType>> nextEntry : theParams.entrySet()) {
      ArrayList<String> valueList = new ArrayList<String>();
      String qualifier = null;
      for (IQueryParameterType nextValue : nextEntry.getValue()) {
        valueList.add(nextValue.getValueAsQueryToken());
        qualifier = nextValue.getQueryParameterQualifier();
      }
      qualifier = StringUtils.defaultString(qualifier);
      params.put(nextEntry.getKey() + qualifier, valueList);
    }

    BaseHttpClientInvocation invocation =
        SearchMethodBinding.createSearchInvocation(
            myContext, toResourceName(theType), params, null, null, null);
    if (isKeepResponses()) {
      myLastRequest = invocation.asHttpRequest(getServerBase(), createExtraParams(), getEncoding());
    }

    BundleResponseHandler binding = new BundleResponseHandler(theType);
    Bundle resp = invokeClient(myContext, binding, invocation, myLogRequestAndResponse);
    return resp;
  }
Example #2
0
  @Override
  public List<IResource> transaction(List<IResource> theResources) {
    BaseHttpClientInvocation invocation =
        TransactionMethodBinding.createTransactionInvocation(theResources, myContext);
    if (isKeepResponses()) {
      myLastRequest = invocation.asHttpRequest(getServerBase(), createExtraParams(), getEncoding());
    }

    Bundle resp =
        invokeClient(
            myContext, new BundleResponseHandler(null), invocation, myLogRequestAndResponse);

    return resp.toListOfResources();
  }
Example #3
0
  @Override
  public MethodOutcome validate(IResource theResource) {
    BaseHttpClientInvocation invocation =
        ValidateMethodBinding.createValidateInvocation(theResource, null, myContext);
    if (isKeepResponses()) {
      myLastRequest = invocation.asHttpRequest(getServerBase(), createExtraParams(), getEncoding());
    }

    RuntimeResourceDefinition def = myContext.getResourceDefinition(theResource);
    final String resourceName = def.getName();

    OutcomeResponseHandler binding = new OutcomeResponseHandler(resourceName);
    MethodOutcome resp = invokeClient(myContext, binding, invocation, myLogRequestAndResponse);
    return resp;
  }
Example #4
0
    protected <Z> Z invoke(
        Map<String, List<String>> theParams,
        IClientResponseHandler<Z> theHandler,
        BaseHttpClientInvocation theInvocation) {
      // if (myParamEncoding != null) {
      // theParams.put(Constants.PARAM_FORMAT,
      // Collections.singletonList(myParamEncoding.getFormatContentType()));
      // }
      //
      // if (myPrettyPrint != null) {
      // theParams.put(Constants.PARAM_PRETTY, Collections.singletonList(myPrettyPrint.toString()));
      // }

      if (isKeepResponses()) {
        myLastRequest = theInvocation.asHttpRequest(getServerBase(), theParams, getEncoding());
      }

      Z resp =
          invokeClient(
              myContext,
              theHandler,
              theInvocation,
              myParamEncoding,
              myPrettyPrint,
              myQueryLogRequestAndResponse || myLogRequestAndResponse);
      return resp;
    }
Example #5
0
  <T> T invokeClient(
      FhirContext theContext,
      IClientResponseHandler<T> binding,
      BaseHttpClientInvocation clientInvocation,
      EncodingEnum theEncoding,
      Boolean thePrettyPrint,
      boolean theLogRequestAndResponse) {

    if (!myDontValidateConformance) {
      myFactory.validateServerBaseIfConfiguredToDoSo(myUrlBase, myClient, this);
    }

    // TODO: handle non 2xx status codes by throwing the correct exception,
    // and ensure it's passed upwards
    HttpRequestBase httpRequest;
    HttpResponse response;
    try {
      Map<String, List<String>> params = createExtraParams();

      if (theEncoding == EncodingEnum.XML) {
        params.put(Constants.PARAM_FORMAT, Collections.singletonList("xml"));
      } else if (theEncoding == EncodingEnum.JSON) {
        params.put(Constants.PARAM_FORMAT, Collections.singletonList("json"));
      }

      if (thePrettyPrint == Boolean.TRUE) {
        params.put(
            Constants.PARAM_PRETTY, Collections.singletonList(Constants.PARAM_PRETTY_VALUE_TRUE));
      }

      EncodingEnum encoding = getEncoding();
      if (theEncoding != null) {
        encoding = theEncoding;
      }

      httpRequest = clientInvocation.asHttpRequest(myUrlBase, params, encoding, thePrettyPrint);

      if (theLogRequestAndResponse) {
        ourLog.info("Client invoking: {}", httpRequest);
        if (httpRequest instanceof HttpEntityEnclosingRequest) {
          HttpEntity entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity();
          if (entity.isRepeatable()) {
            String content = IOUtils.toString(entity.getContent());
            ourLog.info("Client request body: {}", content);
          }
        }
      }

      for (IClientInterceptor nextInterceptor : myInterceptors) {
        nextInterceptor.interceptRequest(httpRequest);
      }

      response = myClient.execute(httpRequest);

      for (IClientInterceptor nextInterceptor : myInterceptors) {
        nextInterceptor.interceptResponse(response);
      }

    } catch (DataFormatException e) {
      throw new FhirClientConnectionException(e);
    } catch (IOException e) {
      throw new FhirClientConnectionException(e);
    }

    try {
      String mimeType;
      if (Constants.STATUS_HTTP_204_NO_CONTENT == response.getStatusLine().getStatusCode()) {
        mimeType = null;
      } else {
        ContentType ct = ContentType.get(response.getEntity());
        mimeType = ct != null ? ct.getMimeType() : null;
      }

      Map<String, List<String>> headers = new HashMap<String, List<String>>();
      if (response.getAllHeaders() != null) {
        for (Header next : response.getAllHeaders()) {
          String name = next.getName().toLowerCase();
          List<String> list = headers.get(name);
          if (list == null) {
            list = new ArrayList<String>();
            headers.put(name, list);
          }
          list.add(next.getValue());
        }
      }

      if (response.getStatusLine().getStatusCode() < 200
          || response.getStatusLine().getStatusCode() > 299) {
        String body = null;
        Reader reader = null;
        try {
          reader = createReaderFromResponse(response);
          body = IOUtils.toString(reader);
        } catch (Exception e) {
          ourLog.debug("Failed to read input stream", e);
        } finally {
          IOUtils.closeQuietly(reader);
        }

        String message =
            "HTTP "
                + response.getStatusLine().getStatusCode()
                + " "
                + response.getStatusLine().getReasonPhrase();
        BaseOperationOutcome oo = null;
        if (Constants.CT_TEXT.equals(mimeType)) {
          message = message + ": " + body;
        } else {
          EncodingEnum enc = EncodingEnum.forContentType(mimeType);
          if (enc != null) {
            IParser p = enc.newParser(theContext);
            try {
              // TODO: handle if something other than OO comes back
              oo = (BaseOperationOutcome) p.parseResource(body);
              if (oo.getIssueFirstRep().getDetailsElement().isEmpty() == false) {
                message = message + ": " + oo.getIssueFirstRep().getDetailsElement().getValue();
              }
            } catch (Exception e) {
              ourLog.debug("Failed to process OperationOutcome response");
            }
          }
        }

        keepResponseAndLogIt(theLogRequestAndResponse, response, body);

        BaseServerResponseException exception =
            BaseServerResponseException.newInstance(
                response.getStatusLine().getStatusCode(), message);
        exception.setOperationOutcome(oo);

        if (body != null) {
          exception.setResponseBody(body);
        }

        throw exception;
      }
      if (binding instanceof IClientResponseHandlerHandlesBinary) {
        IClientResponseHandlerHandlesBinary<T> handlesBinary =
            (IClientResponseHandlerHandlesBinary<T>) binding;
        if (handlesBinary.isBinary()) {
          InputStream reader = response.getEntity().getContent();
          try {

            if (ourLog.isTraceEnabled() || myKeepResponses || theLogRequestAndResponse) {
              byte[] responseBytes = IOUtils.toByteArray(reader);
              if (myKeepResponses) {
                myLastResponse = response;
                myLastResponseBody = null;
              }
              String message =
                  "HTTP "
                      + response.getStatusLine().getStatusCode()
                      + " "
                      + response.getStatusLine().getReasonPhrase();
              if (theLogRequestAndResponse) {
                ourLog.info("Client response: {} - {} bytes", message, responseBytes.length);
              } else {
                ourLog.trace("Client response: {} - {} bytes", message, responseBytes.length);
              }
              reader = new ByteArrayInputStream(responseBytes);
            }

            return handlesBinary.invokeClient(
                mimeType, reader, response.getStatusLine().getStatusCode(), headers);
          } finally {
            IOUtils.closeQuietly(reader);
          }
        }
      }

      Reader reader = createReaderFromResponse(response);

      if (ourLog.isTraceEnabled() || myKeepResponses || theLogRequestAndResponse) {
        String responseString = IOUtils.toString(reader);
        keepResponseAndLogIt(theLogRequestAndResponse, response, responseString);
        reader = new StringReader(responseString);
      }

      try {
        return binding.invokeClient(
            mimeType, reader, response.getStatusLine().getStatusCode(), headers);
      } finally {
        IOUtils.closeQuietly(reader);
      }

    } catch (IllegalStateException e) {
      throw new FhirClientConnectionException(e);
    } catch (IOException e) {
      throw new FhirClientConnectionException(e);
    } finally {
      if (response instanceof CloseableHttpResponse) {
        try {
          ((CloseableHttpResponse) response).close();
        } catch (IOException e) {
          ourLog.debug("Failed to close response", e);
        }
      }
    }
  }