/**
   * Deletes all resources created by tests, after all tests have been run.
   *
   * <p>This cleanup method will always be run, even if one or more tests fail. For this reason, it
   * attempts to remove all resources created at any point during testing, even if some of those
   * resources may be expected to be deleted by certain tests.
   *
   * @throws Exception
   */
  @AfterClass(alwaysRun = true)
  public void cleanUp() throws Exception {
    String noTest = System.getProperty("noTestCleanup");
    if (Boolean.TRUE.toString().equalsIgnoreCase(noTest)) {
      if (logger.isDebugEnabled()) {
        logger.debug("Skipping Cleanup phase ...");
      }
      return;
    }
    if (logger.isDebugEnabled()) {
      logger.debug("Cleaning up temporary resources created for testing ...");
    }
    PersonAuthorityClient personAuthClient = new PersonAuthorityClient();
    // Delete Person resource(s) (before PersonAuthority resources).

    for (String resourceId : personIdsCreated) {
      // Note: Any non-success responses are ignored and not reported.
      personAuthClient.deleteItem(personAuthCSID, resourceId).close();
    }

    // Delete PersonAuthority resource(s).
    // Note: Any non-success response is ignored and not reported.
    if (personAuthCSID != null) {
      personAuthClient.delete(personAuthCSID);
      // Delete Condition Checks resource(s).
      ConditioncheckClient conditioncheckClient = new ConditioncheckClient();
      for (String resourceId : conditioncheckIdsCreated) {
        // Note: Any non-success responses are ignored and not reported.
        conditioncheckClient.delete(resourceId).close();
      }
    }
  }
  // ---------------------------------------------------------------
  // CRUD tests : CREATE tests
  // ---------------------------------------------------------------
  // Success outcomes
  @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class)
  public void createWithAuthRefs(String testName) throws Exception {
    testSetup(STATUS_CREATED, ServiceRequestType.CREATE);

    // Submit the request to the service and store the response.
    String identifier = createIdentifier();

    // Create all the person refs and entities
    createPersonRefs();

    // Create a new Condition Check resource.
    //
    // One or more fields in this resource will be PersonAuthority
    // references, and will refer to Person resources by their refNames.
    ConditioncheckClient conditioncheckClient = new ConditioncheckClient();
    PoxPayloadOut multipart =
        createConditioncheckInstance(
            "conditionCheckRefNumber-" + identifier, conditionCheckerRefName);
    Response response = conditioncheckClient.create(multipart);
    int statusCode = response.getStatus();
    try {
      // Check the status code of the response: does it match
      // the expected response(s)?
      //
      // Specifically:
      // Does it fall within the set of valid status codes?
      // Does it exactly match the expected status code?
      if (logger.isDebugEnabled()) {
        logger.debug(testName + ": status = " + statusCode);
      }
      Assert.assertTrue(
          testRequestType.isValidStatusCode(statusCode),
          invalidStatusCodeMessage(testRequestType, statusCode));
      Assert.assertEquals(statusCode, testExpectedStatusCode);

      // Store the ID returned from the first resource created
      // for additional tests below.
      if (knownResourceId == null) {
        knownResourceId = extractId(response);
        if (logger.isDebugEnabled()) {
          logger.debug(testName + ": knownResourceId=" + knownResourceId);
        }
      }

      // Store the IDs from every resource created by tests,
      // so they can be deleted after tests have been run.
      conditioncheckIdsCreated.add(extractId(response));
    } finally {
      response.close();
    }
  }
  // Success outcomes
  @Test(
      dataProvider = "testName",
      dataProviderClass = AbstractServiceTestImpl.class,
      dependsOnMethods = {"createWithAuthRefs"})
  public void readAndCheckAuthRefs(String testName) throws Exception {
    // Perform setup.
    testSetup(STATUS_OK, ServiceRequestType.READ);

    // Submit the request to the service and store the response.
    ConditioncheckClient conditioncheckClient = new ConditioncheckClient();
    Response res = conditioncheckClient.read(knownResourceId);
    ConditionchecksCommon conditioncheckCommon = null;
    try {
      assertStatusCode(res, testName);
      // Extract the common part from the response.
      PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
      conditioncheckCommon =
          (ConditionchecksCommon)
              extractPart(
                  input, conditioncheckClient.getCommonPartName(), ConditionchecksCommon.class);
      Assert.assertNotNull(conditioncheckCommon);
      if (logger.isDebugEnabled()) {
        logger.debug(objectAsXmlString(conditioncheckCommon, ConditionchecksCommon.class));
      }
    } finally {
      if (res != null) {
        res.close();
      }
    }
    //
    // Check a couple of fields
    Assert.assertEquals(conditioncheckCommon.getConditionChecker(), conditionCheckerRefName);

    // Get the auth refs and check them
    Response res2 = conditioncheckClient.getAuthorityRefs(knownResourceId);
    AuthorityRefList list = null;
    try {
      assertStatusCode(res2, testName);
      list = res2.readEntity(AuthorityRefList.class);
      Assert.assertNotNull(list);
    } finally {
      if (res2 != null) {
        res2.close();
      }
    }

    List<AuthorityRefList.AuthorityRefItem> items = list.getAuthorityRefItem();
    int numAuthRefsFound = items.size();
    if (logger.isDebugEnabled()) {
      logger.debug(
          "Expected "
              + NUM_AUTH_REFS_EXPECTED
              + " authority references, found "
              + numAuthRefsFound);
    }

    // Optionally output additional data about list members for debugging.
    boolean iterateThroughList = true;
    if (iterateThroughList && logger.isDebugEnabled()) {
      int i = 0;
      for (AuthorityRefList.AuthorityRefItem item : items) {
        logger.debug(
            testName
                + ": list-item["
                + i
                + "] Field:"
                + item.getSourceField()
                + "= "
                + item.getAuthDisplayName()
                + item.getItemDisplayName());
        logger.debug(testName + ": list-item[" + i + "] refName=" + item.getRefName());
        logger.debug(testName + ": list-item[" + i + "] URI=" + item.getUri());
        i++;
      }
    }

    Assert.assertEquals(
        numAuthRefsFound,
        NUM_AUTH_REFS_EXPECTED,
        "Did not find all expected authority references! "
            + "Expected "
            + NUM_AUTH_REFS_EXPECTED
            + ", found "
            + numAuthRefsFound);
  }