@Test
  public void test() throws Exception {
    // use admin
    TestContext testContext = TestContainer.getInstance().getTestContext();

    // user is created at security.xml

    testContext.setUsername(NEXUS504_USER);
    testContext.setPassword(TEST_USER_PASSWORD);

    assertThat(UserCreationUtil.login(), hasStatusCode(403));

    // add login privilege to role
    testContext.useAdminForRequests();

    RoleResource role = roleUtil.getRole(NEXUS504_ROLE);
    role.addPrivilege("2" /* login */);
    assertThat(
        "Unable to add login privilege to role "
            + NEXUS504_ROLE
            + "\n"
            + RoleMessageUtil.update(role).getDescription(),
        RoleMessageUtil.update(role),
        isSuccess());

    // try to login again
    testContext.setUsername(NEXUS504_USER);
    testContext.setPassword(TEST_USER_PASSWORD);
    Status status2 = UserCreationUtil.login();
    assertThat(status2, hasStatusCode(200));
  }
  /**
   * Makes a request after setting the user agent and verifies that the session cookie is NOT set.
   *
   * @param userAgent
   * @throws Exception
   */
  private void testCookieNotSetForKnownStateLessClients(String userAgent) throws Exception {
    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + "content/";

    Header header = new Header("User-Agent", userAgent + "/1.6"); // user agent plus some version

    HttpClient httpClient = new HttpClient();
    httpClient
        .getState()
        .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    GetMethod getMethod = new GetMethod(url);
    getMethod.addRequestHeader(header);
    assertThat(executeAndRelease(httpClient, getMethod), equalTo(200));

    Cookie sessionCookie = this.getSessionCookie(httpClient.getState().getCookies());
    assertThat(
        "Session Cookie should not be set for user agent: " + userAgent,
        sessionCookie,
        nullValue());
  }
  @Test
  public void testCookieForStateFullClient() throws Exception {
    setAnonymousAccess(false);

    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + "content/";

    // default useragent is: Jakarta Commons-HttpClient/3.1[\r][\n]
    HttpClient httpClient = new HttpClient();
    httpClient
        .getState()
        .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    // stateful clients must login first, since other rest urls create no sessions
    String loginUrl = this.getBaseNexusUrl() + "service/local/authentication/login";
    httpClient.getParams().setAuthenticationPreemptive(true); // go straight to basic auth
    assertThat(executeAndRelease(httpClient, new GetMethod(loginUrl)), equalTo(200));

    GetMethod getMethod = new GetMethod(url);
    assertThat(executeAndRelease(httpClient, getMethod), equalTo(200));
    Cookie sessionCookie = this.getSessionCookie(httpClient.getState().getCookies());
    assertThat("Session Cookie not set", sessionCookie, notNullValue());
    httpClient.getState().clear(); // remove cookies, credentials, etc

    // do not set the cookie, expect failure
    GetMethod failedGetMethod = new GetMethod(url);
    assertThat(executeAndRelease(httpClient, failedGetMethod), equalTo(401));

    // set the cookie expect a 200, If a cookie is set, and cannot be found on the server, the
    // response will fail with a 401
    httpClient.getState().addCookie(sessionCookie);
    getMethod = new GetMethod(url);
    assertThat(executeAndRelease(httpClient, getMethod), equalTo(200));
  }
  /**
   * 1.) Make a get request to set a cookie </BR> 2.) verify cookie works (do not send basic auth)
   * </BR> 3.) do logout </BR> 4.) repeat step 2 and expect failure.
   */
  @Test
  public void testLogout() throws Exception {
    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "status";
    String logoutUrl =
        this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "authentication/logout";

    Header userAgentHeader = new BasicHeader("User-Agent", "Something Stateful");

    // default useragent is: Jakarta Commons-HttpClient/3.1[\r][\n]
    DefaultHttpClient httpClient = new DefaultHttpClient();
    URI nexusBaseURI = new URI(url);
    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost =
        new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(), nexusBaseURI.getScheme());
    httpClient
        .getCredentialsProvider()
        .setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet getMethod = new HttpGet(url);
    getMethod.addHeader(userAgentHeader);
    try {
      Assert.assertEquals(
          httpClient.execute(getMethod, localcontext).getStatusLine().getStatusCode(), 200);
    } finally {
      getMethod.reset();
    }

    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    Assert.assertNotNull("Session Cookie not set", sessionCookie);

    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    // now with just the cookie
    httpClient.getCookieStore().addCookie(sessionCookie);
    getMethod = new HttpGet(url);
    try {
      Assert.assertEquals(httpClient.execute(getMethod).getStatusLine().getStatusCode(), 200);
    } finally {
      getMethod.reset();
    }

    // do logout
    HttpGet logoutGetMethod = new HttpGet(logoutUrl);
    try {
      final HttpResponse response = httpClient.execute(logoutGetMethod);
      Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
      Assert.assertEquals("OK", EntityUtils.toString(response.getEntity()));
    } finally {
      logoutGetMethod.reset();
    }

    // set cookie again
    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    httpClient.getCookieStore().addCookie(sessionCookie);
    HttpGet failedGetMethod = new HttpGet(url);
    try {
      final HttpResponse response = httpClient.execute(failedGetMethod);
      Assert.assertEquals(response.getStatusLine().getStatusCode(), 401);
    } finally {
      failedGetMethod.reset();
    }
  }