OAuth2Token { public static OAuth2Token fromJSON(String string) throws IOException { try { Object value = new JSONTokener(string).nextValue(); if (value instanceof JSONObject) { return fromJSON((JSONObject) value); } else { throw new IOException("Invalid JSON data: "+value); } } catch (JSONException e) { Log.w(TAG, "JSON parse error", e); throw new IOException("Error parsing data: "+e.getMessage()); } } OAuth2Token(String accessToken, String tokenType, String refreshToken, int expiresIn, String userName); static OAuth2Token fromJSON(String string); @Override String toString(); @SuppressWarnings("ReplaceAllDot") String getTokenForLogging(); final String accessToken; final String tokenType; final String refreshToken; final int expiresIn; final String userName; }
@Test public void testFromJSON() throws Exception { final String response = "{\n" + " \"access_token\":\"1/fFAGRNJru1FTz70BzhT3Zg\",\n" + " \"expires_in\":3920,\n" + " \"token_type\":\"Bearer\",\n" + " \"refresh_token\":\"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI\"\n" + "}"; final OAuth2Token token = OAuth2Token.fromJSON(response); assertThat(token.accessToken).isEqualTo("1/fFAGRNJru1FTz70BzhT3Zg"); assertThat(token.tokenType).isEqualTo("Bearer"); assertThat(token.refreshToken).isEqualTo("1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"); assertThat(token.expiresIn).isEqualTo(3920); }
@Test public void testFromJSONWithMissingFields() throws Exception { final String response = "{\n" + " \"access_token\":\"1/fFAGRNJru1FTz70BzhT3Zg\"\n" + "}"; final OAuth2Token token = OAuth2Token.fromJSON(response); assertThat(token.accessToken).isEqualTo("1/fFAGRNJru1FTz70BzhT3Zg"); assertThat(token.tokenType).isNull(); assertThat(token.refreshToken).isNull(); assertThat(token.expiresIn).isEqualTo(-1); }
@Test public void testFromJSONWithoutRefreshToken() throws Exception { final String response = "{\n" + " \"access_token\":\"1/fFAGRNJru1FTz70BzhT3Zg\",\n" + " \"expires_in\":3920,\n" + " \"token_type\":\"Bearer\"\n" + "}"; final OAuth2Token token = OAuth2Token.fromJSON(response); assertThat(token.accessToken).isEqualTo("1/fFAGRNJru1FTz70BzhT3Zg"); assertThat(token.tokenType).isEqualTo("Bearer"); assertThat(token.refreshToken).isNull(); assertThat(token.expiresIn).isEqualTo(3920); }