AuthenticatedURL { public static void extractToken(HttpURLConnection conn, Token token) throws IOException, AuthenticationException { int respCode = conn.getResponseCode(); if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_CREATED || respCode == HttpURLConnection.HTTP_ACCEPTED) { Map<String, List<String>> headers = conn.getHeaderFields(); List<String> cookies = headers.get("Set-Cookie"); if (cookies != null) { for (String cookie : cookies) { if (cookie.startsWith(AUTH_COOKIE_EQ)) { String value = cookie.substring(AUTH_COOKIE_EQ.length()); int separator = value.indexOf(";"); if (separator > -1) { value = value.substring(0, separator); } if (value.length() > 0) { token.set(value); } } } } } else { token.set(null); throw new AuthenticationException("Authentication failed, status: " + conn.getResponseCode() + ", message: " + conn.getResponseMessage()); } } AuthenticatedURL();  AuthenticatedURL(Authenticator authenticator);  AuthenticatedURL(Authenticator authenticator,
                          ConnectionConfigurator connConfigurator); static void setDefaultAuthenticator(Class<? extends Authenticator> authenticator); static Class<? extends Authenticator> getDefaultAuthenticator(); HttpURLConnection openConnection(URL url, Token token); static void injectToken(HttpURLConnection conn, Token token); static void extractToken(HttpURLConnection conn, Token token); static final String AUTH_COOKIE; }
@Test public void testExtractTokenOK() throws Exception { HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); String tokenStr = "foo"; Map<String, List<String>> headers = new HashMap<String, List<String>>(); List<String> cookies = new ArrayList<String>(); cookies.add(AuthenticatedURL.AUTH_COOKIE + "=" + tokenStr); headers.put("Set-Cookie", cookies); Mockito.when(conn.getHeaderFields()).thenReturn(headers); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL.extractToken(conn, token); Assert.assertEquals(tokenStr, token.toString()); }
@Test public void testExtractTokenFail() throws Exception { HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_UNAUTHORIZED); String tokenStr = "foo"; Map<String, List<String>> headers = new HashMap<String, List<String>>(); List<String> cookies = new ArrayList<String>(); cookies.add(AuthenticatedURL.AUTH_COOKIE + "=" + tokenStr); headers.put("Set-Cookie", cookies); Mockito.when(conn.getHeaderFields()).thenReturn(headers); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); token.set("bar"); try { AuthenticatedURL.extractToken(conn, token); Assert.fail(); } catch (AuthenticationException ex) { Assert.assertFalse(token.isSet()); } catch (Exception ex) { Assert.fail(); } }