/** See issue #50 */
  @Test
  public void testOutOfBoundsDate() {
    Patient p = new Patient();
    p.setBirthDate(new DateDt("2000-15-31"));

    String encoded = ourCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(p);
    ourLog.info(encoded);

    assertThat(encoded, StringContains.containsString("2000-15-31"));

    p = ourCtx.newXmlParser().parseResource(Patient.class, encoded);
    assertEquals("2000-15-31", p.getBirthDateElement().getValueAsString());
    assertEquals("2001-03-31", new SimpleDateFormat("yyyy-MM-dd").format(p.getBirthDate()));

    ValidationResult result = ourCtx.newValidator().validateWithResult(p);
    String resultString =
        ourCtx
            .newXmlParser()
            .setPrettyPrint(true)
            .encodeResourceToString(result.toOperationOutcome());
    ourLog.info(resultString);

    assertEquals(2, ((OperationOutcome) result.toOperationOutcome()).getIssue().size());
    assertThat(resultString, StringContains.containsString("2000-15-31"));
  }
  @Test
  public void testMarshallSettings() throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    marshaller.marshal(settings, new StreamResult(bos));

    String result = bos.toString("UTF-8");
    System.out.println(result);

    assertThat(result, StringContains.containsString("<?xml"));
    assertThat(result, StringContains.containsString("<message>Hello OXM</message>"));
  }
  @Test
  public void testOriginHost() throws Exception {

    Logger logger = lc.getLogger(getClass());

    logger.info("Blubb Test");
    assertEquals(1, GelfTestSender.getMessages().size());

    GelfMessage gelfMessage = GelfTestSender.getMessages().get(0);

    String crossCheckHostName = gelfMessage.getAdditonalFields().get("crossCheckHostName");

    String json = gelfMessage.toJson();
    assertThat(
        json,
        StringContains.containsString("\"_crossCheckHostName\":\"" + crossCheckHostName + "\""));
    assertThat(json, StringContains.containsString("\"host\":\"" + crossCheckHostName + "\""));
  }
 @Test
 public void testCreateWithInvalidReferenceFailsGracefully() {
   Patient patient = new Patient();
   patient.addName().addFamily("testSearchResourceLinkWithChainWithMultipleTypes01");
   patient.setManagingOrganization(new ResourceReferenceDt("Patient/99999999"));
   try {
     ourPatientDao.create(patient);
     fail();
   } catch (InvalidRequestException e) {
     assertThat(e.getMessage(), StringContains.containsString("99999 not found"));
   }
 }
  @Test
  public final void
      givenRequestAcceptsMime_whenResourceIsRetrievedById__thenResponseContentTypeIsMime() {
    // Given
    final String uriForResourceCreation = getApi().createAsUri(createNewResource());

    // When
    final Response res = getApi().findOneByUriAsResponse(uriForResourceCreation, null);

    // Then
    assertThat(res.getContentType(), StringContains.containsString(marshaller.getMime()));
  }
  @Test
  public void updateSubscriptionForUser1() {
    String userID = user1;
    int i = 1;

    startNotificationChannel(userID, i);
    subscribeToAddressBookNotifications(userID, i);

    String test = "Updating/Extending the Subscription to Address Book Notifications for User 1";
    startTest(test);

    String clientCorrelator = Long.toString(System.currentTimeMillis());
    String callback = callbackURL[i];
    String requestData = requestDataClean(updateAddressBookRequestData, clientCorrelator, callback);
    String cleanUserID = cleanPrefix(userID);
    String url = subscriptionURL[i];
    url = prepare(url);

    RestAssured.authentication = RestAssured.basic(userID, applicationPassword);

    Response response =
        RestAssured.given()
            .contentType("application/json")
            .body(requestData)
            .expect()
            .log()
            .ifError()
            .statusCode(200)
            .body(
                "abChangesSubscription.resourceURL",
                StringContains.containsString(cleanUserID),
                "abChangesSubscription.callbackReference.callbackData",
                IsEqual.equalTo("GSMA1"),
                "abChangesSubscription.callbackReference.notifyURL",
                IsEqual.equalTo(callbackURL[i]),
                "abChangesSubscription.callbackReference.notificationFormat",
                IsEqual.equalTo("JSON"))
            .put(url);

    LOGGER.info("Response Received = " + response.getStatusCode());
    LOGGER.info("Body = " + response.asString());

    endTest(test);
  }
  @Test
  public void sessionIMChatAccept4()
      throws JsonGenerationException, JsonMappingException, IOException {
    Setup.startTest("Sending IM chat from User 3 to User 4");

    ChatMessage chatMessage = new ChatMessage("hello user4", "Displayed");
    ObjectMapper mapper = new ObjectMapper();
    String jsonRequestData = "{\"chatMessage\":" + mapper.writeValueAsString(chatMessage) + "}";

    System.out.println("Sending json=" + jsonRequestData);

    RestAssured.authentication = RestAssured.basic(Setup.TestUser3, Setup.applicationPassword);
    Response resp =
        RestAssured.given()
            .contentType("application/json")
            .body(jsonRequestData)
            .expect()
            .log()
            .ifError()
            .statusCode(201)
            .body(
                "resourceReference.resourceURL",
                StringContains.containsString(
                    Setup.encodedValue(Setup.TestUser3)
                        + "/oneToOne/"
                        + Setup.encodedValue(Setup.TestUser4Contact)
                        + "/"
                        + sessionID
                        + "/messages/"))
            .post(Setup.sendIMURL(Setup.TestUser3, Setup.TestUser4Contact, sessionID));

    sendMessageStatusURL = resp.jsonPath().getString("resourceReference.resourceURL");
    String[] parts = sendMessageStatusURL.split("/messages/");
    sentMessageID = parts[1].replaceAll("/status", "");
    System.out.println("Response = " + resp.getStatusCode() + " / " + resp.asString());
    System.out.println("resourceURL = " + sendMessageStatusURL);
    System.out.println("sentMessageID = " + sentMessageID);
    try {
      Thread.sleep(1500);
    } catch (InterruptedException e) {
    }
    Setup.endTest();
  }
  public List<TreeItem> getRESTValidationErrors(
      String wsProjectName, String description, int expectedCount) {
    Matcher<String> descriptionMatcher =
        description != null ? StringContains.containsString(description) : null;
    Matcher<String> pathMatcher =
        wsProjectName != null ? StringStartsWith.startsWith("/" + wsProjectName) : null;

    /* wait for jax-rs validation */
    if (expectedCount == 0
        && !new ProblemsExists()
            .test()) { // prevent from false positive result when we do not expect errors and there
                       // is no error
      new WaitWhile(
          new ProblemsCount(
              ProblemsCount.ProblemType.ERROR,
              expectedCount,
              descriptionMatcher,
              null,
              pathMatcher,
              null,
              null),
          WAIT_FOR_PROBLEMS_FALSE_POSItIVE_TIMEOUT,
          false);
    } else { // prevent from false negative result
      new WaitUntil(
          new ProblemsCount(
              ProblemsCount.ProblemType.ERROR,
              expectedCount,
              descriptionMatcher,
              null,
              pathMatcher,
              null,
              null),
          WAIT_FOR_PROBLEMS_FALSE_NEGATIVE_TIMEOUT,
          false);
    }

    /* return jax-rs validation errors */
    return new ProblemsView()
        .getErrors(descriptionMatcher, null, pathMatcher, null, Is.is(JAX_RS_PROBLEM));
  }
  @Test
  public void adhocIMChat() throws JsonGenerationException, JsonMappingException, IOException {
    Setup.majorTest("Chat/IM", "Adhoc chat between users 1 and 2");

    restart();
    Setup.startTest("Testing initiating IM chat between User 1 and User 2");

    ChatMessage chatMessage = new ChatMessage("hello", "Displayed");
    ObjectMapper mapper = new ObjectMapper();
    String jsonRequestData = "{\"chatMessage\":" + mapper.writeValueAsString(chatMessage) + "}";

    System.out.println("Sending json=" + jsonRequestData);

    RestAssured.authentication = RestAssured.basic(Setup.TestUser1, Setup.applicationPassword);
    Response resp =
        RestAssured.given()
            .contentType("application/json")
            .body(jsonRequestData)
            .expect()
            .log()
            .ifError()
            .statusCode(201)
            .body(
                "resourceReference.resourceURL",
                StringContains.containsString(
                    Setup.encodedValue(Setup.TestUser1)
                        + "/oneToOne/"
                        + Setup.encodedValue(Setup.TestUser2Contact)))
            .post(Setup.sendIMURL(Setup.TestUser1, Setup.TestUser2Contact, "adhoc"));

    sendMessageStatusURL = resp.jsonPath().getString("resourceReference.resourceURL");
    System.out.println("Response = " + resp.getStatusCode() + " / " + resp.asString());
    System.out.println("resourceURL = " + sendMessageStatusURL);
    try {
      Thread.sleep(1500);
    } catch (InterruptedException e) {
    }
    Setup.endTest();
  }
  public List<TreeItem> getRESTValidationWarnings(
      String wsProjectName, String description, int expectedCount) {
    Matcher<String> descriptionMatcher =
        description != null ? StringContains.containsString(description) : null;
    Matcher<String> pathMatcher =
        wsProjectName != null ? StringStartsWith.startsWith("/" + wsProjectName) : null;

    /* wait for warnings */
    if (expectedCount == 0) { // prevent from false-positive
      new WaitWhile(
          new ProblemsCount(
              ProblemsCount.ProblemType.WARNING,
              expectedCount,
              descriptionMatcher,
              null,
              pathMatcher,
              null,
              Is.is(JAX_RS_PROBLEM)),
          WAIT_FOR_PROBLEMS_FALSE_POSItIVE_TIMEOUT,
          false);
    } else { // prevent from false-negative
      new WaitUntil(
          new ProblemsCount(
              ProblemsCount.ProblemType.WARNING,
              expectedCount,
              descriptionMatcher,
              null,
              pathMatcher,
              null,
              Is.is(JAX_RS_PROBLEM)),
          WAIT_FOR_PROBLEMS_FALSE_NEGATIVE_TIMEOUT,
          false);
    }

    /* return jax-rs validation warnings */
    return new ProblemsView()
        .getWarnings(descriptionMatcher, null, pathMatcher, null, Is.is(JAX_RS_PROBLEM));
  }
  @Test
  public void sessionIMChatAccept()
      throws JsonGenerationException, JsonMappingException, IOException {
    Setup.majorTest("Chat/IM", "Confirmed chat between users 3 and 4");

    restart();
    Setup.startTest("Testing initiating IM chat session between User 3 and User 4");

    String requestData3 =
        "{\"chatNotificationSubscription\":{ \"callbackReference\":{\"notifyURL\":\""
            + Setup.callbackURL[3]
            + "\",\"callbackData\":\"GSMA3\"},\"clientCorrelator\":\""
            + UUID.randomUUID().toString()
            + "\", \"duration\":900, \"confirmedChatSupported\":true, \"adhocChatSupported\":false}}";
    String requestData4 =
        "{\"chatNotificationSubscription\":{ \"callbackReference\":{\"notifyURL\":\""
            + Setup.callbackURL[4]
            + "\",\"callbackData\":\"GSMA3\"},\"clientCorrelator\":\""
            + UUID.randomUUID().toString()
            + "\", \"duration\":900, \"confirmedChatSupported\":true, \"adhocChatSupported\":false}}";

    System.out.println("Setting chat subscription for confirmed session for user 3");
    RestAssured.authentication = RestAssured.basic(Setup.TestUser3, Setup.applicationPassword);
    Response resp =
        RestAssured.given()
            .contentType("application/json")
            .body(requestData3)
            .expect()
            .log()
            .ifError()
            .statusCode(201)
            .post(Setup.chatSubscriptionURL(Setup.TestUser3));
    System.out.println("Response = " + resp.getStatusCode() + " / " + resp.asString());

    System.out.println("Setting chat subscription for confirmed session for user 4");
    RestAssured.authentication = RestAssured.basic(Setup.TestUser4, Setup.applicationPassword);
    resp =
        RestAssured.given()
            .contentType("application/json")
            .body(requestData4)
            .expect()
            .log()
            .ifError()
            .statusCode(201)
            .post(Setup.chatSubscriptionURL(Setup.TestUser4));
    System.out.println("Response = " + resp.getStatusCode() + " / " + resp.asString());

    ChatSessionInformation chatSessionInformation =
        new ChatSessionInformation(
            "Session based IM", Setup.TestUser3Contact, "MO", Setup.TestUser4Contact, "MT");

    ObjectMapper mapper = new ObjectMapper();
    String jsonRequestData =
        "{\"chatSessionInformation\":" + mapper.writeValueAsString(chatSessionInformation) + "}";

    System.out.println("Sending json=" + jsonRequestData);

    RestAssured.authentication = RestAssured.basic(Setup.TestUser3, Setup.applicationPassword);
    resp =
        RestAssured.given()
            .contentType("application/json")
            .body(jsonRequestData)
            .expect()
            .log()
            .ifError()
            .statusCode(201)
            .body(
                "chatSessionInformation.status", Matchers.equalTo("Invited"),
                "chatSessionInformation.originatorAddress",
                    Matchers.equalTo(Setup.TestUser3Contact),
                "chatSessionInformation.tParticipantAddress",
                    Matchers.equalTo(Setup.TestUser4Contact),
                "chatSessionInformation.resourceURL",
                    StringContains.containsString(
                        Setup.encodedValue(Setup.TestUser3)
                            + "/oneToOne/"
                            + Setup.encodedValue(Setup.TestUser4Contact)))
            .post(Setup.createIMChatSessionURL(Setup.TestUser3, Setup.TestUser4Contact));

    System.out.println("Response = " + resp.getStatusCode() + " / " + resp.asString());

    JsonPath jsonData = resp.jsonPath();

    sendSessionURL = jsonData.getString("chatSessionInformation.resourceURL");
    System.out.println("sendSessionURL = " + sendSessionURL);
    try {
      Thread.sleep(500);
    } catch (InterruptedException e) {
    }
    Setup.endTest();
  }