@Test
  public void testGetLocation() throws Exception {
    LocationRepository repository = container.getInjector().getInstance(LocationRepository.class);

    String id = repository.create(new Location("foo", 0, 0)).getId();
    HttpResponse httpResponse = container.execute(new HttpGet("/location/" + id));
    assertEquals(HttpURLConnection.HTTP_OK, httpResponse.getStatusLine().getStatusCode());
    HttpEntity entity = httpResponse.getEntity();
    assertEquals(ContentType.APPLICATION_JSON.getMimeType(), ContentType.get(entity).getMimeType());
    String content = EntityUtils.toString(entity);
    ObjectMapper om = new ObjectMapper();
    Map<String, ?> response = om.readValue(content, new TypeReference<Map<String, ?>>() {});
    assertEquals(id, response.get("id"));
  }
Beispiel #2
0
  public static Reader createReaderFromResponse(HttpResponse theResponse)
      throws IllegalStateException, IOException {
    HttpEntity entity = theResponse.getEntity();
    if (entity == null) {
      return new StringReader("");
    }
    Charset charset = null;
    if (entity.getContentType() != null
        && entity.getContentType().getElements() != null
        && entity.getContentType().getElements().length > 0) {
      ContentType ct = ContentType.get(entity);
      charset = ct.getCharset();
    }
    if (charset == null) {
      if (Constants.STATUS_HTTP_204_NO_CONTENT != theResponse.getStatusLine().getStatusCode()) {
        ourLog.warn("Response did not specify a charset.");
      }
      charset = Charset.forName("UTF-8");
    }

    Reader reader = new InputStreamReader(theResponse.getEntity().getContent(), charset);
    return reader;
  }
  protected void processAndAddLastClientInvocation(
      GenericClient theClient,
      ResultType theResultType,
      ModelMap theModelMap,
      long theLatency,
      String outcomeDescription,
      CaptureInterceptor theInterceptor,
      HomeRequest theRequest) {
    try {
      HttpRequestBase lastRequest = theInterceptor.getLastRequest();
      HttpResponse lastResponse = theInterceptor.getLastResponse();
      String requestBody = null;
      String requestUrl = lastRequest != null ? lastRequest.getURI().toASCIIString() : null;
      String action = lastRequest != null ? lastRequest.getMethod() : null;
      String resultStatus = lastResponse != null ? lastResponse.getStatusLine().toString() : null;
      String resultBody = StringUtils.defaultString(theInterceptor.getLastResponseBody());

      if (lastRequest instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) lastRequest).getEntity();
        if (entity.isRepeatable()) {
          requestBody = IOUtils.toString(entity.getContent());
        }
      }

      ContentType ct = lastResponse != null ? ContentType.get(lastResponse.getEntity()) : null;
      String mimeType = ct != null ? ct.getMimeType() : null;
      EncodingEnum ctEnum = EncodingEnum.forContentType(mimeType);
      String narrativeString = "";

      StringBuilder resultDescription = new StringBuilder();
      Bundle bundle = null;
      IBaseResource riBundle = null;

      FhirContext context = getContext(theRequest);
      if (ctEnum == null) {
        resultDescription.append("Non-FHIR response");
      } else {
        switch (ctEnum) {
          case JSON:
            if (theResultType == ResultType.RESOURCE) {
              narrativeString = parseNarrative(theRequest, ctEnum, resultBody);
              resultDescription.append("JSON resource");
            } else if (theResultType == ResultType.BUNDLE) {
              resultDescription.append("JSON bundle");
              if (context.getVersion().getVersion().isRi()) {
                riBundle = context.newJsonParser().parseResource(resultBody);
              } else {
                bundle = context.newJsonParser().parseBundle(resultBody);
              }
            }
            break;
          case XML:
          default:
            if (theResultType == ResultType.RESOURCE) {
              narrativeString = parseNarrative(theRequest, ctEnum, resultBody);
              resultDescription.append("XML resource");
            } else if (theResultType == ResultType.BUNDLE) {
              resultDescription.append("XML bundle");
              if (context.getVersion().getVersion().isRi()) {
                riBundle = context.newXmlParser().parseResource(resultBody);
              } else {
                bundle = context.newXmlParser().parseBundle(resultBody);
              }
            }
            break;
        }
      }

      resultDescription.append(" (").append(resultBody.length() + " bytes)");

      Header[] requestHeaders =
          lastRequest != null ? applyHeaderFilters(lastRequest.getAllHeaders()) : new Header[0];
      Header[] responseHeaders =
          lastResponse != null ? applyHeaderFilters(lastResponse.getAllHeaders()) : new Header[0];

      theModelMap.put("outcomeDescription", outcomeDescription);
      theModelMap.put("resultDescription", resultDescription.toString());
      theModelMap.put("action", action);
      theModelMap.put("bundle", bundle);
      theModelMap.put("riBundle", riBundle);
      theModelMap.put("resultStatus", resultStatus);

      theModelMap.put("requestUrl", requestUrl);
      theModelMap.put("requestUrlText", formatUrl(theClient.getUrlBase(), requestUrl));

      String requestBodyText = format(requestBody, ctEnum);
      theModelMap.put("requestBody", requestBodyText);

      String resultBodyText = format(resultBody, ctEnum);
      theModelMap.put("resultBody", resultBodyText);

      theModelMap.put("resultBodyIsLong", resultBodyText.length() > 1000);
      theModelMap.put("requestHeaders", requestHeaders);
      theModelMap.put("responseHeaders", responseHeaders);
      theModelMap.put("narrative", narrativeString);
      theModelMap.put("latencyMs", theLatency);

    } catch (Exception e) {
      ourLog.error("Failure during processing", e);
      theModelMap.put("errorMsg", "Error during processing: " + e.getMessage());
    }
  }
Beispiel #4
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);
        }
      }
    }
  }