@Override
  public Optional<RegistryAuthenticator> handleHttpResponseException(
      ResponseException responseException) throws ResponseException, RegistryErrorException {
    // Only valid for status code of '401 Unauthorized'.
    if (responseException.getStatusCode() != HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) {
      throw responseException;
    }

    // Checks if the 'WWW-Authenticate' header is present.
    String authenticationMethod = responseException.getHeaders().getAuthenticate();
    if (authenticationMethod == null) {
      throw new RegistryErrorExceptionBuilder(getActionDescription(), responseException)
          .addReason("'WWW-Authenticate' header not found")
          .build();
    }

    // Parses the header to retrieve the components.
    try {
      return RegistryAuthenticator.fromAuthenticationMethod(
          authenticationMethod, registryEndpointRequestProperties, userAgent, httpClient);

    } catch (RegistryAuthenticationFailedException ex) {
      throw new RegistryErrorExceptionBuilder(getActionDescription(), ex)
          .addReason("Failed get authentication method from 'WWW-Authenticate' header")
          .build();
    }
  }
@Test
  public void testHandleHttpResponseException_pass()
      throws RegistryErrorException, ResponseException, MalformedURLException {
    String authenticationMethod =
        "Bearer realm=\"https://somerealm\",service=\"someservice\",scope=\"somescope\"";

    Mockito.when(mockResponseException.getStatusCode())
        .thenReturn(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
    Mockito.when(mockResponseException.getHeaders()).thenReturn(mockHeaders);
    Mockito.when(mockHeaders.getAuthenticate()).thenReturn(authenticationMethod);

    RegistryAuthenticator registryAuthenticator =
        testAuthenticationMethodRetriever.handleHttpResponseException(mockResponseException).get();

    Assert.assertEquals(
        new URL("https://somerealm?service=someservice&scope=repository:someImageName:someScope"),
        registryAuthenticator.getAuthenticationUrl(
            null, Collections.singletonMap("someImageName", "someScope")));
  }