/**
   * This utility method:
   *
   * <ul>
   *   <li>sets up a valid session
   *   <li>sends a request with a cookie containing the session ID
   *   <li>expects a 200 OK status code
   *   <li>fetches the (potentially updated) session
   * </ul>
   *
   * @param originalSession the session before the request is made
   * @param addCookie whether to add the session cookie to the request
   * @return the updated session
   * @throws Throwable
   */
  private Session makeSessionRequest(Session originalSession, boolean addCookie) throws Throwable {
    // wait for the clock to tick to ensure we can test the updated expiration time
    Thread.sleep(100);

    final PolicyTestRequest request = PolicyTestRequest.build(PolicyTestRequestType.GET, RESOURCE);

    if (addCookie) {
      // send request with cookie
      request.header(Constants.HEADER_COOKIE, CommonTestUtil.buildCookieHeader(originalSession));
    }

    final PolicyTestResponse response = send(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.code());

    // content should be returned
    assertNotNull(response.header(Constants.HEADER_CONTENT_LENGTH));

    // verify the session data in the shared state has changed
    final Session updatedSession = CommonTestUtil.fetchSession(originalSession.getSessionId());
    assertNotNull(updatedSession);
    assertEquals(originalSession.getSessionId(), updatedSession.getSessionId());

    // these should not change from request to request
    assertEquals(originalSession.getAbsoluteExpiry(), updatedSession.getAbsoluteExpiry());
    assertEquals(originalSession.getValidityPeriod(), updatedSession.getValidityPeriod());

    return updatedSession;
  }
  /**
   * Send the request and expect a 401 Unauthorized response, and for session data to remain
   * unchanged.
   *
   * @param request the service request
   * @param originalSession the Session state before the request is made
   * @throws Throwable
   */
  private void sendAndExpect401(PolicyTestRequest request, Session originalSession)
      throws Throwable {
    try {
      send(request);
      fail(PolicyFailureError.class + " expected");

    } catch (PolicyFailureError failure) {
      assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, failure.getFailure().getFailureCode());
      assertEquals(PolicyFailureType.Authentication, failure.getFailure().getType());

      // verify the session data in the shared state has not changed
      final Session updatedSession = CommonTestUtil.fetchSession(originalSession.getSessionId());
      assertNotNull(updatedSession);
      assertEquals(originalSession.getSessionId(), updatedSession.getSessionId());

      // verify expiry not updated
      assertEquals(originalSession.getExpires(), updatedSession.getExpires());
    }
  }