From 48ea4712d65a50f397d012d50e502d379f84f76e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 20 Jan 2015 14:13:48 -0600 Subject: [PATCH 001/195] Remove pairUri() --- src/main/java/com/toopher/ToopherIframe.java | 42 ------------------- .../java/com/toopher/TestToopherIframe.java | 16 ------- 2 files changed, 58 deletions(-) diff --git a/src/main/java/com/toopher/ToopherIframe.java b/src/main/java/com/toopher/ToopherIframe.java index 4dd4354..fae9233 100644 --- a/src/main/java/com/toopher/ToopherIframe.java +++ b/src/main/java/com/toopher/ToopherIframe.java @@ -108,48 +108,6 @@ public ToopherIframe(String consumerKey, String consumerSecret, String baseUri) this.baseUri = baseUri; } - /** - * Return a URL to retrieve a Toopher Device Pairing iframe for the given user - * - * @param userName - * Unique name that identifies this user. This will be displayed to the user on - * their mobile device when they pair or authenticate - * @param resetEmail (optional) - * Email address that the user has access to. In case the user has lost or cannot - * access their mobile device, Toopher will send a reset email to this address - * @param ttl - * IFrame URL Time-To-Live in seconds. After TTL has expired, the Toopher - * API will no longer allow the iframe to be fetched by the browser - * @return - * URI that can be used to retrieve the Pairing Iframe by the user's browser - */ - public String pairUri(String userName, String resetEmail, long ttl) { - final List params = new ArrayList(4); - params.add(new BasicNameValuePair("v", IFRAME_VERSION)); - params.add(new BasicNameValuePair("username", userName)); - if (resetEmail != null) { - params.add(new BasicNameValuePair("reset_email", resetEmail)); - } - params.add(new BasicNameValuePair("expires", String.valueOf((getDate().getTime() / 1000) + ttl))); - return getOAuthUri(baseUri + "web/pair", params, consumerKey, consumerSecret); - } - - /** - * Return a URL to retrieve a Toopher Device Pairing iframe for the given user - * - * @param userName - * Unique name that identifies this user. This will be displayed to the user on - * their mobile device when they pair or authenticate - * @param resetEmail - * Email address that the user has access to. In case the user has lost or cannot - * access their mobile device, Toopher will send a reset email to this address - * @return - * URI that can be used to retrieve the Pairing iframe by the user's browser - */ - public String pairUri(String userName, String resetEmail) { - return this.pairUri(userName, resetEmail, DEFAULT_TTL); - } - /** * Generate a URL to retrieve a Toopher Authentication iframe for a given user/action * diff --git a/src/test/java/com/toopher/TestToopherIframe.java b/src/test/java/com/toopher/TestToopherIframe.java index fefaf41..0ee0168 100644 --- a/src/test/java/com/toopher/TestToopherIframe.java +++ b/src/test/java/com/toopher/TestToopherIframe.java @@ -33,22 +33,6 @@ public void setUp() { this.iframeApi = new ToopherIframe(TOOPHER_CONSUMER_KEY, TOOPHER_CONSUMER_SECRET, "https://api.toopher.test/v1/"); } - @Test - public void testGetPairUri() { - ToopherIframe.setDateOverride(TEST_DATE); - ToopherIframe.setNonceOverride(OAUTH_NONCE); - Map params = nvp2map(URLEncodedUtils.parse(iframeApi.pairUri("jdoe", "jdoe@example.com", REQUEST_TTL), Charset.forName("UTF-8"))); - assertEquals("UGlgBEUF6UZEhYPxevJeagqy6D4=", params.get("oauth_signature")); - } - - @Test - public void testGetPairUriWithoutResetEmail() { - ToopherIframe.setDateOverride(TEST_DATE); - ToopherIframe.setNonceOverride(OAUTH_NONCE); - Map params = nvp2map(URLEncodedUtils.parse(iframeApi.pairUri("jdoe", null, REQUEST_TTL), Charset.forName("UTF-8"))); - assertEquals("s/jY/wPfXafzpf9xBUkIkdYaXII=", params.get("oauth_signature")); - } - @Test public void testGetAuthUri() { ToopherIframe.setDateOverride(TEST_DATE); From 7ac476eccaca9796507d4dced9df50ffa535e832 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 20 Jan 2015 18:06:45 -0600 Subject: [PATCH 002/195] Refactor authUri() and update tests --- src/main/java/com/toopher/ToopherIframe.java | 120 +++++++++++++----- .../java/com/toopher/TestToopherIframe.java | 46 ++++++- 2 files changed, 128 insertions(+), 38 deletions(-) diff --git a/src/main/java/com/toopher/ToopherIframe.java b/src/main/java/com/toopher/ToopherIframe.java index fae9233..b26bb85 100644 --- a/src/main/java/com/toopher/ToopherIframe.java +++ b/src/main/java/com/toopher/ToopherIframe.java @@ -109,7 +109,7 @@ public ToopherIframe(String consumerKey, String consumerSecret, String baseUri) } /** - * Generate a URL to retrieve a Toopher Authentication iframe for a given user/action + * Generate a URL to retrieve a Toopher Authentication Iframe for a given user/action * * @param userName * Unique name that identifies this user. This will be displayed to the user on @@ -117,48 +117,51 @@ public ToopherIframe(String consumerKey, String consumerSecret, String baseUri) * @param resetEmail * Email address that the user has access to. In case the user has lost or cannot * access their mobile device, Toopher will send a reset email to this address - * @param actionName - * The name of the action to authenticate; will be shown to the user. If blank, - * the Toopher API will default the action to "Log In". - * @param automationAllowed - * Determines whether Toopher's Automated Location-Based Authentication is permitted - * to grant the authentication without prompting the user - * @param challengeRequired - * If set to true, the user must correctly respond to a challenge on their device - * before the response will be sent * @param requestToken * Optional, can be empty. Toopher will include this token in the signed data returned * with the iframe response. - * @param requesterMetadata - * Optional, can be empty. Toopher will include this value in the signed data returned - * with the iframe response - * @param ttl - * IFrame URL Time-To-Live in seconds. After TTL has expired, the Toopher - * API will no longer allow the iframe to be fetched by the browser * @return * URI that can be used to retrieve the Authentication iframe by the user's browser */ - public String authUri(String userName, String resetEmail, String actionName, boolean automationAllowed, boolean challengeRequired, String requestToken, String requesterMetadata, long ttl) { - final List params = new ArrayList(9); - - if (requesterMetadata == null) { - requesterMetadata = "None"; - } + public String getAuthenticationUrl(String userName, String resetEmail, String requestToken) { + Map extras = new HashMap(); + return getAuthenticationUrl(userName, resetEmail, requestToken, "Log In", "None", extras); + } - params.add(new BasicNameValuePair("v", IFRAME_VERSION)); - params.add(new BasicNameValuePair("username", userName)); - params.add(new BasicNameValuePair("action_name", actionName)); - params.add(new BasicNameValuePair("automation_allowed", automationAllowed ? "True" : "False")); - params.add(new BasicNameValuePair("challenge_required", challengeRequired ? "True" : "False")); - params.add(new BasicNameValuePair("reset_email", resetEmail)); - params.add(new BasicNameValuePair("session_token", requestToken)); - params.add(new BasicNameValuePair("requester_metadata", requesterMetadata)); - params.add(new BasicNameValuePair("expires", String.valueOf((getDate().getTime() / 1000) + ttl))); - return getOAuthUri(baseUri + "web/authenticate", params, consumerKey, consumerSecret); + /** + * Generate a URL to retrieve a Toopher Authentication Iframe for a given user/action + * + * @param userName + * Unique name that identifies this user. This will be displayed to the user on + * their mobile device when they pair or authenticate + * @param resetEmail + * Email address that the user has access to. In case the user has lost or cannot + * access their mobile device, Toopher will send a reset email to this address + * @param requestToken + * Optional, can be empty. Toopher will include this token in the signed data returned + * with the iframe response. + * @param extras + * allowInlinePairing: + * Determines whether to return the combined pairing/authentication iframe url + * or the authentication url. + * automationAllowed: + * Determines whether Toopher's Automated Location-Based Authentication is permitted + * to grant the authentication without prompting the user + * challengeRequired: + * If set to true, the user must correctly respond to a challenge on their device + * before the response will be sent + * ttl: + * IFrame URL Time-To-Live in seconds. After TTL has expired, the Toopher + * API will no longer allow the iframe to be fetched by the browser + * @return + * URI that can be used to retrieve the Authentication iframe by the user's browser + */ + public String getAuthenticationUrl(String userName, String resetEmail, String requestToken, Map extras) { + return getAuthenticationUrl(userName, resetEmail, requestToken, "Log In", "None", extras); } /** - * Simplified interface to generate a "Log In" iframe uri, with sensible defaults + * Generate a URL to retrieve a Toopher Authentication Iframe for a given user/action * * @param userName * Unique name that identifies this user. This will be displayed to the user on @@ -169,11 +172,58 @@ public String authUri(String userName, String resetEmail, String actionName, boo * @param requestToken * Optional, can be empty. Toopher will include this token in the signed data returned * with the iframe response. + * @param actionName + * The name of the action to authenticate; will be shown to the user. If blank, + * the Toopher API will default the action to "Log In". + * @param requesterMetadata + * Optional, can be empty. Toopher will include this value in the signed data returned + * with the iframe response + * @param extras + * allowInlinePairing: + * Determines whether to return the combined pairing/authentication iframe url + * or the authentication url. + * automationAllowed: + * Determines whether Toopher's Automated Location-Based Authentication is permitted + * to grant the authentication without prompting the user + * challengeRequired: + * If set to true, the user must correctly respond to a challenge on their device + * before the response will be sent + * ttl: + * IFrame URL Time-To-Live in seconds. After TTL has expired, the Toopher + * API will no longer allow the iframe to be fetched by the browser * @return * URI that can be used to retrieve the Authentication iframe by the user's browser */ - public String loginUri(String userName, String resetEmail, String requestToken) { - return authUri(userName, resetEmail, "Log In", true, false, requestToken, null, DEFAULT_TTL); + public String getAuthenticationUrl(String userName, String resetEmail, String requestToken, String actionName, String requesterMetadata, Map extras) { + final long ttl; + final List params = new ArrayList(10); + + if (!extras.containsKey("allowInlinePairing")) { + extras.put("allowInlinePairing", "true"); + } + if (!extras.containsKey("automationAllowed")) { + extras.put("automationAllowed", "true"); + } + if (!extras.containsKey("challengeRequired")) { + extras.put("challengeRequired", "false"); + } + if (!extras.containsKey("ttl")) { + ttl = DEFAULT_TTL; + } else { + ttl = Long.parseLong(extras.get("ttl")); + } + + params.add(new BasicNameValuePair("v", IFRAME_VERSION)); + params.add(new BasicNameValuePair("username", userName)); + params.add(new BasicNameValuePair("action_name", actionName )); + params.add(new BasicNameValuePair("allow_inline_pairing", Boolean.parseBoolean(extras.get("allowInlinePairing")) ? "True" : "False")); + params.add(new BasicNameValuePair("automation_allowed", Boolean.parseBoolean(extras.get("automationAllowed")) ? "True" : "False" )); + params.add(new BasicNameValuePair("challenge_required", Boolean.parseBoolean(extras.get("challengeRequired")) ? "True" : "False")); + params.add(new BasicNameValuePair("reset_email", resetEmail)); + params.add(new BasicNameValuePair("session_token", requestToken)); + params.add(new BasicNameValuePair("requester_metadata", requesterMetadata)); + params.add(new BasicNameValuePair("expires", String.valueOf((getDate().getTime() / 1000) + ttl))); + return getOAuthUri(baseUri + "web/authenticate", params, consumerKey, consumerSecret); } /** diff --git a/src/test/java/com/toopher/TestToopherIframe.java b/src/test/java/com/toopher/TestToopherIframe.java index 0ee0168..a9496cb 100644 --- a/src/test/java/com/toopher/TestToopherIframe.java +++ b/src/test/java/com/toopher/TestToopherIframe.java @@ -34,13 +34,53 @@ public void setUp() { } @Test - public void testGetAuthUri() { + public void testGetAuthenticationUrl(){ ToopherIframe.setDateOverride(TEST_DATE); ToopherIframe.setNonceOverride(OAUTH_NONCE); - Map params = nvp2map(URLEncodedUtils.parse(iframeApi.authUri("jdoe", "jdoe@example.com", "Log In", true, false, REQUEST_TOKEN, null, REQUEST_TTL), Charset.forName("UTF-8"))); - assertEquals("PykRbVHUP2OTTjGF0GJaS5TTu54=", params.get("oauth_signature")); + String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&allow_inline_pairing=True&automation_allowed=True&challenge_required=False&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1010&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=7bNVy3DANBEHqZsPz%2BNIr%2BcTIg8%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN)); } + @Test + public void testGetAuthenticationUrlWithExtras() { + ToopherIframe.setDateOverride(TEST_DATE); + ToopherIframe.setNonceOverride(OAUTH_NONCE); + String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&allow_inline_pairing=False&automation_allowed=False&challenge_required=True&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1100&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=Fx9VeYokaK%2F62imRhy8m7abP8hg%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + Map extras = new HashMap(); + extras.put("allowInlinePairing", "false"); + extras.put("automationAllowed", "false"); + extras.put("challengeRequired", "true"); + extras.put("ttl", Long.toString(REQUEST_TTL)); + assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN,extras)); + + } + + @Test + public void testGetAuthenticationUrlWithOptionalArgsAndExtras() { + ToopherIframe.setDateOverride(TEST_DATE); + ToopherIframe.setNonceOverride(OAUTH_NONCE); + String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=it+is+a+test&allow_inline_pairing=False&automation_allowed=False&challenge_required=True&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=metadata&expires=1100&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=hKogqI%2FgjKXpYIH%2BjNDhRSi22b4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + Map extras = new HashMap(); + extras.put("allowInlinePairing", "false"); + extras.put("automationAllowed", "false"); + extras.put("challengeRequired", "true"); + extras.put("ttl", Long.toString(REQUEST_TTL)); + assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN, "it is a test", "metadata", extras)); + } + +// @Test +// public void testGetAuthenticationUrlWithOptionalArgsAndExtras() { +// ToopherIframe.setDateOverride(TEST_DATE); +// ToopherIframe.setNonceOverride(OAUTH_NONCE); +// Map extras = new HashMap(); +// extras.put("allowInlinePairing", "false"); +// extras.put("automationAllowed", "false"); +// extras.put("challengeRequired", "true"); +// extras.put("ttl", Long.toString(REQUEST_TTL)); +// Map params = nvp2map(URLEncodedUtils.parse(iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN, "it is a test", "metadata", extras), Charset.forName("UTF-8"))); +// assertEquals("hKogqI/gjKXpYIH+jNDhRSi22b4=", params.get("oauth_signature")); +// } + @Test public void testValidateGoodSignatureIsSuccessful(){ Map data = new HashMap(); From aa7e3475b111f665103d729393fe31190a8f954f Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 21 Jan 2015 17:28:00 -0600 Subject: [PATCH 003/195] Update javadocs comment for allowInlinePairing --- src/main/java/com/toopher/ToopherIframe.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/toopher/ToopherIframe.java b/src/main/java/com/toopher/ToopherIframe.java index b26bb85..8c55ba6 100644 --- a/src/main/java/com/toopher/ToopherIframe.java +++ b/src/main/java/com/toopher/ToopherIframe.java @@ -142,8 +142,8 @@ public String getAuthenticationUrl(String userName, String resetEmail, String re * with the iframe response. * @param extras * allowInlinePairing: - * Determines whether to return the combined pairing/authentication iframe url - * or the authentication url. + * Enables users to pair and authenticate in the same iframe. If set to false, users + * must be paired separately. The default, true, is strongly recommended. * automationAllowed: * Determines whether Toopher's Automated Location-Based Authentication is permitted * to grant the authentication without prompting the user From 1e44fc2b3c521d77400e20f2d904833dd4153639 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 21 Jan 2015 17:41:03 -0600 Subject: [PATCH 004/195] Create getUserManagementUrl() with test --- src/main/java/com/toopher/ToopherIframe.java | 50 +++++++++++++++++++ .../java/com/toopher/TestToopherIframe.java | 18 +++++++ 2 files changed, 68 insertions(+) diff --git a/src/main/java/com/toopher/ToopherIframe.java b/src/main/java/com/toopher/ToopherIframe.java index 8c55ba6..8bcb155 100644 --- a/src/main/java/com/toopher/ToopherIframe.java +++ b/src/main/java/com/toopher/ToopherIframe.java @@ -226,6 +226,56 @@ public String getAuthenticationUrl(String userName, String resetEmail, String re return getOAuthUri(baseUri + "web/authenticate", params, consumerKey, consumerSecret); } + /** + * Generate a URL to retrieve a Toopher Pairing Iframe for a given user + * + * @param userName + * Unique name that identifies this user. This will be displayed to the user on + * their mobile device when they pair or authenticate + * @param resetEmail + * Email address that the user has access to. In case the user has lost or cannot + * access their mobile device, Toopher will send a reset email to this address + * @return + * URL that can be used to retrieve the Pairing iframe by the user's browser + */ + public String getUserManagementUrl(String userName, String resetEmail) { + Map extras = new HashMap(); + return getUserManagementUrl(userName, resetEmail, extras); + } + + /** + * Generate a URL to retrieve a Toopher Pairing Iframe for a given user + * + * @param userName + * Unique name that identifies this user. This will be displayed to the user on + * their mobile device when they pair or authenticate + * @param resetEmail + * Email address that the user has access to. In case the user has lost or cannot + * access their mobile device, Toopher will send a reset email to this address + * @param extras + * ttl: + * IFrame URL Time-To-Live in seconds. After TTL has expired, the Toopher + * API will no longer allow the iframe to be fetched by the browser + * @return + * URL that can be used to retrieve the Pairing iframe by the user's browser + */ + public String getUserManagementUrl(String userName, String resetEmail, Map extras) { + final long ttl; + final List params = new ArrayList(); + + if (!extras.containsKey("ttl")) { + ttl = DEFAULT_TTL; + } else { + ttl = Long.parseLong(extras.get("ttl")); + } + + params.add(new BasicNameValuePair("v", IFRAME_VERSION)); + params.add(new BasicNameValuePair("username", userName)); + params.add(new BasicNameValuePair("reset_email", resetEmail)); + params.add(new BasicNameValuePair("expires", String.valueOf((getDate().getTime() / 1000) + ttl))); + return getOAuthUri(baseUri + "web/manage_user", params, consumerKey, consumerSecret); + } + /** * Verify the authenticity of data returned from the Toopher iframe by validating the cryptographic signature * diff --git a/src/test/java/com/toopher/TestToopherIframe.java b/src/test/java/com/toopher/TestToopherIframe.java index a9496cb..5abcfd4 100644 --- a/src/test/java/com/toopher/TestToopherIframe.java +++ b/src/test/java/com/toopher/TestToopherIframe.java @@ -81,6 +81,24 @@ public void testGetAuthenticationUrlWithOptionalArgsAndExtras() { // assertEquals("hKogqI/gjKXpYIH+jNDhRSi22b4=", params.get("oauth_signature")); // } + @Test + public void testGetUserManagementUrl() { + ToopherIframe.setDateOverride(TEST_DATE); + ToopherIframe.setNonceOverride(OAUTH_NONCE); + String expected = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1010&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=aq1kavm7iBOXNPndjKLnrI5rEXU%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + assertEquals(expected, iframeApi.getUserManagementUrl("jdoe", "jdoe@example.com")); + } + + @Test + public void testGetUserManagementUrlWithExtras() { + ToopherIframe.setDateOverride(TEST_DATE); + ToopherIframe.setNonceOverride(OAUTH_NONCE); + Map extras = new HashMap(); + extras.put("ttl", Long.toString(REQUEST_TTL)); + String expected = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + assertEquals(expected, iframeApi.getUserManagementUrl("jdoe", "jdoe@example.com", extras)); + } + @Test public void testValidateGoodSignatureIsSuccessful(){ Map data = new HashMap(); From e73ee87ce53ed59c7eeee9cb177a24a6738ee7a9 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 10:12:28 -0600 Subject: [PATCH 005/195] Rename uri to url --- src/main/java/com/toopher/ToopherIframe.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/toopher/ToopherIframe.java b/src/main/java/com/toopher/ToopherIframe.java index 8bcb155..dd3f8d5 100644 --- a/src/main/java/com/toopher/ToopherIframe.java +++ b/src/main/java/com/toopher/ToopherIframe.java @@ -121,7 +121,7 @@ public ToopherIframe(String consumerKey, String consumerSecret, String baseUri) * Optional, can be empty. Toopher will include this token in the signed data returned * with the iframe response. * @return - * URI that can be used to retrieve the Authentication iframe by the user's browser + * URL that can be used to retrieve the Authentication iframe by the user's browser */ public String getAuthenticationUrl(String userName, String resetEmail, String requestToken) { Map extras = new HashMap(); @@ -154,7 +154,7 @@ public String getAuthenticationUrl(String userName, String resetEmail, String re * IFrame URL Time-To-Live in seconds. After TTL has expired, the Toopher * API will no longer allow the iframe to be fetched by the browser * @return - * URI that can be used to retrieve the Authentication iframe by the user's browser + * URL that can be used to retrieve the Authentication iframe by the user's browser */ public String getAuthenticationUrl(String userName, String resetEmail, String requestToken, Map extras) { return getAuthenticationUrl(userName, resetEmail, requestToken, "Log In", "None", extras); @@ -192,7 +192,7 @@ public String getAuthenticationUrl(String userName, String resetEmail, String re * IFrame URL Time-To-Live in seconds. After TTL has expired, the Toopher * API will no longer allow the iframe to be fetched by the browser * @return - * URI that can be used to retrieve the Authentication iframe by the user's browser + * URL that can be used to retrieve the Authentication iframe by the user's browser */ public String getAuthenticationUrl(String userName, String resetEmail, String requestToken, String actionName, String requesterMetadata, Map extras) { final long ttl; @@ -223,7 +223,7 @@ public String getAuthenticationUrl(String userName, String resetEmail, String re params.add(new BasicNameValuePair("session_token", requestToken)); params.add(new BasicNameValuePair("requester_metadata", requesterMetadata)); params.add(new BasicNameValuePair("expires", String.valueOf((getDate().getTime() / 1000) + ttl))); - return getOAuthUri(baseUri + "web/authenticate", params, consumerKey, consumerSecret); + return getOAuthUrl(baseUri + "web/authenticate", params, consumerKey, consumerSecret); } /** @@ -273,7 +273,7 @@ public String getUserManagementUrl(String userName, String resetEmail, Map data) throws return org.apache.commons.codec.binary.Base64.encodeBase64String(mac.doFinal(toSign.getBytes())).trim(); } - private static final String getOAuthUri(String uri, List params, String key, String secret) { + private static final String getOAuthUrl(String uri, List params, String key, String secret) { final OAuthConsumer consumer = new DefaultOAuthConsumer(key, secret); HttpParameters additionalParameters = new HttpParameters(); From 095ada04a03457b433b342a9e4e2cb0d093d045f Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 11:37:55 -0600 Subject: [PATCH 006/195] Refactor getAuthenticationUrl() so that it treats extras as a black box --- src/main/java/com/toopher/ToopherIframe.java | 18 ++++++------------ .../java/com/toopher/TestToopherIframe.java | 18 +++++++++--------- 2 files changed, 15 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/toopher/ToopherIframe.java b/src/main/java/com/toopher/ToopherIframe.java index dd3f8d5..0c0768a 100644 --- a/src/main/java/com/toopher/ToopherIframe.java +++ b/src/main/java/com/toopher/ToopherIframe.java @@ -198,31 +198,25 @@ public String getAuthenticationUrl(String userName, String resetEmail, String re final long ttl; final List params = new ArrayList(10); - if (!extras.containsKey("allowInlinePairing")) { - extras.put("allowInlinePairing", "true"); - } - if (!extras.containsKey("automationAllowed")) { - extras.put("automationAllowed", "true"); - } - if (!extras.containsKey("challengeRequired")) { - extras.put("challengeRequired", "false"); - } if (!extras.containsKey("ttl")) { ttl = DEFAULT_TTL; } else { ttl = Long.parseLong(extras.get("ttl")); + extras.remove("ttl"); } params.add(new BasicNameValuePair("v", IFRAME_VERSION)); params.add(new BasicNameValuePair("username", userName)); params.add(new BasicNameValuePair("action_name", actionName )); - params.add(new BasicNameValuePair("allow_inline_pairing", Boolean.parseBoolean(extras.get("allowInlinePairing")) ? "True" : "False")); - params.add(new BasicNameValuePair("automation_allowed", Boolean.parseBoolean(extras.get("automationAllowed")) ? "True" : "False" )); - params.add(new BasicNameValuePair("challenge_required", Boolean.parseBoolean(extras.get("challengeRequired")) ? "True" : "False")); params.add(new BasicNameValuePair("reset_email", resetEmail)); params.add(new BasicNameValuePair("session_token", requestToken)); params.add(new BasicNameValuePair("requester_metadata", requesterMetadata)); params.add(new BasicNameValuePair("expires", String.valueOf((getDate().getTime() / 1000) + ttl))); + + for (Map.Entry entry : extras.entrySet()) { + params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + return getOAuthUrl(baseUri + "web/authenticate", params, consumerKey, consumerSecret); } diff --git a/src/test/java/com/toopher/TestToopherIframe.java b/src/test/java/com/toopher/TestToopherIframe.java index 5abcfd4..5fc3d97 100644 --- a/src/test/java/com/toopher/TestToopherIframe.java +++ b/src/test/java/com/toopher/TestToopherIframe.java @@ -37,7 +37,7 @@ public void setUp() { public void testGetAuthenticationUrl(){ ToopherIframe.setDateOverride(TEST_DATE); ToopherIframe.setNonceOverride(OAUTH_NONCE); - String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&allow_inline_pairing=True&automation_allowed=True&challenge_required=False&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1010&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=7bNVy3DANBEHqZsPz%2BNIr%2BcTIg8%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1010&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=1qBrA0wErtYCrzqQLwYqUDoynXs%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN)); } @@ -45,11 +45,11 @@ public void testGetAuthenticationUrl(){ public void testGetAuthenticationUrlWithExtras() { ToopherIframe.setDateOverride(TEST_DATE); ToopherIframe.setNonceOverride(OAUTH_NONCE); - String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&allow_inline_pairing=False&automation_allowed=False&challenge_required=True&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1100&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=Fx9VeYokaK%2F62imRhy8m7abP8hg%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1100&automation_allowed=false&challenge_required=true&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=TUgywVd77mWpffzdwjjQJ7ooYPM%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; Map extras = new HashMap(); - extras.put("allowInlinePairing", "false"); - extras.put("automationAllowed", "false"); - extras.put("challengeRequired", "true"); + extras.put("allow_inline_pairing", "false"); + extras.put("automation_allowed", "false"); + extras.put("challenge_required", "true"); extras.put("ttl", Long.toString(REQUEST_TTL)); assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN,extras)); @@ -59,11 +59,11 @@ public void testGetAuthenticationUrlWithExtras() { public void testGetAuthenticationUrlWithOptionalArgsAndExtras() { ToopherIframe.setDateOverride(TEST_DATE); ToopherIframe.setNonceOverride(OAUTH_NONCE); - String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=it+is+a+test&allow_inline_pairing=False&automation_allowed=False&challenge_required=True&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=metadata&expires=1100&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=hKogqI%2FgjKXpYIH%2BjNDhRSi22b4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=it+is+a+test&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=metadata&expires=1100&automation_allowed=false&challenge_required=true&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=61dqeQNPFxNy8PyEFB9e5UfgN8s%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; Map extras = new HashMap(); - extras.put("allowInlinePairing", "false"); - extras.put("automationAllowed", "false"); - extras.put("challengeRequired", "true"); + extras.put("allow_inline_pairing", "false"); + extras.put("automation_allowed", "false"); + extras.put("challenge_required", "true"); extras.put("ttl", Long.toString(REQUEST_TTL)); assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN, "it is a test", "metadata", extras)); } From 39502928832b550e8aa255439f9712bed259c079 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 12:19:00 -0600 Subject: [PATCH 007/195] Rename PairingStatus to Pairing --- .../{PairingStatus.java => Pairing.java} | 36 ++++++++++--------- src/main/java/com/toopher/ToopherAPI.java | 26 +++++++------- src/main/java/com/toopher/ToopherAPIDemo.java | 8 ++--- src/test/java/com/toopher/TestToopherAPI.java | 8 ++--- 4 files changed, 40 insertions(+), 38 deletions(-) rename src/main/java/com/toopher/{PairingStatus.java => Pairing.java} (52%) diff --git a/src/main/java/com/toopher/PairingStatus.java b/src/main/java/com/toopher/Pairing.java similarity index 52% rename from src/main/java/com/toopher/PairingStatus.java rename to src/main/java/com/toopher/Pairing.java index 6ee86f8..c3f8713 100644 --- a/src/main/java/com/toopher/PairingStatus.java +++ b/src/main/java/com/toopher/Pairing.java @@ -7,47 +7,49 @@ * Provides information about the status of a pairing request * */ -public class PairingStatus extends ApiResponseObject { +public class Pairing extends ApiResponseObject { /** * The unique id for the pairing request */ public String id; /** - * The unique id for the user associated with the pairing request + * Indicates if the pairing has been enabled by the user */ - public String userId; + public boolean enabled; /** - * The descriptive name for the user associated with the pairing request + * Indicates if the user has reacted to the pairing request */ - public String userName; + public boolean pending; /** - * Indicates if the pairing has been enabled by the user + * Contains the unique id and description name for the user associated + * with the pairing request */ - public boolean enabled; + public User user; /** - * Indicates if the user has reacted to the pairing request + * Contains the raw JSONObject */ - public boolean pending; + public JSONObject raw; + @Override public String toString() { - return String.format("[PairingStatus: id=%s; userId=%s; userName=%s, pending=%b, enabled=%b]", id, - userId, userName, pending, enabled); + return String.format("[Pairing: id=%s; userId=%s, userName=%s, pending=%b, enabled=%b]", id, + user.id, user.name, pending, enabled); } - public PairingStatus (JSONObject json) throws JSONException { + public Pairing(JSONObject json) throws JSONException { super(json); this.id = json.getString("id"); - - JSONObject user = json.getJSONObject("user"); - this.userId = user.getString("id"); - this.userName = user.getString("name"); - this.pending = json.getBoolean("pending"); this.enabled = json.getBoolean("enabled"); + this.pending = json.getBoolean("pending"); + this.user = new User(json.getJSONObject("user")); + this.raw = json; } + + } diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index ae20740..d99cf6a 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -161,11 +161,11 @@ public ToopherAPI(String consumerKey, String consumerSecret, URI uri, HttpClient * The pairing phrase supplied by the user * @param userName * A user-facing descriptive name for the user (displayed in requests) - * @return A PairingStatus object + * @return A Pairing object * @throws RequestError * Thrown when an exceptional condition is encountered */ - public PairingStatus pair(String pairingPhrase, String userName) throws RequestError { + public Pairing pair(String pairingPhrase, String userName) throws RequestError { return this.pair(pairingPhrase, userName, null); } @@ -178,11 +178,11 @@ public PairingStatus pair(String pairingPhrase, String userName) throws RequestE * A user-facing descriptive name for the user (displayed in requests) * @param extras * An optional Map of extra parameters to provide to the API - * @return A PairingStatus object + * @return A Pairing object * @throws RequestError * Thrown when an exceptional condition is encountered */ - public PairingStatus pair(String pairingPhrase, String userName, Map extras) throws RequestError { + public Pairing pair(String pairingPhrase, String userName, Map extras) throws RequestError { final String endpoint = "pairings/create"; List params = new ArrayList(); @@ -191,7 +191,7 @@ public PairingStatus pair(String pairingPhrase, String userName, Map extras) throws RequestError { + public Pairing pairWithQrCode(String userName, Map extras) throws RequestError { final String endpoint = "pairings/create/qr"; List params = new ArrayList(); @@ -249,7 +249,7 @@ public PairingStatus pairWithQrCode(String userName, Map extras) JSONObject json = post(endpoint, params, extras); try { - return new PairingStatus(json); + return new Pairing(json); } catch (Exception e) { throw new RequestError(e); } diff --git a/src/main/java/com/toopher/ToopherAPIDemo.java b/src/main/java/com/toopher/ToopherAPIDemo.java index 87b3c26..7db6058 100644 --- a/src/main/java/com/toopher/ToopherAPIDemo.java +++ b/src/main/java/com/toopher/ToopherAPIDemo.java @@ -71,8 +71,8 @@ public static void main(String[] args) { System.out.println("Sending pairing request..."); try { - PairingStatus pairingStatus = api.pair(pairingPhrase, userName); - pairingId = pairingStatus.id; + Pairing pairing = api.pair(pairingPhrase, userName); + pairingId = pairing.id; break; } catch (RequestError err) { System.out.println(String.format("The pairing phrase was not accepted (reason:%s)", err.getMessage())); @@ -85,8 +85,8 @@ public static void main(String[] args) { System.out.println("Checking status of pairing request..."); try { - PairingStatus pairingStatus = api.getPairingStatus(pairingId); - if (pairingStatus.enabled) { + Pairing pairing = api.getPairingStatus(pairingId); + if (pairing.enabled) { System.out.println("Pairing complete"); System.out.println(); break; diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index f239276..00feeab 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -17,7 +17,7 @@ public void testCreatePairing() throws InterruptedException, RequestError { ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); - PairingStatus pairing = toopherApi.pair("awkward turtle", "some user"); + Pairing pairing = toopherApi.pair("awkward turtle", "some user"); assertEquals(httpClient.getLastCalledMethod(), "POST"); assertEquals(httpClient.getLastCalledData("pairing_phrase"), "awkward turtle"); @@ -29,13 +29,13 @@ public void testCreatePairing() throws InterruptedException, RequestError { } @Test - public void testGetPairingStatus() throws InterruptedException, RequestError { + public void testGetPairing() throws InterruptedException, RequestError { HttpClientMock httpClient = new HttpClientMock(200, "{'id':'1','enabled':true,'pending':true,'user':{'id':'1','name':'some user'}}".replace("'", "\"")); ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); - PairingStatus pairing = toopherApi.getPairingStatus("1"); + Pairing pairing = toopherApi.getPairingStatus("1"); assertEquals(httpClient.getLastCalledMethod(), "GET"); @@ -52,7 +52,7 @@ public void testCreateQrPairing() throws InterruptedException, RequestError { ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); - PairingStatus pairing = toopherApi.pairWithQrCode("some user"); + Pairing pairing = toopherApi.pairWithQrCode("some user"); assertEquals(httpClient.getLastCalledMethod(), "POST"); From 4ec06ebd0d2e2e2c6e1a7244812516e688f9cae8 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 12:25:24 -0600 Subject: [PATCH 008/195] Update javadocs for extras --- src/main/java/com/toopher/ToopherIframe.java | 26 ++------------------ 1 file changed, 2 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/toopher/ToopherIframe.java b/src/main/java/com/toopher/ToopherIframe.java index 0c0768a..2604e64 100644 --- a/src/main/java/com/toopher/ToopherIframe.java +++ b/src/main/java/com/toopher/ToopherIframe.java @@ -141,18 +141,7 @@ public String getAuthenticationUrl(String userName, String resetEmail, String re * Optional, can be empty. Toopher will include this token in the signed data returned * with the iframe response. * @param extras - * allowInlinePairing: - * Enables users to pair and authenticate in the same iframe. If set to false, users - * must be paired separately. The default, true, is strongly recommended. - * automationAllowed: - * Determines whether Toopher's Automated Location-Based Authentication is permitted - * to grant the authentication without prompting the user - * challengeRequired: - * If set to true, the user must correctly respond to a challenge on their device - * before the response will be sent - * ttl: - * IFrame URL Time-To-Live in seconds. After TTL has expired, the Toopher - * API will no longer allow the iframe to be fetched by the browser + * An optional Map of extra parameters to provide to the API * @return * URL that can be used to retrieve the Authentication iframe by the user's browser */ @@ -179,18 +168,7 @@ public String getAuthenticationUrl(String userName, String resetEmail, String re * Optional, can be empty. Toopher will include this value in the signed data returned * with the iframe response * @param extras - * allowInlinePairing: - * Determines whether to return the combined pairing/authentication iframe url - * or the authentication url. - * automationAllowed: - * Determines whether Toopher's Automated Location-Based Authentication is permitted - * to grant the authentication without prompting the user - * challengeRequired: - * If set to true, the user must correctly respond to a challenge on their device - * before the response will be sent - * ttl: - * IFrame URL Time-To-Live in seconds. After TTL has expired, the Toopher - * API will no longer allow the iframe to be fetched by the browser + * An optional Map of extra parameters to provide to the API * @return * URL that can be used to retrieve the Authentication iframe by the user's browser */ From 0b21d0263f33d8f1ff8ffb71fc7bf42ae3f40405 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 12:25:49 -0600 Subject: [PATCH 009/195] Rename validate to validatePostback --- src/main/java/com/toopher/ToopherIframe.java | 4 ++-- src/test/java/com/toopher/TestToopherIframe.java | 16 +++++++--------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/toopher/ToopherIframe.java b/src/main/java/com/toopher/ToopherIframe.java index 2604e64..cd41bc6 100644 --- a/src/main/java/com/toopher/ToopherIframe.java +++ b/src/main/java/com/toopher/ToopherIframe.java @@ -259,7 +259,7 @@ public String getUserManagementUrl(String userName, String resetEmail, Map validate(Map params, String sessionToken, long ttl) throws SignatureValidationError { + public Map validatePostback(Map params, String sessionToken, long ttl) throws SignatureValidationError { Map data = flattenParams(params); try { @@ -329,7 +329,7 @@ public Map validate(Map params, String session * A map of the validated data if the signature is valid, or null if the signature is invalid */ public Map validate(Map params, String sessionToken) throws SignatureValidationError { - return validate(params, sessionToken, DEFAULT_TTL); + return validatePostback(params, sessionToken, DEFAULT_TTL); } private static Map flattenParams(Map params) { diff --git a/src/test/java/com/toopher/TestToopherIframe.java b/src/test/java/com/toopher/TestToopherIframe.java index 5fc3d97..1f1950d 100644 --- a/src/test/java/com/toopher/TestToopherIframe.java +++ b/src/test/java/com/toopher/TestToopherIframe.java @@ -110,7 +110,7 @@ public void testValidateGoodSignatureIsSuccessful(){ ToopherIframe.setDateOverride(TEST_DATE); try { - assertNotNull(iframeApi.validate(data, REQUEST_TOKEN, 5)); + assertNotNull(iframeApi.validatePostback(data, REQUEST_TOKEN, 5)); } catch (ToopherIframe.SignatureValidationError e) { fail(); } @@ -126,7 +126,7 @@ public void testValidateBadSignatureFails(){ ToopherIframe.setDateOverride(TEST_DATE); try { - iframeApi.validate(data, REQUEST_TOKEN, 5); + iframeApi.validatePostback(data, REQUEST_TOKEN, 5); fail(); } catch (ToopherIframe.SignatureValidationError e) { assertTrue(e.getMessage().contains("Computed signature does not match")); @@ -145,7 +145,7 @@ public void testValidateExpiredSignatureFails() { ToopherIframe.setDateOverride(new Date(TEST_DATE.getTime() + (1000 * 6))); try { - iframeApi.validate(data, REQUEST_TOKEN, 5); + iframeApi.validatePostback(data, REQUEST_TOKEN, 5); fail(); } catch (ToopherIframe.SignatureValidationError e) { assertTrue(e.getMessage().contains("TTL Expired")); @@ -162,7 +162,7 @@ public void testValidateMissingTimestampFails() { ToopherIframe.setDateOverride(TEST_DATE); try { - iframeApi.validate(data, REQUEST_TOKEN, 5); + iframeApi.validatePostback(data, REQUEST_TOKEN, 5); fail(); } catch (ToopherIframe.SignatureValidationError e) { assertTrue(e.getMessage().contains("Missing required keys: timestamp")); @@ -178,7 +178,7 @@ public void testValidateMissingSignatureFails() { ToopherIframe.setDateOverride(TEST_DATE); try { - iframeApi.validate(data, REQUEST_TOKEN, 5); + iframeApi.validatePostback(data, REQUEST_TOKEN, 5); fail(); } catch (ToopherIframe.SignatureValidationError e) { assertTrue(e.getMessage().contains("Missing required keys: toopher_sig")); @@ -195,7 +195,7 @@ public void testInvalidSessionTokenFails() { ToopherIframe.setDateOverride(TEST_DATE); try { - iframeApi.validate(data, REQUEST_TOKEN, 5); + iframeApi.validatePostback(data, REQUEST_TOKEN, 5); fail(); } catch (ToopherIframe.SignatureValidationError e) { assertTrue(e.getMessage().contains("Session token does not match expected value")); @@ -211,12 +211,10 @@ public void testMissingSessionTokenFails() { ToopherIframe.setDateOverride(TEST_DATE); try { - iframeApi.validate(data, REQUEST_TOKEN, 5); + iframeApi.validatePostback(data, REQUEST_TOKEN, 5); fail(); } catch (ToopherIframe.SignatureValidationError e) { assertTrue(e.getMessage().contains("Missing required keys: session_token")); } } - - } From 9e39d2eaa5455bee68530ff0f0a76604680a0237 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 12:26:30 -0600 Subject: [PATCH 010/195] Create User class and update Pairing and tests --- src/main/java/com/toopher/User.java | 40 +++++++++++++++++++ src/test/java/com/toopher/TestToopherAPI.java | 13 +++--- 2 files changed, 46 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/toopher/User.java diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java new file mode 100644 index 0000000..31598bd --- /dev/null +++ b/src/main/java/com/toopher/User.java @@ -0,0 +1,40 @@ +package com.toopher; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Created by graceyim on 1/22/15. + */ +public class User extends ApiResponseObject { + /** + * The unique id for the user + */ + public String id; + + /** + * The name of the user + */ + public String name; + + /** + * + */ + public boolean enabled; + + /** + * Contains the raw JSONObject + */ + public JSONObject raw; + + public User (JSONObject json) throws JSONException { + super(json); + + this.id = json.getString("id"); + this.name = json.getString("name"); + if (json.has("disable_toopher_auth")) { + this.enabled = (json.getBoolean("disable_toopher_auth") ? false : true); + } + this.raw = json; + } +} diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 00feeab..1e78f3e 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -22,8 +22,8 @@ public void testCreatePairing() throws InterruptedException, RequestError { assertEquals(httpClient.getLastCalledMethod(), "POST"); assertEquals(httpClient.getLastCalledData("pairing_phrase"), "awkward turtle"); - assertEquals(pairing.userId, "1"); - assertEquals(pairing.userName, "some user"); + assertEquals(pairing.user.id, "1"); + assertEquals(pairing.user.name, "some user"); assertTrue(pairing.pending); assertTrue(pairing.enabled); } @@ -39,8 +39,8 @@ public void testGetPairing() throws InterruptedException, RequestError { assertEquals(httpClient.getLastCalledMethod(), "GET"); - assertEquals(pairing.userId, "1"); - assertEquals(pairing.userName, "some user"); + assertEquals(pairing.user.id, "1"); + assertEquals(pairing.user.name, "some user"); assertTrue(pairing.pending); assertTrue(pairing.enabled); } @@ -55,9 +55,8 @@ public void testCreateQrPairing() throws InterruptedException, RequestError { Pairing pairing = toopherApi.pairWithQrCode("some user"); assertEquals(httpClient.getLastCalledMethod(), "POST"); - - assertEquals(pairing.userId, "1"); - assertEquals(pairing.userName, "some user"); + assertEquals(pairing.user.id, "1"); + assertEquals(pairing.user.name, "some user"); assertTrue(pairing.pending); assertTrue(pairing.enabled); } From aa92de3de419e7cec117ed802caebb84a81f05da Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 12:40:13 -0600 Subject: [PATCH 011/195] Add comment for old test --- src/test/java/com/toopher/TestToopherIframe.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/com/toopher/TestToopherIframe.java b/src/test/java/com/toopher/TestToopherIframe.java index 1f1950d..ab244e9 100644 --- a/src/test/java/com/toopher/TestToopherIframe.java +++ b/src/test/java/com/toopher/TestToopherIframe.java @@ -68,6 +68,7 @@ public void testGetAuthenticationUrlWithOptionalArgsAndExtras() { assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN, "it is a test", "metadata", extras)); } +// Do we prefer this type of test or the one above? // @Test // public void testGetAuthenticationUrlWithOptionalArgsAndExtras() { // ToopherIframe.setDateOverride(TEST_DATE); From c8f0375bcaeeb21dca316fc69e77d3884437cdbb Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 13:21:07 -0600 Subject: [PATCH 012/195] Rename getPairingStatus to getPairing --- src/main/java/com/toopher/ToopherAPIDemo.java | 2 +- src/test/java/com/toopher/TestToopherAPI.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPIDemo.java b/src/main/java/com/toopher/ToopherAPIDemo.java index 7db6058..2ba5c01 100644 --- a/src/main/java/com/toopher/ToopherAPIDemo.java +++ b/src/main/java/com/toopher/ToopherAPIDemo.java @@ -85,7 +85,7 @@ public static void main(String[] args) { System.out.println("Checking status of pairing request..."); try { - Pairing pairing = api.getPairingStatus(pairingId); + Pairing pairing = api.getPairing(pairingId); if (pairing.enabled) { System.out.println("Pairing complete"); System.out.println(); diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 1e78f3e..a2c31d5 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -35,7 +35,7 @@ public void testGetPairing() throws InterruptedException, RequestError { ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); - Pairing pairing = toopherApi.getPairingStatus("1"); + Pairing pairing = toopherApi.getPairing(id); assertEquals(httpClient.getLastCalledMethod(), "GET"); From 09a68447151791bd0e2690f37a952fbb097d0008 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 13:22:33 -0600 Subject: [PATCH 013/195] Use JSONObject for HttpClientMock --- src/test/java/com/toopher/TestToopherAPI.java | 58 ++++++++++++++----- 1 file changed, 45 insertions(+), 13 deletions(-) diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index a2c31d5..b81ce0e 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -1,19 +1,42 @@ package com.toopher; +import org.json.JSONObject; +import org.junit.Before; import org.junit.Test; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.util.UUID; import static org.junit.Assert.*; public class TestToopherAPI { + private ToopherAPI toopherApi; + private String id; + private JSONObject user; + private String userId; + private String userName; + + @Before + public void setUp() { + this.id = UUID.randomUUID().toString(); + this.user = new JSONObject(); + this.user.put("id", UUID.randomUUID().toString()); + this.user.put("name", "user_name"); + this.userId = this.user.getString("id"); + this.userName = this.user.getString("name"); + } + @Test public void testCreatePairing() throws InterruptedException, RequestError { - HttpClientMock httpClient = new HttpClientMock(200, - "{'id':'1','enabled':true,'pending':true,'user':{'id':'1','name':'some user'}}".replace("'", "\"")); + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("enabled", true); + jsonResponse.put("pending", true); + jsonResponse.put("user", user); + HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); @@ -22,16 +45,20 @@ public void testCreatePairing() throws InterruptedException, RequestError { assertEquals(httpClient.getLastCalledMethod(), "POST"); assertEquals(httpClient.getLastCalledData("pairing_phrase"), "awkward turtle"); - assertEquals(pairing.user.id, "1"); - assertEquals(pairing.user.name, "some user"); + assertEquals(pairing.user.id, userId); + assertEquals(pairing.user.name, userName); assertTrue(pairing.pending); assertTrue(pairing.enabled); } @Test public void testGetPairing() throws InterruptedException, RequestError { - HttpClientMock httpClient = new HttpClientMock(200, - "{'id':'1','enabled':true,'pending':true,'user':{'id':'1','name':'some user'}}".replace("'", "\"")); + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("enabled", true); + jsonResponse.put("pending", true); + jsonResponse.put("user", user); + HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); @@ -39,24 +66,29 @@ public void testGetPairing() throws InterruptedException, RequestError { assertEquals(httpClient.getLastCalledMethod(), "GET"); - assertEquals(pairing.user.id, "1"); - assertEquals(pairing.user.name, "some user"); + assertEquals(pairing.user.id, userId); + assertEquals(pairing.user.name, userName); assertTrue(pairing.pending); assertTrue(pairing.enabled); } @Test public void testCreateQrPairing() throws InterruptedException, RequestError { - HttpClientMock httpClient = new HttpClientMock(200, - "{'id':'1','enabled':true,'pending':true,'user':{'id':'1','name':'some user'}}".replace("'", "\"")); + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("enabled", true); + jsonResponse.put("pending", true); + jsonResponse.put("user", user); + + HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); - Pairing pairing = toopherApi.pairWithQrCode("some user"); + Pairing pairing = toopherApi.pairWithQrCode(userName); assertEquals(httpClient.getLastCalledMethod(), "POST"); - assertEquals(pairing.user.id, "1"); - assertEquals(pairing.user.name, "some user"); + assertEquals(pairing.user.id, userId); + assertEquals(pairing.user.name, userName); assertTrue(pairing.pending); assertTrue(pairing.enabled); } From 3cdf869cf58ba7c2cf5b00cf59b58c96deb6528e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 14:52:49 -0600 Subject: [PATCH 014/195] Replace ToopherAPI.getPairing() with ToopherAPI.advanced.pairings.getById() --- src/main/java/com/toopher/ToopherAPI.java | 54 ++++++++++++------- src/main/java/com/toopher/ToopherAPIDemo.java | 2 +- src/test/java/com/toopher/TestToopherAPI.java | 16 +++--- 3 files changed, 43 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index d99cf6a..339ef65 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -49,6 +49,7 @@ public class ToopherAPI { private final String uriHost; private final int uriPort; private final String uriBase; + public final AdvancedApiUsageFactory advanced; /** * The ToopherJava binding library version @@ -131,6 +132,7 @@ public ToopherAPI(String consumerKey, String consumerSecret, URI uri) { * The alternate HTTP client */ public ToopherAPI(String consumerKey, String consumerSecret, URI uri, HttpClient httpClient) { + this.advanced = new AdvancedApiUsageFactory(consumerKey, consumerSecret); if (httpClient == null) { this.httpClient = new DefaultHttpClient(); HttpProtocolParams.setUserAgent(this.httpClient.getParams(), @@ -197,26 +199,6 @@ public Pairing pair(String pairingPhrase, String userName, Map e } } - /** - * Retrieve the current status of a pairing request - * - * @param pairingRequestId - * The unique id for a pairing request - * @return A Pairing object - * @throws RequestError - * Thrown when an exceptional condition is encountered - */ - public Pairing getPairing(String pairingRequestId) throws RequestError { - final String endpoint = String.format("pairings/%s", pairingRequestId); - - JSONObject json = get(endpoint); - try { - return new Pairing(json); - } catch (Exception e) { - throw new RequestError(e); - } - } - /** * Create a pairing that is presented as a QR code * @@ -579,4 +561,36 @@ private static void parseRequestError(StatusLine statusLine, HttpResponse respon statusLine.getReasonPhrase())); } } + + class AdvancedApiUsageFactory { + public final Pairings pairings; + + public AdvancedApiUsageFactory(String consumerKey, String consumerSecret) { + pairings = new Pairings(); + } + + class Pairings { + + /** + * Retrieve the current status of a pairing + * + * @param pairingId + * The unique id for a pairing + * @return + * A Pairing object + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ + public Pairing getById(String pairingId) throws RequestError { + final String endpoint = String.format("pairings/%s", pairingId); + + JSONObject json = get(endpoint); + try { + return new Pairing(json); + } catch (Exception e) { + throw new RequestError(e); + } + } + } + } } diff --git a/src/main/java/com/toopher/ToopherAPIDemo.java b/src/main/java/com/toopher/ToopherAPIDemo.java index 2ba5c01..06b263a 100644 --- a/src/main/java/com/toopher/ToopherAPIDemo.java +++ b/src/main/java/com/toopher/ToopherAPIDemo.java @@ -85,7 +85,7 @@ public static void main(String[] args) { System.out.println("Checking status of pairing request..."); try { - Pairing pairing = api.getPairing(pairingId); + Pairing pairing = api.advanced.pairings.getById(pairingId); if (pairing.enabled) { System.out.println("Pairing complete"); System.out.println(); diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index b81ce0e..c6bb888 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -52,20 +52,20 @@ public void testCreatePairing() throws InterruptedException, RequestError { } @Test - public void testGetPairing() throws InterruptedException, RequestError { + public void testCreateQrPairing() throws InterruptedException, RequestError { JSONObject jsonResponse = new JSONObject(); jsonResponse.put("id", id); jsonResponse.put("enabled", true); jsonResponse.put("pending", true); jsonResponse.put("user", user); + HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); - Pairing pairing = toopherApi.getPairing(id); - - assertEquals(httpClient.getLastCalledMethod(), "GET"); + Pairing pairing = toopherApi.pairWithQrCode(userName); + assertEquals(httpClient.getLastCalledMethod(), "POST"); assertEquals(pairing.user.id, userId); assertEquals(pairing.user.name, userName); assertTrue(pairing.pending); @@ -73,7 +73,7 @@ public void testGetPairing() throws InterruptedException, RequestError { } @Test - public void testCreateQrPairing() throws InterruptedException, RequestError { + public void testAdvancedPairingsGetById() throws InterruptedException, RequestError { JSONObject jsonResponse = new JSONObject(); jsonResponse.put("id", id); jsonResponse.put("enabled", true); @@ -82,11 +82,11 @@ public void testCreateQrPairing() throws InterruptedException, RequestError { HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); - ToopherAPI toopherApi = new ToopherAPI("key", "secret", + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); - Pairing pairing = toopherApi.pairWithQrCode(userName); + Pairing pairing = toopherAPI.advanced.pairings.getById(id); - assertEquals(httpClient.getLastCalledMethod(), "POST"); + assertEquals(httpClient.getLastCalledMethod(), "GET"); assertEquals(pairing.user.id, userId); assertEquals(pairing.user.name, userName); assertTrue(pairing.pending); From 550e518027d787bb2ace56f8d7b5d61291719090 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 14:54:46 -0600 Subject: [PATCH 015/195] Correct javadocs for setToopherEnabledForUser() --- src/main/java/com/toopher/ToopherAPI.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 339ef65..6f02c8e 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -394,7 +394,7 @@ public void assignUserFriendlyNameToTerminal(String userName, String terminalNam * * @param userName * The name of the user - * @param enabled + * @param toopherEnabled * Whether or not the user is Toopher-enabled * @throws RequestError * Thrown when an exceptional condition is encountered, or the From 5537363128a7d859ef37dc442c2391c18cc6196e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 15:28:20 -0600 Subject: [PATCH 016/195] Rename AuthenticationStatus to AuthenticationRequest --- ...Status.java => AuthenticationRequest.java} | 25 ++++++----------- src/main/java/com/toopher/ToopherAPI.java | 28 +++++++++---------- src/main/java/com/toopher/ToopherAPIDemo.java | 4 +-- 3 files changed, 24 insertions(+), 33 deletions(-) rename src/main/java/com/toopher/{AuthenticationStatus.java => AuthenticationRequest.java} (59%) diff --git a/src/main/java/com/toopher/AuthenticationStatus.java b/src/main/java/com/toopher/AuthenticationRequest.java similarity index 59% rename from src/main/java/com/toopher/AuthenticationStatus.java rename to src/main/java/com/toopher/AuthenticationRequest.java index 311c2d0..0c022e8 100644 --- a/src/main/java/com/toopher/AuthenticationStatus.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -8,7 +8,7 @@ * Provide information about the status of an authentication request * */ -public class AuthenticationStatus extends ApiResponseObject { +public class AuthenticationRequest extends ApiResponseObject { /** * The unique id for the authentication request @@ -36,17 +36,12 @@ public class AuthenticationStatus extends ApiResponseObject { public String reason; /** - * The unique id for the terminal associated with the request + * Contains the unique id and descriptive name for the terminal + * associated with the request */ - public String terminalId; + public UserTerminal terminal; - /** - * The descriptive name for the terminal associated with the request - */ - public String terminalName; - - - public AuthenticationStatus(JSONObject json) throws JSONException{ + public AuthenticationRequest(JSONObject json) throws JSONException{ super(json); this.id = json.getString("id"); @@ -54,17 +49,13 @@ public AuthenticationStatus(JSONObject json) throws JSONException{ this.granted = json.getBoolean("granted"); this.automated = json.getBoolean("automated"); this.reason = json.getString("reason"); - - JSONObject terminal = json.getJSONObject("terminal"); - this.terminalId = terminal.getString("id"); - this.terminalName = terminal.getString("name"); - + this.terminal = new UserTerminal(json.getJSONObject("terminal")); } @Override public String toString() { - return String.format("[AuthenticationStatus: id=%s; pending=%b; granted=%b; automated=%b; reason=%s; terminalId=%s; terminalName=%s]", - id, pending, granted, automated, reason, terminalId, terminalName); + return String.format("[AuthenticationRequest: id=%s; pending=%b; granted=%b; automated=%b; reason=%s; terminalId=%s; terminalName=%s]", + id, pending, granted, automated, reason, terminal.id, terminal.name); } } diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 6f02c8e..0f18451 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -244,11 +244,11 @@ public Pairing pairWithQrCode(String userName, Map extras) throw * The pairing id indicating to whom the request should be sent * @param terminalName * The user-facing descriptive name for the terminal from which the request originates - * @return An AuthenticationStatus object + * @return An AuthenticationRequest object * @throws RequestError * Thrown when an exceptional condition is encountered */ - public AuthenticationStatus authenticate(String pairingId, String terminalName) throws RequestError { + public AuthenticationRequest authenticate(String pairingId, String terminalName) throws RequestError { return authenticate(pairingId, terminalName, null, null); } @@ -261,11 +261,11 @@ public AuthenticationStatus authenticate(String pairingId, String terminalName) * The user-facing descriptive name for the terminal from which the request originates * @param actionName * The user-facing descriptive name for the action which is being authenticated - * @return An AuthenticationStatus object + * @return An AuthenticationRequest object * @throws RequestError * Thrown when an exceptional condition is encountered */ - public AuthenticationStatus authenticate(String pairingId, String terminalName, String actionName) throws RequestError { + public AuthenticationRequest authenticate(String pairingId, String terminalName, String actionName) throws RequestError { return authenticate(pairingId, terminalName, actionName, null); } @@ -280,11 +280,11 @@ public AuthenticationStatus authenticate(String pairingId, String terminalName, * The user-facing descriptive name for the action which is being authenticated * @param extras * An optional Map of extra parameters to provide to the API - * @return An AuthenticationStatus object + * @return An AuthenticationRequest object * @throws RequestError * Thrown when an exceptional condition is encountered */ - public AuthenticationStatus authenticate(String pairingId, String terminalName, + public AuthenticationRequest authenticate(String pairingId, String terminalName, String actionName, Map extras) throws RequestError { final String endpoint = "authentication_requests/initiate"; @@ -301,7 +301,7 @@ public AuthenticationStatus authenticate(String pairingId, String terminalName, JSONObject json = post(endpoint, params, extras); try { - return new AuthenticationStatus(json); + return new AuthenticationRequest(json); } catch (Exception e) { throw new RequestError(e); } @@ -316,11 +316,11 @@ public AuthenticationStatus authenticate(String pairingId, String terminalName, * Unique identifier for this terminal. Not displayed to the user. * @param actionName * The user-facing descriptive name for the action which is being authenticated - * @return An AuthenticationStatus object + * @return An AuthenticationRequest object * @throws RequestError * Thrown when an exceptional condition is encountered */ - public AuthenticationStatus authenticateByUserName(String userName, String terminalNameExtra, String actionName, Map extras) throws RequestError { + public AuthenticationRequest authenticateByUserName(String userName, String terminalNameExtra, String actionName, Map extras) throws RequestError { if (extras == null) { extras = new HashMap(); } @@ -335,29 +335,29 @@ public AuthenticationStatus authenticateByUserName(String userName, String termi * * @param authenticationRequestId * The authentication request ID - * @return An AuthenticationStatus object + * @return An AuthenticationRequest object * @throws RequestError * Thrown when an exceptional condition is encountered */ - public AuthenticationStatus getAuthenticationStatus(String authenticationRequestId) + public AuthenticationRequest getAuthenticationStatus(String authenticationRequestId) throws RequestError { final String endpoint = String.format("authentication_requests/%s", authenticationRequestId); JSONObject json = get(endpoint); try { - return new AuthenticationStatus(json); + return new AuthenticationRequest(json); } catch (Exception e) { throw new RequestError(e); } } - public AuthenticationStatus getAuthenticationStatusWithOTP(String authenticationRequestId,String OTP) throws RequestError { + public AuthenticationRequest getAuthenticationStatusWithOTP(String authenticationRequestId,String OTP) throws RequestError { final String endpoint = String.format("authentication_requests/%s/otp_auth", authenticationRequestId); List params = new ArrayList(); params.add(new BasicNameValuePair("otp", OTP)); JSONObject json = post(endpoint, params, null); try { - return new AuthenticationStatus(json); + return new AuthenticationRequest(json); } catch (Exception e) { throw new RequestError(e); } diff --git a/src/main/java/com/toopher/ToopherAPIDemo.java b/src/main/java/com/toopher/ToopherAPIDemo.java index 06b263a..e0bca7b 100644 --- a/src/main/java/com/toopher/ToopherAPIDemo.java +++ b/src/main/java/com/toopher/ToopherAPIDemo.java @@ -111,7 +111,7 @@ public static void main(String[] args) { String requestId; try { - AuthenticationStatus requestStatus = api.authenticate(pairingId, terminalName); + AuthenticationRequest requestStatus = api.authenticate(pairingId, terminalName); requestId = requestStatus.id; } catch (RequestError err) { System.out.println(String.format("Error initiating authentication (reason:%s)", err.getMessage())); @@ -123,7 +123,7 @@ public static void main(String[] args) { in.nextLine(); System.out.println("Checking status of authentication request..."); - AuthenticationStatus requestStatus; + AuthenticationRequest requestStatus; try { requestStatus = api.getAuthenticationStatus(requestId); } catch (RequestError err) { From c62a8ef583ee0007dc7934ae965809c78c3158f4 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 15:31:11 -0600 Subject: [PATCH 017/195] Create UserTerminal class --- src/main/java/com/toopher/UserTerminal.java | 27 +++++++++++++++++++ src/test/java/com/toopher/TestToopherAPI.java | 9 +++++++ 2 files changed, 36 insertions(+) create mode 100644 src/main/java/com/toopher/UserTerminal.java diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java new file mode 100644 index 0000000..c2bc2bb --- /dev/null +++ b/src/main/java/com/toopher/UserTerminal.java @@ -0,0 +1,27 @@ +package com.toopher; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Created by graceyim on 1/22/15. + */ +public class UserTerminal extends ApiResponseObject { + public String id; + public String name; + public String requesterSpecifiedId; + public User user; + public JSONObject raw; + + public UserTerminal (JSONObject json) throws JSONException { + super(json); + + this.id = json.getString("id"); + this.name = json.getString("name"); + if (json.has("name_extra")) { + this.requesterSpecifiedId = json.getString("name_extra"); + } + this.user = new User(json.getJSONObject("user")); + this.raw = json; + } +} diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index c6bb888..3d7f64e 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -18,6 +18,9 @@ public class TestToopherAPI { private JSONObject user; private String userId; private String userName; + private JSONObject terminal; + private String terminalId; + private String terminalName; @Before public void setUp() { @@ -27,6 +30,12 @@ public void setUp() { this.user.put("name", "user_name"); this.userId = this.user.getString("id"); this.userName = this.user.getString("name"); + this.terminal = new JSONObject(); + this.terminal.put("id", UUID.randomUUID().toString()); + this.terminal.put("name", "terminalName"); + this.terminal.put("user", this.user); + this.terminalId = this.terminal.getString("id"); + this.terminalName = this.terminal.getString("name"); } @Test From f03db07570ff2797f030a0d773abe3040662105e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 15:59:14 -0600 Subject: [PATCH 018/195] Add variables to setUp() and DEFAULT_BASE_URL for tests --- src/test/java/com/toopher/TestToopherAPI.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 3d7f64e..332c2b3 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -13,11 +13,15 @@ import static org.junit.Assert.*; public class TestToopherAPI { + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; + private ToopherAPI toopherApi; private String id; + private String name; private JSONObject user; private String userId; private String userName; + private String reason; private JSONObject terminal; private String terminalId; private String terminalName; @@ -25,11 +29,13 @@ public class TestToopherAPI { @Before public void setUp() { this.id = UUID.randomUUID().toString(); + this.name = "name"; this.user = new JSONObject(); this.user.put("id", UUID.randomUUID().toString()); - this.user.put("name", "user_name"); + this.user.put("name", "userName"); this.userId = this.user.getString("id"); this.userName = this.user.getString("name"); + this.reason = "it is a test"; this.terminal = new JSONObject(); this.terminal.put("id", UUID.randomUUID().toString()); this.terminal.put("name", "terminalName"); From 60bc22bbbfeca6a6b015bb1e14bd2d63f8a4775e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 15:56:56 -0600 Subject: [PATCH 019/195] Create ToopherAPI.advanced.authenticationRequests.getById() --- src/main/java/com/toopher/ToopherAPI.java | 26 ++++++++++++++++- src/test/java/com/toopher/TestToopherAPI.java | 28 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 0f18451..5bc1e0f 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -564,13 +564,14 @@ private static void parseRequestError(StatusLine statusLine, HttpResponse respon class AdvancedApiUsageFactory { public final Pairings pairings; + public final AuthenticationRequests authenticationRequests; public AdvancedApiUsageFactory(String consumerKey, String consumerSecret) { pairings = new Pairings(); + authenticationRequests = new AuthenticationRequests(); } class Pairings { - /** * Retrieve the current status of a pairing * @@ -592,5 +593,28 @@ public Pairing getById(String pairingId) throws RequestError { } } } + + class AuthenticationRequests { + /** + * Retrieve the current status of an authentication request + * + * @param authenticationRequestId + * The unique id for an authentication request + * @return + * An AuthenticationRequest object + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ + public AuthenticationRequest getById(String authenticationRequestId) throws RequestError { + final String endpoint = String.format("authentication_requests/%s", authenticationRequestId); + + JSONObject json = get(endpoint); + try { + return new AuthenticationRequest(json); + } catch (Exception e) { + throw new RequestError(e); + } + } + } } } diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 332c2b3..8f5b9ed 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -108,6 +108,34 @@ public void testAdvancedPairingsGetById() throws InterruptedException, RequestEr assertTrue(pairing.enabled); } + @Test + public void testAdvancedAuthenticationRequestsGetById() throws InterruptedException, RequestError { + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("pending", true); + jsonResponse.put("granted", true); + jsonResponse.put("automated", false); + jsonResponse.put("reason", reason); + jsonResponse.put("terminal", terminal); + + HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); + + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + AuthenticationRequest authenticationRequest = toopherAPI.advanced.authenticationRequests.getById(id); + + assertEquals(httpClient.getLastCalledMethod(), "GET"); + assertEquals(authenticationRequest.id, id); + assertEquals(authenticationRequest.reason, reason); + assertEquals(authenticationRequest.terminal.id, terminalId); + assertEquals(authenticationRequest.terminal.name, terminalName); + assertEquals(authenticationRequest.terminal.user.id, userId); + assertEquals(authenticationRequest.terminal.user.name, userName); + assertTrue(authenticationRequest.pending); + assertTrue(authenticationRequest.granted); + assertFalse(authenticationRequest.automated); + } + private URI createURI(String url) { try { return new URL(url).toURI(); From eb23d155a428c6a0f75af823fb20c3ce880de37c Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 15:57:51 -0600 Subject: [PATCH 020/195] Create ToopherAPI.advanced.users.getById() --- src/main/java/com/toopher/ToopherAPI.java | 25 +++++++++++++++++++ src/test/java/com/toopher/TestToopherAPI.java | 20 +++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 5bc1e0f..7524794 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -565,10 +565,12 @@ private static void parseRequestError(StatusLine statusLine, HttpResponse respon class AdvancedApiUsageFactory { public final Pairings pairings; public final AuthenticationRequests authenticationRequests; + public final Users users; public AdvancedApiUsageFactory(String consumerKey, String consumerSecret) { pairings = new Pairings(); authenticationRequests = new AuthenticationRequests(); + users = new Users(); } class Pairings { @@ -616,5 +618,28 @@ public AuthenticationRequest getById(String authenticationRequestId) throws Requ } } } + + class Users { + /** + * Retrieve the current status of a user + * + * @param userId + * The unique id for a user + * @return + * A User object + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ + public User getById(String userId) throws RequestError { + final String endpoint = String.format("users/%s", userId); + + JSONObject json = get(endpoint); + try { + return new User(json); + } catch (Exception e) { + throw new RequestError(e); + } + } + } } } diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 8f5b9ed..eda8d3e 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -136,6 +136,26 @@ public void testAdvancedAuthenticationRequestsGetById() throws InterruptedExcept assertFalse(authenticationRequest.automated); } + @Test + public void testAdvancedUsersGetById() throws InterruptedException, RequestError { + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("name", name); + jsonResponse.put("enabled", true); + jsonResponse.put("disable_toopher_auth", true); + + HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); + + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + User user = toopherAPI.advanced.users.getById(id); + + assertEquals(httpClient.getLastCalledMethod(), "GET"); + assertEquals(user.id, id); + assertEquals(user.name, name); + assertFalse(user.enabled); + } + private URI createURI(String url) { try { return new URL(url).toURI(); From 27edf247579718480c5f9374f062fb90c0d49d0f Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 22 Jan 2015 17:09:59 -0600 Subject: [PATCH 021/195] Cleanup ToopherAPI, TestToopherAPI and User --- src/main/java/com/toopher/ToopherAPI.java | 24 ++++++++++++++++++- src/main/java/com/toopher/User.java | 2 +- src/test/java/com/toopher/TestToopherAPI.java | 22 ++++++++++++++++- 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 7524794..853b7d1 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -621,7 +621,7 @@ public AuthenticationRequest getById(String authenticationRequestId) throws Requ class Users { /** - * Retrieve the current status of a user + * Retrieve the current status of a user with the user id * * @param userId * The unique id for a user @@ -640,6 +640,28 @@ public User getById(String userId) throws RequestError { throw new RequestError(e); } } + + /** + * Retrieve the current status of a user with the user name + * @param name + * The name of the user + * @return + * A User object + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ + public User getByName(String name) throws RequestError { + final String endpoint = String.format("users"); + + List params = new ArrayList(); + params.add(new BasicNameValuePair("user_name", name)); + JSONObject json = get(endpoint, params, null); + try { + return new User(json); + } catch (Exception e) { + throw new RequestError(e); + } + } } } } diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index 31598bd..4137ad1 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -18,7 +18,7 @@ public class User extends ApiResponseObject { public String name; /** - * + * Whether or not the user is Toopher-enabled */ public boolean enabled; diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index eda8d3e..efaf1b3 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -1,5 +1,6 @@ package com.toopher; +import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; @@ -15,7 +16,6 @@ public class TestToopherAPI { private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; - private ToopherAPI toopherApi; private String id; private String name; private JSONObject user; @@ -156,6 +156,26 @@ public void testAdvancedUsersGetById() throws InterruptedException, RequestError assertFalse(user.enabled); } + @Test + public void testAdvancedUsersGetByName() throws InterruptedException, RequestError { + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("name", name); + jsonResponse.put("enabled", true); + jsonResponse.put("disable_toopher_auth", false); + + HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); + + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + User user = toopherAPI.advanced.users.getByName(name); + + assertEquals(httpClient.getLastCalledMethod(), "GET"); + assertEquals(user.id, id); + assertEquals(user.name, name); + assertTrue(user.enabled); + } + private URI createURI(String url) { try { return new URL(url).toURI(); From 472fc33368e5bf9ccfa8958b372861fa31fc287b Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 23 Jan 2015 09:12:17 -0600 Subject: [PATCH 022/195] Create ToopherAPI.advanced.users.getByName() --- src/main/java/com/toopher/ToopherAPI.java | 14 ++++++- src/test/java/com/toopher/TestToopherAPI.java | 41 ++++++++++--------- 2 files changed, 34 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 853b7d1..126f8f3 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -652,15 +652,25 @@ public User getById(String userId) throws RequestError { */ public User getByName(String name) throws RequestError { final String endpoint = String.format("users"); + JSONArray result; List params = new ArrayList(); params.add(new BasicNameValuePair("user_name", name)); - JSONObject json = get(endpoint, params, null); try { - return new User(json); + result = (JSONArray) get(endpoint, params, null); } catch (Exception e) { throw new RequestError(e); } + + + if (result.length() > 1) { + throw new RequestError("More than one user with name {0}".format(name)); + } + if (result.length() == 0) { + throw new RequestError("No users with name {0}".format(name)); + } + String userId = result.getJSONObject(0).getString("id"); + return getById(userId); } } } diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index efaf1b3..ab2f6b7 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -156,25 +156,28 @@ public void testAdvancedUsersGetById() throws InterruptedException, RequestError assertFalse(user.enabled); } - @Test - public void testAdvancedUsersGetByName() throws InterruptedException, RequestError { - JSONObject jsonResponse = new JSONObject(); - jsonResponse.put("id", id); - jsonResponse.put("name", name); - jsonResponse.put("enabled", true); - jsonResponse.put("disable_toopher_auth", false); - - HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); - - ToopherAPI toopherAPI = new ToopherAPI("key", "secret", - createURI(DEFAULT_BASE_URL), httpClient); - User user = toopherAPI.advanced.users.getByName(name); - - assertEquals(httpClient.getLastCalledMethod(), "GET"); - assertEquals(user.id, id); - assertEquals(user.name, name); - assertTrue(user.enabled); - } +// TODO: Need to attach 2 JSON response objects +// @Test +// public void testAdvancedUsersGetByName() throws InterruptedException, RequestError { +// JSONObject jsonResponse = new JSONObject(); +// jsonResponse.put("id", id); +// jsonResponse.put("name", name); +// jsonResponse.put("enabled", true); +// jsonResponse.put("disable_toopher_auth", false); +// JSONArray jsonArray = new JSONArray(); +// jsonArray.put(jsonResponse); +// +// HttpClientMock httpClient = new HttpClientMock(200, jsonArray.toString()); +// +// ToopherAPI toopherAPI = new ToopherAPI("key", "secret", +// createURI(DEFAULT_BASE_URL), httpClient); +// User user = toopherAPI.advanced.users.getByName(name); +// +// assertEquals(httpClient.getLastCalledMethod(), "GET"); +// assertEquals(user.id, id); +// assertEquals(user.name, name); +// assertTrue(user.enabled); +// } private URI createURI(String url) { try { From 244f105c9f114fffefdd80f175bd901ca046f292 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 23 Jan 2015 09:45:22 -0600 Subject: [PATCH 023/195] Create ToopherAPI.advanced.users.create() --- src/main/java/com/toopher/ToopherAPI.java | 45 +++++++++++++++++++ src/test/java/com/toopher/TestToopherAPI.java | 40 +++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 126f8f3..0606a73 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -620,6 +620,51 @@ public AuthenticationRequest getById(String authenticationRequestId) throws Requ } class Users { + /** + * Create a new user with a userName + * + * @param userName + * The name of the user + * @return + * A User object + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ + public User create(String userName) throws RequestError { + Map extras = new HashMap(); + return create(userName, extras); + } + + /** + * Create a new user with a userName + * + * @param userName + * The name of the user + * @param extras + * An optional Map of extra parameters to provide to the API + * @return + * A User object + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ + public User create(String userName, Map extras) throws RequestError { + final String endpoint = "users/create"; + List params = new ArrayList(); + JSONObject result; + + for (Map.Entry entry : extras.entrySet()) { + params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + + try { + result = post(endpoint, params, null); + } catch (Exception e) { + throw new RequestError(e); + } + + return new User(result); + } + /** * Retrieve the current status of a user with the user id * diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index ab2f6b7..596f4c9 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -9,6 +9,8 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.util.HashMap; +import java.util.Map; import java.util.UUID; import static org.junit.Assert.*; @@ -136,6 +138,44 @@ public void testAdvancedAuthenticationRequestsGetById() throws InterruptedExcept assertFalse(authenticationRequest.automated); } + @Test + public void testAdvancedUsersCreate() throws InterruptedException, RequestError { + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("name", name); + + HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); + + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + User user = toopherAPI.advanced.users.create(name); + + assertEquals(httpClient.getLastCalledMethod(), "POST"); + assertEquals(user.id, id); + assertEquals(user.name, name); + } + + @Test + public void testAdvancedUsersCreateWithExtras() throws InterruptedException, RequestError { + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("name", name); + jsonResponse.put("enabled", false); + Map extras = new HashMap(); + extras.put("disable_toopher_auth", "false"); + + HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); + + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + User user = toopherAPI.advanced.users.create(name, extras); + + assertEquals(httpClient.getLastCalledMethod(), "POST"); + assertEquals(user.id, id); + assertEquals(user.name, name); + assertFalse(user.enabled); + } + @Test public void testAdvancedUsersGetById() throws InterruptedException, RequestError { JSONObject jsonResponse = new JSONObject(); From 7a98127d4dbf1723529fd3037d2b1c6d84954f24 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 23 Jan 2015 09:50:27 -0600 Subject: [PATCH 024/195] Fix endpoint in Users.getByName() --- src/main/java/com/toopher/ToopherAPI.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 0606a73..d2c8762 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -696,7 +696,7 @@ public User getById(String userId) throws RequestError { * Thrown when an exceptional condition is encountered */ public User getByName(String name) throws RequestError { - final String endpoint = String.format("users"); + final String endpoint = "users"; JSONArray result; List params = new ArrayList(); From b5ed21633b0015d9fad0157351ef11fe4d997b62 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 23 Jan 2015 10:48:14 -0600 Subject: [PATCH 025/195] Create ToopherAPI.advanced.userTerminals.getById() --- src/main/java/com/toopher/ToopherAPI.java | 21 ++++++++++++++++++ src/test/java/com/toopher/TestToopherAPI.java | 22 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index d2c8762..8596972 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -566,11 +566,13 @@ class AdvancedApiUsageFactory { public final Pairings pairings; public final AuthenticationRequests authenticationRequests; public final Users users; + public final UserTerminals userTerminals; public AdvancedApiUsageFactory(String consumerKey, String consumerSecret) { pairings = new Pairings(); authenticationRequests = new AuthenticationRequests(); users = new Users(); + userTerminals = new UserTerminals(); } class Pairings { @@ -718,5 +720,24 @@ public User getByName(String name) throws RequestError { return getById(userId); } } + + class UserTerminals { + /** + * Retrieve the current status of a user terminal by terminal id + * + * @param terminalId + * The unique id for a user terminal + * @return + * A UserTerminal object + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ + public UserTerminal getById(String terminalId) throws RequestError { + final String endpoint = String.format("/user_terminals/%s", terminalId); + JSONObject result = get(endpoint); + return new UserTerminal(result); + } + + } } } diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 596f4c9..bca5f55 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -219,6 +219,28 @@ public void testAdvancedUsersGetById() throws InterruptedException, RequestError // assertTrue(user.enabled); // } + @Test + public void testAdvancedUserTerminalsGetById() throws InterruptedException, RequestError { + JSONObject response = new JSONObject(); + response.put("id", id); + response.put("name", name); + response.put("name_extra", "nameExtra"); + response.put("user", user); + + HttpClientMock httpClient = new HttpClientMock(200, response.toString()); + + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + UserTerminal userTerminal = toopherAPI.advanced.userTerminals.getById(id); + + assertEquals(httpClient.getLastCalledMethod(), "GET"); + assertEquals(userTerminal.id, id); + assertEquals(userTerminal.name, name); + assertEquals(userTerminal.requesterSpecifiedId, "nameExtra"); + assertEquals(userTerminal.user.id, userId); + assertEquals(userTerminal.user.name, userName); + } + private URI createURI(String url) { try { return new URL(url).toURI(); From 2cb4de7fac5e130af7289486cf450b39245593df Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 11:16:17 -0600 Subject: [PATCH 026/195] Create Action object --- src/main/java/com/toopher/Action.java | 26 +++++++++++++++++++ src/test/java/com/toopher/TestToopherAPI.java | 8 ++++++ 2 files changed, 34 insertions(+) create mode 100644 src/main/java/com/toopher/Action.java diff --git a/src/main/java/com/toopher/Action.java b/src/main/java/com/toopher/Action.java new file mode 100644 index 0000000..9f8a825 --- /dev/null +++ b/src/main/java/com/toopher/Action.java @@ -0,0 +1,26 @@ +package com.toopher; + +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Created by graceyim on 1/26/15. + */ +public class Action extends ApiResponseObject { + /** + * The unique id for the authentication request + */ + public String id; + + /** + * The name of the action + */ + public String name; + + public Action (JSONObject json) throws JSONException { + super(json); + + this.id = json.getString("id"); + this.name = json.getString("name"); + } +} diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index bca5f55..e8dc5e7 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -23,6 +23,9 @@ public class TestToopherAPI { private JSONObject user; private String userId; private String userName; + private JSONObject action; + private String actionId; + private String actionName; private String reason; private JSONObject terminal; private String terminalId; @@ -37,6 +40,11 @@ public void setUp() { this.user.put("name", "userName"); this.userId = this.user.getString("id"); this.userName = this.user.getString("name"); + this.action = new JSONObject(); + this.action.put("id", UUID.randomUUID().toString()); + this.action.put("name", "log in"); + this.actionId = this.action.getString("id"); + this.actionName = this.action.getString("name"); this.reason = "it is a test"; this.terminal = new JSONObject(); this.terminal.put("id", UUID.randomUUID().toString()); From 995612c041b2904b25af29ffa9c4c1f8ddf7e74a Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 11:16:38 -0600 Subject: [PATCH 027/195] Add Action and User to AuthenticationRequest object --- .../java/com/toopher/AuthenticationRequest.java | 14 ++++++++++++++ src/test/java/com/toopher/TestToopherAPI.java | 3 +++ 2 files changed, 17 insertions(+) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index 0c022e8..0c277d1 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -41,6 +41,18 @@ public class AuthenticationRequest extends ApiResponseObject { */ public UserTerminal terminal; + /** + * Contains the unique id and descriptive name for the user + * associated with the request + */ + public User user; + + /** + * Contains the unique id and descriptive name for the action + * associated with the request + */ + public Action action; + public AuthenticationRequest(JSONObject json) throws JSONException{ super(json); @@ -50,6 +62,8 @@ public AuthenticationRequest(JSONObject json) throws JSONException{ this.automated = json.getBoolean("automated"); this.reason = json.getString("reason"); this.terminal = new UserTerminal(json.getJSONObject("terminal")); + this.action = new Action(json.getJSONObject("action")); + this.user = terminal.user; } @Override diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index e8dc5e7..7aa8a15 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -126,6 +126,7 @@ public void testAdvancedAuthenticationRequestsGetById() throws InterruptedExcept jsonResponse.put("granted", true); jsonResponse.put("automated", false); jsonResponse.put("reason", reason); + jsonResponse.put("action", action); jsonResponse.put("terminal", terminal); HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); @@ -141,6 +142,8 @@ public void testAdvancedAuthenticationRequestsGetById() throws InterruptedExcept assertEquals(authenticationRequest.terminal.name, terminalName); assertEquals(authenticationRequest.terminal.user.id, userId); assertEquals(authenticationRequest.terminal.user.name, userName); + assertEquals(authenticationRequest.action.id, actionId); + assertEquals(authenticationRequest.action.name, actionName); assertTrue(authenticationRequest.pending); assertTrue(authenticationRequest.granted); assertFalse(authenticationRequest.automated); From 308bc31cf08eb4a92dd3e1d27bdd8d0435fd88c9 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 12:31:30 -0600 Subject: [PATCH 028/195] Remove raw from UserTerminal --- src/main/java/com/toopher/UserTerminal.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index c2bc2bb..83e128b 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -11,7 +11,6 @@ public class UserTerminal extends ApiResponseObject { public String name; public String requesterSpecifiedId; public User user; - public JSONObject raw; public UserTerminal (JSONObject json) throws JSONException { super(json); @@ -22,6 +21,5 @@ public UserTerminal (JSONObject json) throws JSONException { this.requesterSpecifiedId = json.getString("name_extra"); } this.user = new User(json.getJSONObject("user")); - this.raw = json; } } From 34d72a1661e003e8ca30e3613e0c55ee4b46368d Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 12:47:32 -0600 Subject: [PATCH 029/195] Create ApiRawRequester class for get() and post() --- src/main/java/com/toopher/ToopherAPI.java | 151 +++++++++++----------- 1 file changed, 78 insertions(+), 73 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 8596972..dbb0e46 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -191,7 +191,7 @@ public Pairing pair(String pairingPhrase, String userName, Map e params.add(new BasicNameValuePair("pairing_phrase", pairingPhrase)); params.add(new BasicNameValuePair("user_name", userName)); - JSONObject json = post(endpoint, params, extras); + JSONObject json = advanced.raw.post(endpoint, params, extras); try { return new Pairing(json); } catch (Exception e) { @@ -229,7 +229,7 @@ public Pairing pairWithQrCode(String userName, Map extras) throw List params = new ArrayList(); params.add(new BasicNameValuePair("user_name", userName)); - JSONObject json = post(endpoint, params, extras); + JSONObject json = advanced.raw.post(endpoint, params, extras); try { return new Pairing(json); } catch (Exception e) { @@ -299,7 +299,7 @@ public AuthenticationRequest authenticate(String pairingId, String terminalName, params.add(new BasicNameValuePair("action_name", actionName)); } - JSONObject json = post(endpoint, params, extras); + JSONObject json = advanced.raw.post(endpoint, params, extras); try { return new AuthenticationRequest(json); } catch (Exception e) { @@ -343,7 +343,7 @@ public AuthenticationRequest getAuthenticationStatus(String authenticationReques throws RequestError { final String endpoint = String.format("authentication_requests/%s", authenticationRequestId); - JSONObject json = get(endpoint); + JSONObject json = advanced.raw.get(endpoint); try { return new AuthenticationRequest(json); } catch (Exception e) { @@ -355,7 +355,7 @@ public AuthenticationRequest getAuthenticationStatusWithOTP(String authenticatio final String endpoint = String.format("authentication_requests/%s/otp_auth", authenticationRequestId); List params = new ArrayList(); params.add(new BasicNameValuePair("otp", OTP)); - JSONObject json = post(endpoint, params, null); + JSONObject json = advanced.raw.post(endpoint, params, null); try { return new AuthenticationRequest(json); } catch (Exception e) { @@ -386,7 +386,7 @@ public void assignUserFriendlyNameToTerminal(String userName, String terminalNam params.add(new BasicNameValuePair("name", terminalName)); params.add(new BasicNameValuePair("name_extra", terminalNameExtra)); - post(endpoint, params, null); + advanced.raw.post(endpoint, params, null); } /** @@ -407,7 +407,7 @@ public void setToopherEnabledForUser(String userName, boolean toopherEnabled) th List params = new ArrayList(); params.add(new BasicNameValuePair("name", userName)); - JSONArray result = get(searchEndpoint, params, null); + JSONArray result = advanced.raw.get(searchEndpoint, params, null); // user name should be a unique field per requester - if more than one object is returned, this is gonna be a problem if (result.length() > 1) { @@ -430,67 +430,9 @@ public void setToopherEnabledForUser(String userName, boolean toopherEnabled) th params = new ArrayList(); params.add(new BasicNameValuePair("disable_toopher_auth", toopherEnabled ? "false" : "true")); - post(String.format(updateEndpoint, userId), params, null); + advanced.raw.post(String.format(updateEndpoint, userId), params, null); } - - - private T get(String endpoint) throws RequestError { - return request(new HttpGet(), endpoint, null); - } - private T get(String endpoint, List params, Map extras) throws RequestError { - if (params == null) { - params = new ArrayList(); - } - if (extras != null && extras.size() > 0) { - for (Map.Entry e : extras.entrySet()){ - params.add(new BasicNameValuePair(e.getKey(), e.getValue())); - } - } - return request(new HttpGet(), endpoint, params); - } - - private T post(String endpoint, List params, Map extras) throws RequestError { - HttpPost post = new HttpPost(); - if (extras != null && extras.size() > 0) { - for (Map.Entry e : extras.entrySet()){ - params.add(new BasicNameValuePair(e.getKey(), e.getValue())); - } - } - if (params != null && params.size() > 0) { - try { - post.setEntity(new UrlEncodedFormEntity(params)); - } catch (Exception e) { - throw new RequestError(e); - } - } - return request(post, endpoint, null); - } - - private T request(HttpRequestBase httpRequest, String endpoint, List queryStringParameters) throws RequestError { - try { - URIBuilder uriBuilder = new URIBuilder().setScheme(this.uriScheme).setHost(this.uriHost) - .setPort(this.uriPort) - .setPath(this.uriBase + endpoint); - if (queryStringParameters != null && queryStringParameters.size() > 0) { - for (NameValuePair nvp : queryStringParameters) { - uriBuilder.setParameter(nvp.getName(), nvp.getValue()); - } - } - httpRequest.setURI(uriBuilder.build()); - consumer.sign(httpRequest); - } catch (Exception e) { - throw new RequestError(e); - } - - try { - return (T) httpClient.execute(httpRequest, jsonHandler); - } catch (RequestError re) { - throw re; - } catch (Exception e) { - throw new RequestError(e); - } - } - + private static ResponseHandler jsonHandler = new ResponseHandler() { @Override @@ -567,12 +509,14 @@ class AdvancedApiUsageFactory { public final AuthenticationRequests authenticationRequests; public final Users users; public final UserTerminals userTerminals; + public final ApiRawRequester raw; public AdvancedApiUsageFactory(String consumerKey, String consumerSecret) { pairings = new Pairings(); authenticationRequests = new AuthenticationRequests(); users = new Users(); userTerminals = new UserTerminals(); + raw = new ApiRawRequester(); } class Pairings { @@ -589,7 +533,7 @@ class Pairings { public Pairing getById(String pairingId) throws RequestError { final String endpoint = String.format("pairings/%s", pairingId); - JSONObject json = get(endpoint); + JSONObject json = advanced.raw.get(endpoint); try { return new Pairing(json); } catch (Exception e) { @@ -612,7 +556,7 @@ class AuthenticationRequests { public AuthenticationRequest getById(String authenticationRequestId) throws RequestError { final String endpoint = String.format("authentication_requests/%s", authenticationRequestId); - JSONObject json = get(endpoint); + JSONObject json = advanced.raw.get(endpoint); try { return new AuthenticationRequest(json); } catch (Exception e) { @@ -659,7 +603,7 @@ public User create(String userName, Map extras) throws RequestEr } try { - result = post(endpoint, params, null); + result = advanced.raw.post(endpoint, params, null); } catch (Exception e) { throw new RequestError(e); } @@ -680,7 +624,7 @@ public User create(String userName, Map extras) throws RequestEr public User getById(String userId) throws RequestError { final String endpoint = String.format("users/%s", userId); - JSONObject json = get(endpoint); + JSONObject json = advanced.raw.get(endpoint); try { return new User(json); } catch (Exception e) { @@ -704,7 +648,7 @@ public User getByName(String name) throws RequestError { List params = new ArrayList(); params.add(new BasicNameValuePair("user_name", name)); try { - result = (JSONArray) get(endpoint, params, null); + result = (JSONArray) advanced.raw.get(endpoint, params, null); } catch (Exception e) { throw new RequestError(e); } @@ -734,10 +678,71 @@ class UserTerminals { */ public UserTerminal getById(String terminalId) throws RequestError { final String endpoint = String.format("/user_terminals/%s", terminalId); - JSONObject result = get(endpoint); + JSONObject result = advanced.raw.get(endpoint); return new UserTerminal(result); } } + + class ApiRawRequester { + public T get(String endpoint) throws RequestError { + return request(new HttpGet(), endpoint, null); + } + + public T get(String endpoint, List params, Map extras) throws RequestError { + if (params == null) { + params = new ArrayList(); + } + if (extras != null && extras.size() > 0) { + for (Map.Entry e : extras.entrySet()){ + params.add(new BasicNameValuePair(e.getKey(), e.getValue())); + } + } + return request(new HttpGet(), endpoint, params); + } + + public T post(String endpoint, List params, Map extras) throws RequestError { + HttpPost post = new HttpPost(); + if (extras != null && extras.size() > 0) { + for (Map.Entry e : extras.entrySet()){ + params.add(new BasicNameValuePair(e.getKey(), e.getValue())); + } + } + if (params != null && params.size() > 0) { + try { + post.setEntity(new UrlEncodedFormEntity(params)); + } catch (Exception e) { + throw new RequestError(e); + } + } + return request(post, endpoint, null); + } + + private T request(HttpRequestBase httpRequest, String endpoint, List queryStringParameters) throws RequestError { + try { + URIBuilder uriBuilder = new URIBuilder().setScheme(uriScheme).setHost(uriHost) + .setPort(uriPort) + .setPath(uriBase + endpoint); + if (queryStringParameters != null && queryStringParameters.size() > 0) { + for (NameValuePair nvp : queryStringParameters) { + uriBuilder.setParameter(nvp.getName(), nvp.getValue()); + } + } + httpRequest.setURI(uriBuilder.build()); + consumer.sign(httpRequest); + } catch (Exception e) { + throw new RequestError(e); + } + + try { + return (T) httpClient.execute(httpRequest, jsonHandler); + } catch (RequestError re) { + throw re; + } catch (Exception e) { + throw new RequestError(e); + } + } + + } } } From c7b27984fd75f967809e6a14da5aa2b31d951ed2 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 14:12:34 -0600 Subject: [PATCH 030/195] Refactor pair() to handle regular, QR and SMS pairings --- src/main/java/com/toopher/ToopherAPI.java | 85 +++++++++---------- src/test/java/com/toopher/TestToopherAPI.java | 27 +++++- 2 files changed, 64 insertions(+), 48 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index dbb0e46..a5d216e 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -157,64 +157,39 @@ public ToopherAPI(String consumerKey, String consumerSecret, URI uri, HttpClient /** - * Create a pairing - * - * @param pairingPhrase - * The pairing phrase supplied by the user - * @param userName - * A user-facing descriptive name for the user (displayed in requests) - * @return A Pairing object - * @throws RequestError - * Thrown when an exceptional condition is encountered - */ - public Pairing pair(String pairingPhrase, String userName) throws RequestError { - return this.pair(pairingPhrase, userName, null); - } - - /** - * Create a pairing - * - * @param pairingPhrase - * The pairing phrase supplied by the user + * Create a QR pairing * @param userName - * A user-facing descriptive name for the user (displayed in requests) - * @param extras - * An optional Map of extra parameters to provide to the API - * @return A Pairing object + * A user-facing descriptive name for the user (displayed in requests) + * @return A Pairing object * @throws RequestError - * Thrown when an exceptional condition is encountered + * Thrown when an exceptional condition is encountered */ - public Pairing pair(String pairingPhrase, String userName, Map extras) throws RequestError { - final String endpoint = "pairings/create"; - - List params = new ArrayList(); - params.add(new BasicNameValuePair("pairing_phrase", pairingPhrase)); - params.add(new BasicNameValuePair("user_name", userName)); - - JSONObject json = advanced.raw.post(endpoint, params, extras); - try { - return new Pairing(json); - } catch (Exception e) { - throw new RequestError(e); - } + public Pairing pair(String userName) throws RequestError { + Map extras = new HashMap(); + return this.pair(userName, "", extras); } - + /** - * Create a pairing that is presented as a QR code + * Create an SMS pairing or regular pairing * + * @param pairingPhraseOrNum + * The pairing phrase or phone number supplied by the user * @param userName * A user-facing descriptive name for the user (displayed in requests) * @return A Pairing object * @throws RequestError * Thrown when an exceptional condition is encountered */ - public Pairing pairWithQrCode(String userName) throws RequestError { - return this.pairWithQrCode(userName, null); + public Pairing pair(String userName, String pairingPhraseOrNum) throws RequestError { + Map extras = new HashMap(); + return this.pair(userName, pairingPhraseOrNum, extras); } /** - * Create a pairing that is presented as a QR code + * Create an SMS pairing or regular pairing * + * @param pairingPhraseOrNum + * The pairing phrase or phone number supplied by the user * @param userName * A user-facing descriptive name for the user (displayed in requests) * @param extras @@ -223,15 +198,33 @@ public Pairing pairWithQrCode(String userName) throws RequestError { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public Pairing pairWithQrCode(String userName, Map extras) throws RequestError { - final String endpoint = "pairings/create/qr"; + public Pairing pair( String userName, String pairingPhraseOrNum, Map extras) throws RequestError { + String endpoint; + JSONObject result; List params = new ArrayList(); params.add(new BasicNameValuePair("user_name", userName)); - JSONObject json = advanced.raw.post(endpoint, params, extras); + for (Map.Entry entry : extras.entrySet()) { + params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + + if (!pairingPhraseOrNum.isEmpty()) { + if (pairingPhraseOrNum.matches("\\d+")) { + params.add(new BasicNameValuePair("phone_number", pairingPhraseOrNum)); + endpoint = "pairings/create/sms"; + } else { + params.add(new BasicNameValuePair("pairing_phrase", pairingPhraseOrNum)); + endpoint = "pairings/create"; + } + } else { + endpoint = "pairings/create/qr"; + } + + result = advanced.raw.post(endpoint, params, null); + try { - return new Pairing(json); + return new Pairing(result); } catch (Exception e) { throw new RequestError(e); } diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 7aa8a15..0a6a9ed 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -65,7 +65,7 @@ public void testCreatePairing() throws InterruptedException, RequestError { ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); - Pairing pairing = toopherApi.pair("awkward turtle", "some user"); + Pairing pairing = toopherApi.pair("some user", "awkward turtle"); assertEquals(httpClient.getLastCalledMethod(), "POST"); assertEquals(httpClient.getLastCalledData("pairing_phrase"), "awkward turtle"); @@ -88,7 +88,7 @@ public void testCreateQrPairing() throws InterruptedException, RequestError { ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI("https://api.toopher.test/v1"), httpClient); - Pairing pairing = toopherApi.pairWithQrCode(userName); + Pairing pairing = toopherApi.pair(userName); assertEquals(httpClient.getLastCalledMethod(), "POST"); assertEquals(pairing.user.id, userId); @@ -97,6 +97,29 @@ public void testCreateQrPairing() throws InterruptedException, RequestError { assertTrue(pairing.enabled); } + @Test + public void testCreateSmsPairing() throws InterruptedException, RequestError { + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("enabled", true); + jsonResponse.put("pending", true); + jsonResponse.put("user", user); + + HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); + + ToopherAPI toopherApi = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + Pairing pairing = toopherApi.pair(userName, "123456"); + + assertEquals(httpClient.getLastCalledMethod(), "POST"); + assertEquals(httpClient.getLastCalledData("phone_number"), "123456"); + + assertEquals(pairing.user.id, userId); + assertEquals(pairing.user.name, userName); + assertTrue(pairing.pending); + assertTrue(pairing.enabled); + } + @Test public void testAdvancedPairingsGetById() throws InterruptedException, RequestError { JSONObject jsonResponse = new JSONObject(); From 582d7d98a402feada9b44d8966ff87aef0cf4056 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 14:25:32 -0600 Subject: [PATCH 031/195] Add terminalNameExtra to tests --- src/test/java/com/toopher/TestToopherAPI.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 0a6a9ed..1102a4c 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -30,6 +30,7 @@ public class TestToopherAPI { private JSONObject terminal; private String terminalId; private String terminalName; + private String terminalNameExtra; @Before public void setUp() { @@ -49,9 +50,11 @@ public void setUp() { this.terminal = new JSONObject(); this.terminal.put("id", UUID.randomUUID().toString()); this.terminal.put("name", "terminalName"); + this.terminal.put("name_extra", "terminalNameExtra"); this.terminal.put("user", this.user); this.terminalId = this.terminal.getString("id"); this.terminalName = this.terminal.getString("name"); + this.terminalNameExtra = this.terminal.getString("name_extra"); } @Test @@ -258,7 +261,7 @@ public void testAdvancedUserTerminalsGetById() throws InterruptedException, Requ JSONObject response = new JSONObject(); response.put("id", id); response.put("name", name); - response.put("name_extra", "nameExtra"); + response.put("name_extra", terminalNameExtra); response.put("user", user); HttpClientMock httpClient = new HttpClientMock(200, response.toString()); @@ -270,7 +273,7 @@ public void testAdvancedUserTerminalsGetById() throws InterruptedException, Requ assertEquals(httpClient.getLastCalledMethod(), "GET"); assertEquals(userTerminal.id, id); assertEquals(userTerminal.name, name); - assertEquals(userTerminal.requesterSpecifiedId, "nameExtra"); + assertEquals(userTerminal.requesterSpecifiedId, terminalNameExtra); assertEquals(userTerminal.user.id, userId); assertEquals(userTerminal.user.name, userName); } From c555c1a6fb6b3d816389e5aefeb8c3c1d8ef65df Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 14:36:42 -0600 Subject: [PATCH 032/195] Remove old getAuthenticationStatus() --- src/main/java/com/toopher/ToopherAPI.java | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index a5d216e..dc580fb 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -323,27 +323,6 @@ public AuthenticationRequest authenticateByUserName(String userName, String term return authenticate(null, null, actionName, extras); } - /** - * Retrieve status information for an authentication request - * - * @param authenticationRequestId - * The authentication request ID - * @return An AuthenticationRequest object - * @throws RequestError - * Thrown when an exceptional condition is encountered - */ - public AuthenticationRequest getAuthenticationStatus(String authenticationRequestId) - throws RequestError { - final String endpoint = String.format("authentication_requests/%s", authenticationRequestId); - - JSONObject json = advanced.raw.get(endpoint); - try { - return new AuthenticationRequest(json); - } catch (Exception e) { - throw new RequestError(e); - } - } - public AuthenticationRequest getAuthenticationStatusWithOTP(String authenticationRequestId,String OTP) throws RequestError { final String endpoint = String.format("authentication_requests/%s/otp_auth", authenticationRequestId); List params = new ArrayList(); From ad38f26d39bfd9335eff10077d752a881fd4b6df Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 15:03:34 -0600 Subject: [PATCH 033/195] Refactor authenticate() to handle authentication with username or pairing id --- src/main/java/com/toopher/ToopherAPI.java | 72 +++++++------------ src/main/java/com/toopher/ToopherAPIDemo.java | 2 +- src/test/java/com/toopher/TestToopherAPI.java | 60 ++++++++++++++++ 3 files changed, 86 insertions(+), 48 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index dc580fb..f70bbef 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -3,10 +3,7 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.HashMap; +import java.util.*; import oauth.signpost.OAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; @@ -233,24 +230,24 @@ public Pairing pair( String userName, String pairingPhraseOrNum, Map extras = new HashMap(); + return authenticate(pairingIdOrUsername, terminalNameOrTerminalNameExtra, actionName, extras); } /** - * Initiate an authentication request + * Initiate an authentication request by pairing id or username * - * @param pairingId - * The pairing id indicating to whom the request should be sent - * @param terminalName + * @param pairingIdOrUsername + * The pairing id or username indicating to whom the request should be sent + * @param terminalNameOrTerminalNameExtra * The user-facing descriptive name for the terminal from which the request originates + * or the unique identifier for this terminal. Not displayed to the user. * @param actionName * The user-facing descriptive name for the action which is being authenticated * @param extras @@ -277,17 +276,19 @@ public AuthenticationRequest authenticate(String pairingId, String terminalName, * @throws RequestError * Thrown when an exceptional condition is encountered */ - public AuthenticationRequest authenticate(String pairingId, String terminalName, - String actionName, Map extras) throws RequestError { + public AuthenticationRequest authenticate(String pairingIdOrUsername, String terminalNameOrTerminalNameExtra, String actionName, Map extras) throws RequestError { final String endpoint = "authentication_requests/initiate"; - List params = new ArrayList(); - if (pairingId != null) { - params.add(new BasicNameValuePair("pairing_id", pairingId)); - } - if (terminalName != null) { - params.add(new BasicNameValuePair("terminal_name", terminalName)); + + try { + UUID.fromString(pairingIdOrUsername); + params.add(new BasicNameValuePair("pairing_id", pairingIdOrUsername)); + params.add(new BasicNameValuePair("terminal_name", terminalNameOrTerminalNameExtra)); + } catch (Exception e) { + params.add(new BasicNameValuePair("user_name", pairingIdOrUsername)); + params.add(new BasicNameValuePair("terminal_name_extra", terminalNameOrTerminalNameExtra)); } + if (actionName != null && actionName.length() > 0) { params.add(new BasicNameValuePair("action_name", actionName)); } @@ -300,29 +301,6 @@ public AuthenticationRequest authenticate(String pairingId, String terminalName, } } - /** - * Initiate a login authentication request by username (instead of PairingID) - * - * @param userName - * The unique UserName for this user - * @param terminalNameExtra - * Unique identifier for this terminal. Not displayed to the user. - * @param actionName - * The user-facing descriptive name for the action which is being authenticated - * @return An AuthenticationRequest object - * @throws RequestError - * Thrown when an exceptional condition is encountered - */ - public AuthenticationRequest authenticateByUserName(String userName, String terminalNameExtra, String actionName, Map extras) throws RequestError { - if (extras == null) { - extras = new HashMap(); - } - extras.put("user_name", userName); - extras.put("terminal_name_extra", terminalNameExtra); - - return authenticate(null, null, actionName, extras); - } - public AuthenticationRequest getAuthenticationStatusWithOTP(String authenticationRequestId,String OTP) throws RequestError { final String endpoint = String.format("authentication_requests/%s/otp_auth", authenticationRequestId); List params = new ArrayList(); diff --git a/src/main/java/com/toopher/ToopherAPIDemo.java b/src/main/java/com/toopher/ToopherAPIDemo.java index e0bca7b..5481a4b 100644 --- a/src/main/java/com/toopher/ToopherAPIDemo.java +++ b/src/main/java/com/toopher/ToopherAPIDemo.java @@ -125,7 +125,7 @@ public static void main(String[] args) { AuthenticationRequest requestStatus; try { - requestStatus = api.getAuthenticationStatus(requestId); + requestStatus = api.authenticate(requestId, terminalName); } catch (RequestError err) { System.out.println(String.format("Could not check authentication status (reason:%s)", err.getMessage())); continue; diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 1102a4c..aa45c25 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -144,6 +144,66 @@ public void testAdvancedPairingsGetById() throws InterruptedException, RequestEr assertTrue(pairing.enabled); } + @Test + public void testCreateAuthenticationRequestWithPairingId() throws InterruptedException, RequestError { + JSONObject response = new JSONObject(); + response.put("id", id); + response.put("pending", true); + response.put("granted", true); + response.put("automated", false); + response.put("reason", reason); + response.put("terminal", terminal); + response.put("action", action); + + HttpClientMock httpClient = new HttpClientMock(200, response.toString()); + + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + AuthenticationRequest authenticationRequest = toopherAPI.authenticate(id, terminalName, actionName); + + assertEquals(httpClient.getLastCalledMethod(), "POST"); + assertEquals(authenticationRequest.id, id); + assertTrue(authenticationRequest.pending); + assertTrue(authenticationRequest.granted); + assertFalse(authenticationRequest.automated); + assertEquals(authenticationRequest.reason, reason); + assertEquals(authenticationRequest.terminal.id, terminalId); + assertEquals(authenticationRequest.terminal.name, terminalName); + assertEquals(authenticationRequest.action.id, actionId); + assertEquals(authenticationRequest.action.name, actionName); + } + + @Test + public void testCreateAuthenticationRequestWithUsername() throws InterruptedException, RequestError { + JSONObject response = new JSONObject(); + response.put("id", id); + response.put("pending", true); + response.put("granted", true); + response.put("automated", false); + response.put("reason", reason); + response.put("terminal", terminal); + response.put("action", action); + + HttpClientMock httpClient = new HttpClientMock(200, response.toString()); + + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + AuthenticationRequest authenticationRequest = toopherAPI.authenticate(userName, terminalNameExtra, actionName); + + assertEquals(httpClient.getLastCalledMethod(), "POST"); + assertEquals(authenticationRequest.id, id); + assertTrue(authenticationRequest.pending); + assertTrue(authenticationRequest.granted); + assertFalse(authenticationRequest.automated); + assertEquals(authenticationRequest.reason, reason); + assertEquals(authenticationRequest.terminal.id, terminalId); + assertEquals(authenticationRequest.terminal.name, terminalName); + assertEquals(authenticationRequest.action.id, actionId); + assertEquals(authenticationRequest.action.name, actionName); + } + + + @Test public void testAdvancedAuthenticationRequestsGetById() throws InterruptedException, RequestError { JSONObject jsonResponse = new JSONObject(); From ab268af272cae92b9b0bbad44cba7b3133456f4c Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 15:55:16 -0600 Subject: [PATCH 034/195] Add AuthenticationRequest.authenticate_with_otp() --- .../com/toopher/AuthenticationRequest.java | 25 ++++++ .../toopher/TestAuthenticationRequest.java | 82 +++++++++++++++++++ 2 files changed, 107 insertions(+) create mode 100644 src/test/java/com/toopher/TestAuthenticationRequest.java diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index 0c277d1..874b2ca 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -1,7 +1,12 @@ package com.toopher; +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; import java.util.Map; /** @@ -72,4 +77,24 @@ public String toString() { id, pending, granted, automated, reason, terminal.id, terminal.name); } + public void authenticate_with_otp(ToopherAPI api, String otp) throws RequestError { + String endpoint = "authentication_requests/{0}/otp_auth".format(id); + List params = new ArrayList(); + params.add(new BasicNameValuePair("otp", otp)); + + JSONObject json = api.advanced.raw.post(endpoint, params, null); + try { + update(json); + } catch (Exception e) { + throw new RequestError(e); + } + } + + public void update(JSONObject jsonResponse) { + this.pending = jsonResponse.getBoolean("pending"); + this.granted = jsonResponse.getBoolean("granted"); + this.automated = jsonResponse.getBoolean("automated"); + this.reason = jsonResponse.getString("reason"); + } + } diff --git a/src/test/java/com/toopher/TestAuthenticationRequest.java b/src/test/java/com/toopher/TestAuthenticationRequest.java new file mode 100644 index 0000000..18a33a1 --- /dev/null +++ b/src/test/java/com/toopher/TestAuthenticationRequest.java @@ -0,0 +1,82 @@ +package com.toopher; + +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.UUID; + +import static org.junit.Assert.*; + +/** + * Created by graceyim on 1/26/15. + */ +public class TestAuthenticationRequest { + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; + + private ToopherAPI api; + private String id; + private String reason; + private JSONObject terminal; + private JSONObject action; + private JSONObject user; + private JSONObject jsonResponse; + + @Before + public void setUp() { + this.api = new ToopherAPI("key", "secret"); + this.id = UUID.randomUUID().toString(); + this.reason = "it is a test"; + this.user = new JSONObject(); + this.user.put("id", UUID.randomUUID().toString()); + this.user.put("name", "userName"); + this.terminal = new JSONObject(); + this.terminal.put("id", UUID.randomUUID().toString()); + this.terminal.put("name", "terminalName"); + this.terminal.put("name_extra", "terminalNameExtra"); + this.terminal.put("user", this.user); + this.action = new JSONObject(); + this.action.put("id", UUID.randomUUID().toString()); + this.action.put("name", "log in"); + this.jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("pending", true); + jsonResponse.put("granted", true); + jsonResponse.put("automated", true); + jsonResponse.put("reason", reason); + jsonResponse.put("user", user); + jsonResponse.put("terminal", terminal); + jsonResponse.put("action", action); + } + + @Test + public void testAuthenticateWithOtp() throws InterruptedException, RequestError { + AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse); + + JSONObject newJsonResponse = jsonResponse; + newJsonResponse.remove("reason"); + newJsonResponse.put("reason", "it is a changed test"); + + HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + authenticationRequest.authenticate_with_otp(toopherAPI, "testOtp"); + + assertEquals(authenticationRequest.id, id); + assertEquals(authenticationRequest.reason, "it is a changed test"); + } + + private URI createURI(String url) { + try { + return new URL(url).toURI(); + } catch (MalformedURLException e) { + return null; + } catch (URISyntaxException e) { + return null; + } + } +} From 98068e334477d6d9c714efd90e70d34d0c9696b6 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 16:09:57 -0600 Subject: [PATCH 035/195] Add update() to Action --- src/main/java/com/toopher/Action.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/toopher/Action.java b/src/main/java/com/toopher/Action.java index 9f8a825..d0df02b 100644 --- a/src/main/java/com/toopher/Action.java +++ b/src/main/java/com/toopher/Action.java @@ -23,4 +23,8 @@ public Action (JSONObject json) throws JSONException { this.id = json.getString("id"); this.name = json.getString("name"); } + + public void update(JSONObject jsonResponse) { + this.name = jsonResponse.getString("name"); + } } From 0d1073dec1aa94432b0929c618bd56b81f75a9b1 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 16:10:22 -0600 Subject: [PATCH 036/195] Add update() and remove raw from User --- src/main/java/com/toopher/User.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index 4137ad1..bf701b9 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -22,11 +22,6 @@ public class User extends ApiResponseObject { */ public boolean enabled; - /** - * Contains the raw JSONObject - */ - public JSONObject raw; - public User (JSONObject json) throws JSONException { super(json); @@ -35,6 +30,12 @@ public User (JSONObject json) throws JSONException { if (json.has("disable_toopher_auth")) { this.enabled = (json.getBoolean("disable_toopher_auth") ? false : true); } - this.raw = json; + } + + public void update(JSONObject jsonResponse) { + this.name = jsonResponse.getString("name"); + if (jsonResponse.has("disable_toopher_auth")) { + this.enabled = (jsonResponse.getBoolean("disable_toopher_auth") ? false : true); + } } } From 10b9facbca11168a54484922b160719fcd2e59eb Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 16:10:34 -0600 Subject: [PATCH 037/195] Add update() to UserTerminal --- src/main/java/com/toopher/UserTerminal.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index 83e128b..79e759d 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -22,4 +22,11 @@ public UserTerminal (JSONObject json) throws JSONException { } this.user = new User(json.getJSONObject("user")); } + + public void update(JSONObject jsonResponse) { + this.name = jsonResponse.getString("name"); + if (jsonResponse.has("name_extra")) { + this.requesterSpecifiedId = jsonResponse.getString("name_extra"); + } + } } From db5889603c582b22f897ab18994def6b1cd4362d Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 16:10:52 -0600 Subject: [PATCH 038/195] Update AuthenticationRequest with update methods --- src/main/java/com/toopher/AuthenticationRequest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index 874b2ca..288c71a 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -95,6 +95,9 @@ public void update(JSONObject jsonResponse) { this.granted = jsonResponse.getBoolean("granted"); this.automated = jsonResponse.getBoolean("automated"); this.reason = jsonResponse.getString("reason"); + this.terminal.update(jsonResponse.getJSONObject("terminal")); + this.action.update(jsonResponse.getJSONObject("action")); + this.user.update(jsonResponse.getJSONObject("user")); } } From 8a56fe0b92bc13e9ca73d51ed1d709fdb7fcdc9c Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 16:48:49 -0600 Subject: [PATCH 039/195] Add AuthenticationRequest.refreshFromServer() --- .../com/toopher/AuthenticationRequest.java | 6 +++++ .../toopher/TestAuthenticationRequest.java | 22 +++++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index 288c71a..861930b 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -90,6 +90,12 @@ public void authenticate_with_otp(ToopherAPI api, String otp) throws RequestErro } } + public void refresh_from_server(ToopherAPI api) throws RequestError { + String endpoint = "authentication_requests{0}".format(id); + JSONObject result = api.advanced.raw.get(endpoint); + update(result); + } + public void update(JSONObject jsonResponse) { this.pending = jsonResponse.getBoolean("pending"); this.granted = jsonResponse.getBoolean("granted"); diff --git a/src/test/java/com/toopher/TestAuthenticationRequest.java b/src/test/java/com/toopher/TestAuthenticationRequest.java index 18a33a1..9803142 100644 --- a/src/test/java/com/toopher/TestAuthenticationRequest.java +++ b/src/test/java/com/toopher/TestAuthenticationRequest.java @@ -18,7 +18,6 @@ public class TestAuthenticationRequest { private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; - private ToopherAPI api; private String id; private String reason; private JSONObject terminal; @@ -28,7 +27,6 @@ public class TestAuthenticationRequest { @Before public void setUp() { - this.api = new ToopherAPI("key", "secret"); this.id = UUID.randomUUID().toString(); this.reason = "it is a test"; this.user = new JSONObject(); @@ -70,6 +68,26 @@ public void testAuthenticateWithOtp() throws InterruptedException, RequestError assertEquals(authenticationRequest.reason, "it is a changed test"); } + @Test + public void testRefreshFromServer() throws InterruptedException, RequestError { + AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse); + + JSONObject newJsonResponse = jsonResponse; + newJsonResponse.remove("pending"); + newJsonResponse.remove("granted"); + jsonResponse.put("pending", false); + jsonResponse.put("granted", false); + + HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + authenticationRequest.refresh_from_server(toopherAPI); + + assertEquals(authenticationRequest.id, id); + assertFalse(authenticationRequest.pending); + assertFalse(authenticationRequest.granted); + } + private URI createURI(String url) { try { return new URL(url).toURI(); From d98b233287beb006cd8f3d2715e96777c4132e38 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 17:26:56 -0600 Subject: [PATCH 040/195] Add toString() for UserTerminal --- src/main/java/com/toopher/UserTerminal.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index 79e759d..aff0b8d 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -23,6 +23,12 @@ public UserTerminal (JSONObject json) throws JSONException { this.user = new User(json.getJSONObject("user")); } + @Override + public String toString() { + return String.format("[UserTerminal: id=%s; name=%s; requesterSpecifiedId=%s; userName=%s; userId=%s]", + id, name, requesterSpecifiedId, user.name, user.id); + } + public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); if (jsonResponse.has("name_extra")) { From d5b943e60aec4d0956afef803538a549ce19eedb Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 17:27:44 -0600 Subject: [PATCH 041/195] Update User when updating UserTerminal --- src/main/java/com/toopher/UserTerminal.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index aff0b8d..ee91ffc 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -34,5 +34,6 @@ public void update(JSONObject jsonResponse) { if (jsonResponse.has("name_extra")) { this.requesterSpecifiedId = jsonResponse.getString("name_extra"); } + this.user.update(jsonResponse.getJSONObject("user")); } } From 37b4045ff7182b34b81e7052483f233af0068480 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 17:28:14 -0600 Subject: [PATCH 042/195] Add UserTerminal.refreshFromServer() --- src/main/java/com/toopher/UserTerminal.java | 6 ++ .../java/com/toopher/TestUserTerminal.java | 69 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 src/test/java/com/toopher/TestUserTerminal.java diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index ee91ffc..2e1519c 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -29,6 +29,12 @@ public String toString() { id, name, requesterSpecifiedId, user.name, user.id); } + public void refresh_from_server(ToopherAPI api) throws RequestError { + String endpoint = "user_terminals/{0}".format(id); + JSONObject result = api.advanced.raw.get(endpoint); + update(result); + } + public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); if (jsonResponse.has("name_extra")) { diff --git a/src/test/java/com/toopher/TestUserTerminal.java b/src/test/java/com/toopher/TestUserTerminal.java new file mode 100644 index 0000000..1b4ec5d --- /dev/null +++ b/src/test/java/com/toopher/TestUserTerminal.java @@ -0,0 +1,69 @@ +package com.toopher; + +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; + +import java.net.URI; +import java.util.UUID; + +import static org.junit.Assert.*; + + +/** + * Created by graceyim on 1/26/15. + */ +public class TestUserTerminal { + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; + + private String id; + private String name; + private String requesterSpecifiedId; + public JSONObject user; + public String userName; + + @Before + public void setUp() { + this.id = UUID.randomUUID().toString(); + this.name = "terminalName"; + this.requesterSpecifiedId = "terminalNameExtra"; + this.user = new JSONObject(); + this.user.put("id", UUID.randomUUID().toString()); + this.user.put("name", "userName"); + this.userName = this.user.getString("name"); + } + + @Test + public void testRefreshFromServer() throws InterruptedException, RequestError { + JSONObject jsonResponse = new JSONObject(); + jsonResponse.put("id", id); + jsonResponse.put("name", name); + jsonResponse.put("name_extra", requesterSpecifiedId); + jsonResponse.put("user", user); + UserTerminal terminal = new UserTerminal(jsonResponse); + + JSONObject newJsonResponse = jsonResponse; + newJsonResponse.remove("name"); + jsonResponse.put("name", "terminalNameChanged"); + newJsonResponse.remove("name_extra"); + jsonResponse.put("name_extra", "terminalNameExtraChanged"); + JSONObject newUser = newJsonResponse.getJSONObject("user"); + newUser.remove("name"); + newUser.put("name", "userNameChanged"); + + HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + assertEquals(terminal.id, id); + assertEquals(terminal.name, name); + assertEquals(terminal.requesterSpecifiedId, requesterSpecifiedId); + assertEquals(terminal.user.name, userName); + + terminal.refresh_from_server(toopherAPI); + + assertEquals(terminal.id, id); + assertEquals(terminal.name, "terminalNameChanged"); + assertEquals(terminal.requesterSpecifiedId, "terminalNameExtraChanged"); + assertEquals(terminal.user.name, "userNameChanged"); + } +} From 1e5a66667eeae1b97cbcb7a75ea9bdec41171af8 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 17:33:51 -0600 Subject: [PATCH 043/195] Remove raw from Pairing --- src/main/java/com/toopher/Pairing.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index c3f8713..7a6974d 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -29,12 +29,6 @@ public class Pairing extends ApiResponseObject { */ public User user; - /** - * Contains the raw JSONObject - */ - public JSONObject raw; - - @Override public String toString() { return String.format("[Pairing: id=%s; userId=%s, userName=%s, pending=%b, enabled=%b]", id, @@ -48,7 +42,6 @@ public Pairing(JSONObject json) throws JSONException { this.enabled = json.getBoolean("enabled"); this.pending = json.getBoolean("pending"); this.user = new User(json.getJSONObject("user")); - this.raw = json; } From b8a82dc9d1c230f42df30b06a4cfd5264085b42e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 26 Jan 2015 17:48:48 -0600 Subject: [PATCH 044/195] Add Pairing.refresh_from_server() and update() --- src/main/java/com/toopher/Pairing.java | 12 ++++ src/test/java/com/toopher/TestPairing.java | 67 ++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 src/test/java/com/toopher/TestPairing.java diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index 7a6974d..e1cb6d7 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -44,5 +44,17 @@ public Pairing(JSONObject json) throws JSONException { this.user = new User(json.getJSONObject("user")); } + public void refreshFromServer(ToopherAPI api) throws RequestError { + String endpoint = "pairings/{0}".format(id); + JSONObject result = api.advanced.raw.get(endpoint); + update(result); + } + + public void update(JSONObject jsonResponse) { + this.enabled = jsonResponse.getBoolean("enabled"); + this.pending = jsonResponse.getBoolean("pending"); + this.user.update(jsonResponse.getJSONObject("user")); + } + } diff --git a/src/test/java/com/toopher/TestPairing.java b/src/test/java/com/toopher/TestPairing.java new file mode 100644 index 0000000..1a42329 --- /dev/null +++ b/src/test/java/com/toopher/TestPairing.java @@ -0,0 +1,67 @@ +package com.toopher; + +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; + +import java.net.URI; +import java.util.UUID; + +import static org.junit.Assert.*; + + +/** + * Created by graceyim on 1/26/15. + */ +public class TestPairing { + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; + + private String id; + private JSONObject user; + private String userId; + private String userName; + private JSONObject jsonResponse; + + @Before + public void setUp() { + this.id = UUID.randomUUID().toString(); + this.user = new JSONObject(); + this.user.put("id", UUID.randomUUID().toString()); + this.user.put("name", "userName"); + this.userId = user.getString("id"); + this.userName = user.getString("name"); + this.jsonResponse = new JSONObject(); + this.jsonResponse.put("id", id); + this.jsonResponse.put("enabled", true); + this.jsonResponse.put("pending", false); + this.jsonResponse.put("user", user); + } + + @Test + public void testRefreshFromServer() throws InterruptedException, RequestError { + Pairing pairing = new Pairing(jsonResponse); + + JSONObject newJsonResponse = jsonResponse; + JSONObject newUser = newJsonResponse.getJSONObject("user"); + newUser.remove("name"); + newUser.put("name", "userNameChanged"); + newJsonResponse.remove("enabled"); + newJsonResponse.put("enabled", false); + + HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + assertEquals(pairing.id, id); + assertEquals(pairing.user.name, userName); + assertTrue(pairing.enabled); + assertFalse(pairing.pending); + + pairing.refreshFromServer(toopherAPI); + + assertEquals(pairing.id, id); + assertEquals(pairing.user.name, "userNameChanged"); + assertFalse(pairing.enabled); + assertFalse(pairing.pending); + } + +} From 810075d0e303ffcb362e5d82a713f3e242c56119 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 27 Jan 2015 10:38:31 -0600 Subject: [PATCH 045/195] Make update() private in AuthenticationRequest and Pairing --- src/main/java/com/toopher/AuthenticationRequest.java | 2 +- src/main/java/com/toopher/Pairing.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index 861930b..4c35a7d 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -96,7 +96,7 @@ public void refresh_from_server(ToopherAPI api) throws RequestError { update(result); } - public void update(JSONObject jsonResponse) { + private void update(JSONObject jsonResponse) { this.pending = jsonResponse.getBoolean("pending"); this.granted = jsonResponse.getBoolean("granted"); this.automated = jsonResponse.getBoolean("automated"); diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index e1cb6d7..2221285 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -50,7 +50,7 @@ public void refreshFromServer(ToopherAPI api) throws RequestError { update(result); } - public void update(JSONObject jsonResponse) { + private void update(JSONObject jsonResponse) { this.enabled = jsonResponse.getBoolean("enabled"); this.pending = jsonResponse.getBoolean("pending"); this.user.update(jsonResponse.getJSONObject("user")); From 0f2832e12d5b5bd03f7de0750b4ca7103fda2eca Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 27 Jan 2015 10:51:16 -0600 Subject: [PATCH 046/195] Change DEFAULT_TTL to 300 --- src/main/java/com/toopher/ToopherIframe.java | 2 +- src/test/java/com/toopher/TestToopherIframe.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/toopher/ToopherIframe.java b/src/main/java/com/toopher/ToopherIframe.java index cd41bc6..9f84322 100644 --- a/src/main/java/com/toopher/ToopherIframe.java +++ b/src/main/java/com/toopher/ToopherIframe.java @@ -45,7 +45,7 @@ public SignatureValidationError(String message, Exception cause) { /** * Default amount of time that iframe requests are valid (seconds) */ - private static final long DEFAULT_TTL = 10L; + private static final long DEFAULT_TTL = 300L; private static final String DEFAULT_BASE_URI = "https://api.toopher.com/v1/"; diff --git a/src/test/java/com/toopher/TestToopherIframe.java b/src/test/java/com/toopher/TestToopherIframe.java index ab244e9..d5db6c7 100644 --- a/src/test/java/com/toopher/TestToopherIframe.java +++ b/src/test/java/com/toopher/TestToopherIframe.java @@ -37,7 +37,7 @@ public void setUp() { public void testGetAuthenticationUrl(){ ToopherIframe.setDateOverride(TEST_DATE); ToopherIframe.setNonceOverride(OAUTH_NONCE); - String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1010&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=1qBrA0wErtYCrzqQLwYqUDoynXs%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN)); } @@ -86,7 +86,7 @@ public void testGetAuthenticationUrlWithOptionalArgsAndExtras() { public void testGetUserManagementUrl() { ToopherIframe.setDateOverride(TEST_DATE); ToopherIframe.setNonceOverride(OAUTH_NONCE); - String expected = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1010&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=aq1kavm7iBOXNPndjKLnrI5rEXU%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + String expected = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; assertEquals(expected, iframeApi.getUserManagementUrl("jdoe", "jdoe@example.com")); } From 75d01cd47d922c56f9ba54790155dadc96c456ec Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 27 Jan 2015 11:25:40 -0600 Subject: [PATCH 047/195] Add Pairing.getResetLink() --- src/main/java/com/toopher/Pairing.java | 13 +++++++++ src/main/java/com/toopher/ToopherAPI.java | 4 +++ src/test/java/com/toopher/TestPairing.java | 34 ++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index 2221285..8b665ef 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -3,6 +3,9 @@ import org.json.JSONException; import org.json.JSONObject; +import java.util.HashMap; +import java.util.Map; + /** * Provides information about the status of a pairing request * @@ -57,4 +60,14 @@ private void update(JSONObject jsonResponse) { } + public String getResetLink(ToopherAPI api) throws RequestError { + Map extras = new HashMap(); + return getResetLink(api, extras); + } + + public String getResetLink(ToopherAPI api, Map extras) throws RequestError { + String endpoint = "pairings/{0}/generate_reset_link".format(id); + JSONObject result = api.advanced.raw.post(endpoint); + return result.getString("url"); + } } diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index f70bbef..c8d0e1c 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -651,6 +651,10 @@ public T get(String endpoint, List params, Map T post(String endpoint) throws RequestError { + return post(endpoint, null, null); + } + public T post(String endpoint, List params, Map extras) throws RequestError { HttpPost post = new HttpPost(); if (extras != null && extras.size() > 0) { diff --git a/src/test/java/com/toopher/TestPairing.java b/src/test/java/com/toopher/TestPairing.java index 1a42329..6cc34c6 100644 --- a/src/test/java/com/toopher/TestPairing.java +++ b/src/test/java/com/toopher/TestPairing.java @@ -5,6 +5,8 @@ import org.junit.Test; import java.net.URI; +import java.util.HashMap; +import java.util.Map; import java.util.UUID; import static org.junit.Assert.*; @@ -64,4 +66,36 @@ public void testRefreshFromServer() throws InterruptedException, RequestError { assertFalse(pairing.pending); } + @Test + public void testGetResetLink() throws InterruptedException, RequestError { + Pairing pairing = new Pairing(jsonResponse); + + JSONObject urlJsonResponse = new JSONObject(); + urlJsonResponse.put("url", "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); + + HttpClientMock httpClient = new HttpClientMock(200, urlJsonResponse.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + String resetLink = pairing.getResetLink(toopherAPI); + + assertEquals(resetLink, "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); + } + + @Test + public void testGetResetLinkWithExtras() throws InterruptedException, RequestError { + Pairing pairing = new Pairing(jsonResponse); + + JSONObject urlJsonResponse = new JSONObject(); + urlJsonResponse.put("url", "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); + + HttpClientMock httpClient = new HttpClientMock(200, urlJsonResponse.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + Map extras = new HashMap(); + extras.put("security_question", "is this a test?"); + extras.put("security_answer", "yes!"); + String resetLink = pairing.getResetLink(toopherAPI, extras); + + assertEquals(resetLink, "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); + } } From d914a074f40efdd107890f39676389b0df93b42e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 27 Jan 2015 12:23:42 -0600 Subject: [PATCH 048/195] Add Pairing object to test setUp() --- src/test/java/com/toopher/TestPairing.java | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/src/test/java/com/toopher/TestPairing.java b/src/test/java/com/toopher/TestPairing.java index 6cc34c6..3304e9c 100644 --- a/src/test/java/com/toopher/TestPairing.java +++ b/src/test/java/com/toopher/TestPairing.java @@ -23,6 +23,7 @@ public class TestPairing { private String userId; private String userName; private JSONObject jsonResponse; + private Pairing pairing; @Before public void setUp() { @@ -32,17 +33,17 @@ public void setUp() { this.user.put("name", "userName"); this.userId = user.getString("id"); this.userName = user.getString("name"); + this.jsonResponse = new JSONObject(); - this.jsonResponse.put("id", id); - this.jsonResponse.put("enabled", true); - this.jsonResponse.put("pending", false); - this.jsonResponse.put("user", user); + jsonResponse.put("id", id); + jsonResponse.put("enabled", true); + jsonResponse.put("pending", false); + jsonResponse.put("user", user); + this.pairing = new Pairing(jsonResponse); } @Test public void testRefreshFromServer() throws InterruptedException, RequestError { - Pairing pairing = new Pairing(jsonResponse); - JSONObject newJsonResponse = jsonResponse; JSONObject newUser = newJsonResponse.getJSONObject("user"); newUser.remove("name"); @@ -68,8 +69,6 @@ public void testRefreshFromServer() throws InterruptedException, RequestError { @Test public void testGetResetLink() throws InterruptedException, RequestError { - Pairing pairing = new Pairing(jsonResponse); - JSONObject urlJsonResponse = new JSONObject(); urlJsonResponse.put("url", "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); @@ -83,8 +82,6 @@ public void testGetResetLink() throws InterruptedException, RequestError { @Test public void testGetResetLinkWithExtras() throws InterruptedException, RequestError { - Pairing pairing = new Pairing(jsonResponse); - JSONObject urlJsonResponse = new JSONObject(); urlJsonResponse.put("url", "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); From 24a1c17be1667d86024bdf5fd86f694acad1cd09 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 27 Jan 2015 12:24:00 -0600 Subject: [PATCH 049/195] Add Pairing.emailResetLink() --- src/main/java/com/toopher/Pairing.java | 15 ++++++++++++++ src/test/java/com/toopher/TestPairing.java | 24 ++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index 8b665ef..e95d876 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -1,9 +1,13 @@ package com.toopher; +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; /** @@ -70,4 +74,15 @@ public String getResetLink(ToopherAPI api, Map extras) throws Re JSONObject result = api.advanced.raw.post(endpoint); return result.getString("url"); } + + public void emailResetLink(ToopherAPI api, String email) throws RequestError { + emailResetLink(api, email, null); + } + + public void emailResetLink(ToopherAPI api, String email, Map extras) throws RequestError { + String endpoint = "pairings/{0}/send_reset_link".format(id); + List params = new ArrayList(); + params.add(new BasicNameValuePair("reset_email", email)); + api.advanced.raw.post(endpoint, params, extras); + } } diff --git a/src/test/java/com/toopher/TestPairing.java b/src/test/java/com/toopher/TestPairing.java index 3304e9c..bdab681 100644 --- a/src/test/java/com/toopher/TestPairing.java +++ b/src/test/java/com/toopher/TestPairing.java @@ -95,4 +95,28 @@ public void testGetResetLinkWithExtras() throws InterruptedException, RequestErr assertEquals(resetLink, "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); } + + @Test + public void testEmailResetLink() throws InterruptedException, RequestError { + HttpClientMock httpClient = new HttpClientMock(201, "[]"); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + pairing.emailResetLink(toopherAPI, "email"); + assertEquals(httpClient.getLastCalledMethod(), "POST"); + assertEquals(httpClient.getLastCalledData("reset_email"), "email"); + } + + @Test + public void testEmailResetLinkWithExtras() throws InterruptedException, RequestError { + HttpClientMock httpClient = new HttpClientMock(201, "[]"); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + Map extras = new HashMap(); + extras.put("one_extra", "one_extra"); + pairing.emailResetLink(toopherAPI, "email", extras); + assertEquals(httpClient.getLastCalledMethod(), "POST"); + assertEquals(httpClient.getLastCalledData("reset_email"), "email"); + assertEquals(httpClient.getLastCalledData("one_extra"), "one_extra"); + + } } From 8d5be4114395333f23f0fcdff42f40cc8b83653b Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 29 Jan 2015 11:58:46 -0600 Subject: [PATCH 050/195] Add extras to params in Pairing.getResetLink() --- src/main/java/com/toopher/Pairing.java | 8 +++++++- src/main/java/com/toopher/ToopherAPI.java | 4 ++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index e95d876..6c337af 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -70,8 +70,14 @@ public String getResetLink(ToopherAPI api) throws RequestError { } public String getResetLink(ToopherAPI api, Map extras) throws RequestError { + List params = new ArrayList(); + + for (Map.Entry entry : extras.entrySet()) { + params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + String endpoint = "pairings/{0}/generate_reset_link".format(id); - JSONObject result = api.advanced.raw.post(endpoint); + JSONObject result = api.advanced.raw.post(endpoint, params); return result.getString("url"); } diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index c8d0e1c..3124511 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -655,6 +655,10 @@ public T post(String endpoint) throws RequestError { return post(endpoint, null, null); } + public T post(String endpoint, List params) throws RequestError { + return post(endpoint, params, null); + } + public T post(String endpoint, List params, Map extras) throws RequestError { HttpPost post = new HttpPost(); if (extras != null && extras.size() > 0) { From 8fb9adc9b5d72fca39bf22e031e383256b108db8 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 29 Jan 2015 17:14:18 -0600 Subject: [PATCH 051/195] Use ApiRawRequester.post(endpoint, params) when extras are null --- src/main/java/com/toopher/ToopherAPI.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 3124511..5796278 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -218,7 +218,7 @@ public Pairing pair( String userName, String pairingPhraseOrNum, Map params = new ArrayList(); params.add(new BasicNameValuePair("otp", OTP)); - JSONObject json = advanced.raw.post(endpoint, params, null); + JSONObject json = advanced.raw.post(endpoint, params); try { return new AuthenticationRequest(json); } catch (Exception e) { @@ -336,7 +336,7 @@ public void assignUserFriendlyNameToTerminal(String userName, String terminalNam params.add(new BasicNameValuePair("name", terminalName)); params.add(new BasicNameValuePair("name_extra", terminalNameExtra)); - advanced.raw.post(endpoint, params, null); + advanced.raw.post(endpoint, params); } /** @@ -380,7 +380,7 @@ public void setToopherEnabledForUser(String userName, boolean toopherEnabled) th params = new ArrayList(); params.add(new BasicNameValuePair("disable_toopher_auth", toopherEnabled ? "false" : "true")); - advanced.raw.post(String.format(updateEndpoint, userId), params, null); + advanced.raw.post(String.format(updateEndpoint, userId), params); } private static ResponseHandler jsonHandler = new ResponseHandler() { @@ -553,7 +553,7 @@ public User create(String userName, Map extras) throws RequestEr } try { - result = advanced.raw.post(endpoint, params, null); + result = advanced.raw.post(endpoint, params); } catch (Exception e) { throw new RequestError(e); } From 5849894226d5b4199311b3694ba8b654bb7fd099 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 29 Jan 2015 17:15:20 -0600 Subject: [PATCH 052/195] Add ApiRawRequester.get(endpoint, params) for when extras are null --- src/main/java/com/toopher/ToopherAPI.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 5796278..97c029f 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -357,7 +357,7 @@ public void setToopherEnabledForUser(String userName, boolean toopherEnabled) th List params = new ArrayList(); params.add(new BasicNameValuePair("name", userName)); - JSONArray result = advanced.raw.get(searchEndpoint, params, null); + JSONArray result = advanced.raw.get(searchEndpoint, params); // user name should be a unique field per requester - if more than one object is returned, this is gonna be a problem if (result.length() > 1) { @@ -639,6 +639,10 @@ public T get(String endpoint) throws RequestError { return request(new HttpGet(), endpoint, null); } + public T get(String endpoint, List params) throws RequestError { + return request(new HttpGet(), endpoint, params); + } + public T get(String endpoint, List params, Map extras) throws RequestError { if (params == null) { params = new ArrayList(); From 7f4237970a6ef4a13ada31baa4e217bf7ca9e674 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 29 Jan 2015 17:18:06 -0600 Subject: [PATCH 053/195] Update HttpClientMock and add ResponseMock to mock 2 responses to test Users.getByName --- src/main/java/com/toopher/ToopherAPI.java | 10 +--- src/test/java/com/toopher/HttpClientMock.java | 50 +++++++++++++++---- src/test/java/com/toopher/ResponseMock.java | 22 ++++++++ src/test/java/com/toopher/TestToopherAPI.java | 48 ++++++++++-------- 4 files changed, 91 insertions(+), 39 deletions(-) create mode 100644 src/test/java/com/toopher/ResponseMock.java diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 97c029f..319fb23 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -593,16 +593,10 @@ public User getById(String userId) throws RequestError { */ public User getByName(String name) throws RequestError { final String endpoint = "users"; - JSONArray result; List params = new ArrayList(); - params.add(new BasicNameValuePair("user_name", name)); - try { - result = (JSONArray) advanced.raw.get(endpoint, params, null); - } catch (Exception e) { - throw new RequestError(e); - } - + params.add(new BasicNameValuePair("name", name)); + JSONArray result = (JSONArray) advanced.raw.get(endpoint, params); if (result.length() > 1) { throw new RequestError("More than one user with name {0}".format(name)); diff --git a/src/test/java/com/toopher/HttpClientMock.java b/src/test/java/com/toopher/HttpClientMock.java index b13927b..634f0e7 100644 --- a/src/test/java/com/toopher/HttpClientMock.java +++ b/src/test/java/com/toopher/HttpClientMock.java @@ -18,6 +18,9 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.Semaphore; @Ignore @@ -28,6 +31,8 @@ public class HttpClientMock extends DefaultHttpClient { private HttpUriRequest lastRequest; private int expectedResponseStatus; private String expectedResponseBody; + private Map expectedUriResponses; + private java.net.URI lastURI; public HttpClientMock(int responseStatus, String responseBody) throws InterruptedException { this.expectedResponseStatus = responseStatus; @@ -36,6 +41,15 @@ public HttpClientMock(int responseStatus, String responseBody) throws Interrupte done.acquire(); } + public HttpClientMock(Map responses) throws InterruptedException { + expectedUriResponses = new HashMap(); + for (URI url : responses.keySet()) { + expectedUriResponses.put(url, responses.get(url)); + } + done = new Semaphore(1); + done.acquire(); + } + public String getLastCalledMethod() { if (lastRequest != null) { return lastRequest.getMethod(); @@ -50,8 +64,26 @@ public String getLastCalledData(String key) { return null; } + public URI getLastCalledEndpoint() { + return lastURI; + } + + public String getExpectedResponse() { + if (expectedUriResponses != null) { + return expectedUriResponses.get(lastURI).getResponseBody(); + } + return null; + } + + public int getExpectedResponseStatus() { + if (expectedUriResponses != null) { + return expectedUriResponses.get(lastURI).getStatusCode(); + } + return -1; + } + @Override - public T execute(HttpUriRequest req, ResponseHandler responseHandler) { + public T execute(HttpUriRequest req, ResponseHandler responseHandler) throws IOException { lastRequest = req; if (req instanceof HttpPost){ try { @@ -65,22 +97,22 @@ public T execute(HttpUriRequest req, ResponseHandler responseHa } else { lastParams = req.getParams(); } - HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, expectedResponseStatus, null)); BasicHttpEntity entity = new BasicHttpEntity(); + if ( req == lastRequest && expectedUriResponses != null) { + expectedResponseBody = expectedUriResponses.get(req.getURI()).getResponseBody(); + expectedResponseStatus = expectedUriResponses.get(req.getURI()).getStatusCode(); + } try { entity.setContent(new ByteArrayInputStream(expectedResponseBody.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } + HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, expectedResponseStatus, null)); resp.setEntity(entity); - + lastURI = req.getURI(); T result; - try { - result = responseHandler.handleResponse(resp); - } catch (IOException e) { - result = null; - e.printStackTrace(); - } + result = responseHandler.handleResponse(resp); + done.release(); return result; } diff --git a/src/test/java/com/toopher/ResponseMock.java b/src/test/java/com/toopher/ResponseMock.java new file mode 100644 index 0000000..68ce091 --- /dev/null +++ b/src/test/java/com/toopher/ResponseMock.java @@ -0,0 +1,22 @@ +package com.toopher; + +/** + * Created by graceyim on 1/29/15. + */ +public class ResponseMock { + private int statusCode; + private String jsonResponse; + + public ResponseMock(int statusCode, String jsonResponse) { + this.statusCode = statusCode; + this.jsonResponse = jsonResponse; + } + + public int getStatusCode() { + return statusCode; + } + + public String getResponseBody() { + return jsonResponse; + } +} diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index aa45c25..ffc7e35 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -293,28 +293,32 @@ public void testAdvancedUsersGetById() throws InterruptedException, RequestError assertFalse(user.enabled); } -// TODO: Need to attach 2 JSON response objects -// @Test -// public void testAdvancedUsersGetByName() throws InterruptedException, RequestError { -// JSONObject jsonResponse = new JSONObject(); -// jsonResponse.put("id", id); -// jsonResponse.put("name", name); -// jsonResponse.put("enabled", true); -// jsonResponse.put("disable_toopher_auth", false); -// JSONArray jsonArray = new JSONArray(); -// jsonArray.put(jsonResponse); -// -// HttpClientMock httpClient = new HttpClientMock(200, jsonArray.toString()); -// -// ToopherAPI toopherAPI = new ToopherAPI("key", "secret", -// createURI(DEFAULT_BASE_URL), httpClient); -// User user = toopherAPI.advanced.users.getByName(name); -// -// assertEquals(httpClient.getLastCalledMethod(), "GET"); -// assertEquals(user.id, id); -// assertEquals(user.name, name); -// assertTrue(user.enabled); -// } + @Test + public void testAdvancedUsersGetByName() throws InterruptedException, RequestError { + JSONObject usersJsonResponse = new JSONObject(); + usersJsonResponse.put("id", id); + usersJsonResponse.put("name", name); + usersJsonResponse.put("enabled", true); + usersJsonResponse.put("disable_toopher_auth", false); + JSONArray usersJsonArray = new JSONArray(); + usersJsonArray.put(usersJsonResponse); + + Map expectedUriResponses = new HashMap(); + expectedUriResponses.put(createURI("https://api.toopher.test/v1/users/" + id), new ResponseMock(200, usersJsonResponse.toString())); + expectedUriResponses.put(createURI("https://api.toopher.test/v1/users?name=name"), new ResponseMock(200, usersJsonArray.toString())); + + HttpClientMock httpClient = new HttpClientMock(expectedUriResponses); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + User user = toopherAPI.advanced.users.getByName(name); + String actualResponse = httpClient.getExpectedResponse(); + String expectedResponse = usersJsonResponse.toString(); + + assertEquals(expectedResponse, actualResponse); + assertEquals(user.id, id); + assertEquals(user.name, name); + assertTrue(user.enabled); + } @Test public void testAdvancedUserTerminalsGetById() throws InterruptedException, RequestError { From a5b13dfc8dcb054e8cbcfe8cde5b74a9eb96aedb Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 29 Jan 2015 17:20:10 -0600 Subject: [PATCH 054/195] Rename endpoint for UserTerminal.getById to be consistent with other endpoints --- src/main/java/com/toopher/ToopherAPI.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 319fb23..ba57b8b 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -621,7 +621,7 @@ class UserTerminals { * Thrown when an exceptional condition is encountered */ public UserTerminal getById(String terminalId) throws RequestError { - final String endpoint = String.format("/user_terminals/%s", terminalId); + final String endpoint = String.format("user_terminals/%s", terminalId); JSONObject result = advanced.raw.get(endpoint); return new UserTerminal(result); } From 1dc677c29d7ccb551a903f4a6d8f4d0e459b64cb Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 29 Jan 2015 17:21:00 -0600 Subject: [PATCH 055/195] Rename DEFAULT_BASE_URL endpoint in tests to be consistent with ToopherAPI url format --- src/test/java/com/toopher/TestToopherAPI.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index ffc7e35..ec84277 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -16,7 +16,7 @@ import static org.junit.Assert.*; public class TestToopherAPI { - private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; private String id; private String name; From c75cacb5153b20126f8190b36866a30dc5db2c0a Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 3 Feb 2015 14:29:25 -0600 Subject: [PATCH 056/195] Add reason_code to AuthenticationRequest --- src/main/java/com/toopher/AuthenticationRequest.java | 7 +++++++ src/test/java/com/toopher/TestAuthenticationRequest.java | 4 ++++ src/test/java/com/toopher/TestToopherAPI.java | 8 ++++++++ 3 files changed, 19 insertions(+) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index 4c35a7d..ab4f53f 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -40,6 +40,11 @@ public class AuthenticationRequest extends ApiResponseObject { */ public String reason; + /** + * Indicates the code associated with the reason for the request's outcome + */ + public int reasonCode; + /** * Contains the unique id and descriptive name for the terminal * associated with the request @@ -66,6 +71,7 @@ public AuthenticationRequest(JSONObject json) throws JSONException{ this.granted = json.getBoolean("granted"); this.automated = json.getBoolean("automated"); this.reason = json.getString("reason"); + this.reasonCode = json.getInt("reason_code"); this.terminal = new UserTerminal(json.getJSONObject("terminal")); this.action = new Action(json.getJSONObject("action")); this.user = terminal.user; @@ -101,6 +107,7 @@ private void update(JSONObject jsonResponse) { this.granted = jsonResponse.getBoolean("granted"); this.automated = jsonResponse.getBoolean("automated"); this.reason = jsonResponse.getString("reason"); + this.reasonCode = jsonResponse.getInt("reason_code"); this.terminal.update(jsonResponse.getJSONObject("terminal")); this.action.update(jsonResponse.getJSONObject("action")); this.user.update(jsonResponse.getJSONObject("user")); diff --git a/src/test/java/com/toopher/TestAuthenticationRequest.java b/src/test/java/com/toopher/TestAuthenticationRequest.java index 9803142..e68c7a1 100644 --- a/src/test/java/com/toopher/TestAuthenticationRequest.java +++ b/src/test/java/com/toopher/TestAuthenticationRequest.java @@ -20,6 +20,7 @@ public class TestAuthenticationRequest { private String id; private String reason; + private int reasonCode; private JSONObject terminal; private JSONObject action; private JSONObject user; @@ -29,6 +30,7 @@ public class TestAuthenticationRequest { public void setUp() { this.id = UUID.randomUUID().toString(); this.reason = "it is a test"; + this.reasonCode = 111; this.user = new JSONObject(); this.user.put("id", UUID.randomUUID().toString()); this.user.put("name", "userName"); @@ -46,6 +48,7 @@ public void setUp() { jsonResponse.put("granted", true); jsonResponse.put("automated", true); jsonResponse.put("reason", reason); + jsonResponse.put("reason_code", reasonCode); jsonResponse.put("user", user); jsonResponse.put("terminal", terminal); jsonResponse.put("action", action); @@ -84,6 +87,7 @@ public void testRefreshFromServer() throws InterruptedException, RequestError { authenticationRequest.refresh_from_server(toopherAPI); assertEquals(authenticationRequest.id, id); + assertEquals(authenticationRequest.reasonCode, reasonCode); assertFalse(authenticationRequest.pending); assertFalse(authenticationRequest.granted); } diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index ec84277..d6379fa 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -27,6 +27,7 @@ public class TestToopherAPI { private String actionId; private String actionName; private String reason; + private int reasonCode; private JSONObject terminal; private String terminalId; private String terminalName; @@ -47,6 +48,7 @@ public void setUp() { this.actionId = this.action.getString("id"); this.actionName = this.action.getString("name"); this.reason = "it is a test"; + this.reasonCode = 111; this.terminal = new JSONObject(); this.terminal.put("id", UUID.randomUUID().toString()); this.terminal.put("name", "terminalName"); @@ -152,6 +154,7 @@ public void testCreateAuthenticationRequestWithPairingId() throws InterruptedExc response.put("granted", true); response.put("automated", false); response.put("reason", reason); + response.put("reason_code", reasonCode); response.put("terminal", terminal); response.put("action", action); @@ -167,6 +170,7 @@ public void testCreateAuthenticationRequestWithPairingId() throws InterruptedExc assertTrue(authenticationRequest.granted); assertFalse(authenticationRequest.automated); assertEquals(authenticationRequest.reason, reason); + assertEquals(authenticationRequest.reasonCode, reasonCode); assertEquals(authenticationRequest.terminal.id, terminalId); assertEquals(authenticationRequest.terminal.name, terminalName); assertEquals(authenticationRequest.action.id, actionId); @@ -181,6 +185,7 @@ public void testCreateAuthenticationRequestWithUsername() throws InterruptedExce response.put("granted", true); response.put("automated", false); response.put("reason", reason); + response.put("reason_code", reasonCode); response.put("terminal", terminal); response.put("action", action); @@ -196,6 +201,7 @@ public void testCreateAuthenticationRequestWithUsername() throws InterruptedExce assertTrue(authenticationRequest.granted); assertFalse(authenticationRequest.automated); assertEquals(authenticationRequest.reason, reason); + assertEquals(authenticationRequest.reasonCode, reasonCode); assertEquals(authenticationRequest.terminal.id, terminalId); assertEquals(authenticationRequest.terminal.name, terminalName); assertEquals(authenticationRequest.action.id, actionId); @@ -212,6 +218,7 @@ public void testAdvancedAuthenticationRequestsGetById() throws InterruptedExcept jsonResponse.put("granted", true); jsonResponse.put("automated", false); jsonResponse.put("reason", reason); + jsonResponse.put("reason_code", reasonCode); jsonResponse.put("action", action); jsonResponse.put("terminal", terminal); @@ -224,6 +231,7 @@ public void testAdvancedAuthenticationRequestsGetById() throws InterruptedExcept assertEquals(httpClient.getLastCalledMethod(), "GET"); assertEquals(authenticationRequest.id, id); assertEquals(authenticationRequest.reason, reason); + assertEquals(authenticationRequest.reasonCode, reasonCode); assertEquals(authenticationRequest.terminal.id, terminalId); assertEquals(authenticationRequest.terminal.name, terminalName); assertEquals(authenticationRequest.terminal.user.id, userId); From 3acc683c53be4def3f1daecc517017cd1af4eb7b Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 3 Feb 2015 15:10:18 -0600 Subject: [PATCH 057/195] Use camelCase, not snake_case --- src/main/java/com/toopher/AuthenticationRequest.java | 4 ++-- src/test/java/com/toopher/TestAuthenticationRequest.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index ab4f53f..9d7f1ba 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -83,7 +83,7 @@ public String toString() { id, pending, granted, automated, reason, terminal.id, terminal.name); } - public void authenticate_with_otp(ToopherAPI api, String otp) throws RequestError { + public void authenticateWithOtp(ToopherAPI api, String otp) throws RequestError { String endpoint = "authentication_requests/{0}/otp_auth".format(id); List params = new ArrayList(); params.add(new BasicNameValuePair("otp", otp)); @@ -96,7 +96,7 @@ public void authenticate_with_otp(ToopherAPI api, String otp) throws RequestErro } } - public void refresh_from_server(ToopherAPI api) throws RequestError { + public void refreshFromServer(ToopherAPI api) throws RequestError { String endpoint = "authentication_requests{0}".format(id); JSONObject result = api.advanced.raw.get(endpoint); update(result); diff --git a/src/test/java/com/toopher/TestAuthenticationRequest.java b/src/test/java/com/toopher/TestAuthenticationRequest.java index e68c7a1..e99f6ff 100644 --- a/src/test/java/com/toopher/TestAuthenticationRequest.java +++ b/src/test/java/com/toopher/TestAuthenticationRequest.java @@ -65,7 +65,7 @@ public void testAuthenticateWithOtp() throws InterruptedException, RequestError HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); - authenticationRequest.authenticate_with_otp(toopherAPI, "testOtp"); + authenticationRequest.authenticateWithOtp(toopherAPI, "testOtp"); assertEquals(authenticationRequest.id, id); assertEquals(authenticationRequest.reason, "it is a changed test"); @@ -84,7 +84,7 @@ public void testRefreshFromServer() throws InterruptedException, RequestError { HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); - authenticationRequest.refresh_from_server(toopherAPI); + authenticationRequest.refreshFromServer(toopherAPI); assertEquals(authenticationRequest.id, id); assertEquals(authenticationRequest.reasonCode, reasonCode); From 87979983b828f30fee4e2246208b3acb53c5258b Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Tue, 3 Feb 2015 17:22:19 -0600 Subject: [PATCH 058/195] Add api to User(s), UserTerminal(s), AuthenticationRequest(s) and Pairing(s) --- .../com/toopher/AuthenticationRequest.java | 15 ++++-- src/main/java/com/toopher/Pairing.java | 25 +++++---- src/main/java/com/toopher/ToopherAPI.java | 52 ++++++++++++++----- src/main/java/com/toopher/User.java | 8 ++- src/main/java/com/toopher/UserTerminal.java | 8 +-- .../toopher/TestAuthenticationRequest.java | 12 ++--- src/test/java/com/toopher/TestPairing.java | 30 ++++++----- .../java/com/toopher/TestUserTerminal.java | 16 +++--- 8 files changed, 105 insertions(+), 61 deletions(-) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index 9d7f1ba..fbcf410 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -14,6 +14,10 @@ * */ public class AuthenticationRequest extends ApiResponseObject { + /** + * The ToopherAPI associated with this request + */ + public ToopherAPI api; /** * The unique id for the authentication request @@ -63,16 +67,17 @@ public class AuthenticationRequest extends ApiResponseObject { */ public Action action; - public AuthenticationRequest(JSONObject json) throws JSONException{ + public AuthenticationRequest(JSONObject json, ToopherAPI toopherAPI) throws JSONException{ super(json); - + + this.api = toopherAPI; this.id = json.getString("id"); this.pending = json.getBoolean("pending"); this.granted = json.getBoolean("granted"); this.automated = json.getBoolean("automated"); this.reason = json.getString("reason"); this.reasonCode = json.getInt("reason_code"); - this.terminal = new UserTerminal(json.getJSONObject("terminal")); + this.terminal = new UserTerminal(json.getJSONObject("terminal"), toopherAPI); this.action = new Action(json.getJSONObject("action")); this.user = terminal.user; } @@ -83,7 +88,7 @@ public String toString() { id, pending, granted, automated, reason, terminal.id, terminal.name); } - public void authenticateWithOtp(ToopherAPI api, String otp) throws RequestError { + public void authenticateWithOtp(String otp) throws RequestError { String endpoint = "authentication_requests/{0}/otp_auth".format(id); List params = new ArrayList(); params.add(new BasicNameValuePair("otp", otp)); @@ -96,7 +101,7 @@ public void authenticateWithOtp(ToopherAPI api, String otp) throws RequestError } } - public void refreshFromServer(ToopherAPI api) throws RequestError { + public void refreshFromServer() throws RequestError { String endpoint = "authentication_requests{0}".format(id); JSONObject result = api.advanced.raw.get(endpoint); update(result); diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index 6c337af..104c5f8 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -15,6 +15,11 @@ * */ public class Pairing extends ApiResponseObject { + /** + * The ToopherAPI associated with this pairing + */ + public ToopherAPI api; + /** * The unique id for the pairing request */ @@ -42,16 +47,17 @@ public String toString() { user.id, user.name, pending, enabled); } - public Pairing(JSONObject json) throws JSONException { + public Pairing(JSONObject json, ToopherAPI toopherAPI) throws JSONException { super(json); + this.api = toopherAPI; this.id = json.getString("id"); this.enabled = json.getBoolean("enabled"); this.pending = json.getBoolean("pending"); - this.user = new User(json.getJSONObject("user")); + this.user = new User(json.getJSONObject("user"), toopherAPI); } - public void refreshFromServer(ToopherAPI api) throws RequestError { + public void refreshFromServer() throws RequestError { String endpoint = "pairings/{0}".format(id); JSONObject result = api.advanced.raw.get(endpoint); update(result); @@ -63,13 +69,12 @@ private void update(JSONObject jsonResponse) { this.user.update(jsonResponse.getJSONObject("user")); } - - public String getResetLink(ToopherAPI api) throws RequestError { + public String getResetLink() throws RequestError { Map extras = new HashMap(); - return getResetLink(api, extras); + return getResetLink(extras); } - public String getResetLink(ToopherAPI api, Map extras) throws RequestError { + public String getResetLink(Map extras) throws RequestError { List params = new ArrayList(); for (Map.Entry entry : extras.entrySet()) { @@ -81,11 +86,11 @@ public String getResetLink(ToopherAPI api, Map extras) throws Re return result.getString("url"); } - public void emailResetLink(ToopherAPI api, String email) throws RequestError { - emailResetLink(api, email, null); + public void emailResetLink(String email) throws RequestError { + emailResetLink(email, null); } - public void emailResetLink(ToopherAPI api, String email, Map extras) throws RequestError { + public void emailResetLink(String email, Map extras) throws RequestError { String endpoint = "pairings/{0}/send_reset_link".format(id); List params = new ArrayList(); params.add(new BasicNameValuePair("reset_email", email)); diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index ba57b8b..9969d22 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -129,7 +129,7 @@ public ToopherAPI(String consumerKey, String consumerSecret, URI uri) { * The alternate HTTP client */ public ToopherAPI(String consumerKey, String consumerSecret, URI uri, HttpClient httpClient) { - this.advanced = new AdvancedApiUsageFactory(consumerKey, consumerSecret); + this.advanced = new AdvancedApiUsageFactory(consumerKey, consumerSecret, this); if (httpClient == null) { this.httpClient = new DefaultHttpClient(); HttpProtocolParams.setUserAgent(this.httpClient.getParams(), @@ -221,7 +221,7 @@ public Pairing pair( String userName, String pairingPhraseOrNum, Map extras) throws RequestEr throw new RequestError(e); } - return new User(result); + return new User(result, api); } /** @@ -576,7 +594,7 @@ public User getById(String userId) throws RequestError { JSONObject json = advanced.raw.get(endpoint); try { - return new User(json); + return new User(json, api); } catch (Exception e) { throw new RequestError(e); } @@ -610,6 +628,12 @@ public User getByName(String name) throws RequestError { } class UserTerminals { + public final ToopherAPI api; + + public UserTerminals(ToopherAPI toopherAPI) { + api = toopherAPI; + } + /** * Retrieve the current status of a user terminal by terminal id * @@ -623,7 +647,7 @@ class UserTerminals { public UserTerminal getById(String terminalId) throws RequestError { final String endpoint = String.format("user_terminals/%s", terminalId); JSONObject result = advanced.raw.get(endpoint); - return new UserTerminal(result); + return new UserTerminal(result, api); } } diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index bf701b9..e398cb7 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -7,6 +7,11 @@ * Created by graceyim on 1/22/15. */ public class User extends ApiResponseObject { + /** + * The ToopherAPI associated with this user + */ + public ToopherAPI api; + /** * The unique id for the user */ @@ -22,9 +27,10 @@ public class User extends ApiResponseObject { */ public boolean enabled; - public User (JSONObject json) throws JSONException { + public User (JSONObject json, ToopherAPI toopherAPI) throws JSONException { super(json); + this.api = toopherAPI; this.id = json.getString("id"); this.name = json.getString("name"); if (json.has("disable_toopher_auth")) { diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index 2e1519c..628be0e 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -7,20 +7,22 @@ * Created by graceyim on 1/22/15. */ public class UserTerminal extends ApiResponseObject { + public ToopherAPI api; public String id; public String name; public String requesterSpecifiedId; public User user; - public UserTerminal (JSONObject json) throws JSONException { + public UserTerminal (JSONObject json, ToopherAPI toopherAPI) throws JSONException { super(json); + this.api = toopherAPI; this.id = json.getString("id"); this.name = json.getString("name"); if (json.has("name_extra")) { this.requesterSpecifiedId = json.getString("name_extra"); } - this.user = new User(json.getJSONObject("user")); + this.user = new User(json.getJSONObject("user"), toopherAPI); } @Override @@ -29,7 +31,7 @@ public String toString() { id, name, requesterSpecifiedId, user.name, user.id); } - public void refresh_from_server(ToopherAPI api) throws RequestError { + public void refresh_from_server() throws RequestError { String endpoint = "user_terminals/{0}".format(id); JSONObject result = api.advanced.raw.get(endpoint); update(result); diff --git a/src/test/java/com/toopher/TestAuthenticationRequest.java b/src/test/java/com/toopher/TestAuthenticationRequest.java index e99f6ff..7f7a4ce 100644 --- a/src/test/java/com/toopher/TestAuthenticationRequest.java +++ b/src/test/java/com/toopher/TestAuthenticationRequest.java @@ -56,8 +56,6 @@ public void setUp() { @Test public void testAuthenticateWithOtp() throws InterruptedException, RequestError { - AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse); - JSONObject newJsonResponse = jsonResponse; newJsonResponse.remove("reason"); newJsonResponse.put("reason", "it is a changed test"); @@ -65,7 +63,9 @@ public void testAuthenticateWithOtp() throws InterruptedException, RequestError HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); - authenticationRequest.authenticateWithOtp(toopherAPI, "testOtp"); + + AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse, toopherAPI); + authenticationRequest.authenticateWithOtp("testOtp"); assertEquals(authenticationRequest.id, id); assertEquals(authenticationRequest.reason, "it is a changed test"); @@ -73,8 +73,6 @@ public void testAuthenticateWithOtp() throws InterruptedException, RequestError @Test public void testRefreshFromServer() throws InterruptedException, RequestError { - AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse); - JSONObject newJsonResponse = jsonResponse; newJsonResponse.remove("pending"); newJsonResponse.remove("granted"); @@ -84,7 +82,9 @@ public void testRefreshFromServer() throws InterruptedException, RequestError { HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); - authenticationRequest.refreshFromServer(toopherAPI); + + AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse, toopherAPI); + authenticationRequest.refreshFromServer(); assertEquals(authenticationRequest.id, id); assertEquals(authenticationRequest.reasonCode, reasonCode); diff --git a/src/test/java/com/toopher/TestPairing.java b/src/test/java/com/toopher/TestPairing.java index bdab681..2046413 100644 --- a/src/test/java/com/toopher/TestPairing.java +++ b/src/test/java/com/toopher/TestPairing.java @@ -39,32 +39,32 @@ public void setUp() { jsonResponse.put("enabled", true); jsonResponse.put("pending", false); jsonResponse.put("user", user); - this.pairing = new Pairing(jsonResponse); } @Test public void testRefreshFromServer() throws InterruptedException, RequestError { - JSONObject newJsonResponse = jsonResponse; - JSONObject newUser = newJsonResponse.getJSONObject("user"); - newUser.remove("name"); + JSONObject newResponse = new JSONObject(); + JSONObject newUser = new JSONObject(); newUser.put("name", "userNameChanged"); - newJsonResponse.remove("enabled"); - newJsonResponse.put("enabled", false); + newResponse.put("user", newUser); + newResponse.put("enabled", false); + newResponse.put("pending", true); - HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); + HttpClientMock httpClient = new HttpClientMock(200, newResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); + Pairing pairing = new Pairing(jsonResponse, toopherAPI); assertEquals(pairing.id, id); assertEquals(pairing.user.name, userName); assertTrue(pairing.enabled); assertFalse(pairing.pending); - pairing.refreshFromServer(toopherAPI); + pairing.refreshFromServer(); assertEquals(pairing.id, id); assertEquals(pairing.user.name, "userNameChanged"); assertFalse(pairing.enabled); - assertFalse(pairing.pending); + assertTrue(pairing.pending); } @Test @@ -75,7 +75,8 @@ public void testGetResetLink() throws InterruptedException, RequestError { HttpClientMock httpClient = new HttpClientMock(200, urlJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); - String resetLink = pairing.getResetLink(toopherAPI); + Pairing pairing = new Pairing(jsonResponse, toopherAPI); + String resetLink = pairing.getResetLink(); assertEquals(resetLink, "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); } @@ -91,7 +92,8 @@ public void testGetResetLinkWithExtras() throws InterruptedException, RequestErr Map extras = new HashMap(); extras.put("security_question", "is this a test?"); extras.put("security_answer", "yes!"); - String resetLink = pairing.getResetLink(toopherAPI, extras); + Pairing pairing = new Pairing(jsonResponse, toopherAPI); + String resetLink = pairing.getResetLink(extras); assertEquals(resetLink, "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); } @@ -101,7 +103,8 @@ public void testEmailResetLink() throws InterruptedException, RequestError { HttpClientMock httpClient = new HttpClientMock(201, "[]"); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); - pairing.emailResetLink(toopherAPI, "email"); + Pairing pairing = new Pairing(jsonResponse, toopherAPI); + pairing.emailResetLink("email"); assertEquals(httpClient.getLastCalledMethod(), "POST"); assertEquals(httpClient.getLastCalledData("reset_email"), "email"); } @@ -113,7 +116,8 @@ public void testEmailResetLinkWithExtras() throws InterruptedException, RequestE URI.create(DEFAULT_BASE_URL), httpClient); Map extras = new HashMap(); extras.put("one_extra", "one_extra"); - pairing.emailResetLink(toopherAPI, "email", extras); + Pairing pairing = new Pairing(jsonResponse, toopherAPI); + pairing.emailResetLink("email", extras); assertEquals(httpClient.getLastCalledMethod(), "POST"); assertEquals(httpClient.getLastCalledData("reset_email"), "email"); assertEquals(httpClient.getLastCalledData("one_extra"), "one_extra"); diff --git a/src/test/java/com/toopher/TestUserTerminal.java b/src/test/java/com/toopher/TestUserTerminal.java index 1b4ec5d..0e7e2c9 100644 --- a/src/test/java/com/toopher/TestUserTerminal.java +++ b/src/test/java/com/toopher/TestUserTerminal.java @@ -40,26 +40,24 @@ public void testRefreshFromServer() throws InterruptedException, RequestError { jsonResponse.put("name", name); jsonResponse.put("name_extra", requesterSpecifiedId); jsonResponse.put("user", user); - UserTerminal terminal = new UserTerminal(jsonResponse); - JSONObject newJsonResponse = jsonResponse; - newJsonResponse.remove("name"); - jsonResponse.put("name", "terminalNameChanged"); - newJsonResponse.remove("name_extra"); - jsonResponse.put("name_extra", "terminalNameExtraChanged"); - JSONObject newUser = newJsonResponse.getJSONObject("user"); - newUser.remove("name"); + JSONObject newJsonResponse = new JSONObject(); + newJsonResponse.put("name", "terminalNameChanged"); + newJsonResponse.put("name_extra", "terminalNameExtraChanged"); + JSONObject newUser = new JSONObject(); newUser.put("name", "userNameChanged"); + newJsonResponse.put("user", newUser); HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); + UserTerminal terminal = new UserTerminal(jsonResponse, toopherAPI); assertEquals(terminal.id, id); assertEquals(terminal.name, name); assertEquals(terminal.requesterSpecifiedId, requesterSpecifiedId); assertEquals(terminal.user.name, userName); - terminal.refresh_from_server(toopherAPI); + terminal.refresh_from_server(); assertEquals(terminal.id, id); assertEquals(terminal.name, "terminalNameChanged"); From 914f39016f482d8194967ff361a790427834813e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 09:18:08 -0600 Subject: [PATCH 059/195] Rename authenticateWithOtp to grantWithOtp --- src/main/java/com/toopher/AuthenticationRequest.java | 2 +- src/test/java/com/toopher/TestAuthenticationRequest.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index fbcf410..ec95d27 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -88,7 +88,7 @@ public String toString() { id, pending, granted, automated, reason, terminal.id, terminal.name); } - public void authenticateWithOtp(String otp) throws RequestError { + public void grantWithOtp(String otp) throws RequestError { String endpoint = "authentication_requests/{0}/otp_auth".format(id); List params = new ArrayList(); params.add(new BasicNameValuePair("otp", otp)); diff --git a/src/test/java/com/toopher/TestAuthenticationRequest.java b/src/test/java/com/toopher/TestAuthenticationRequest.java index 7f7a4ce..8ca5a53 100644 --- a/src/test/java/com/toopher/TestAuthenticationRequest.java +++ b/src/test/java/com/toopher/TestAuthenticationRequest.java @@ -55,7 +55,7 @@ public void setUp() { } @Test - public void testAuthenticateWithOtp() throws InterruptedException, RequestError { + public void testGrantWithOtp() throws InterruptedException, RequestError { JSONObject newJsonResponse = jsonResponse; newJsonResponse.remove("reason"); newJsonResponse.put("reason", "it is a changed test"); @@ -65,7 +65,7 @@ public void testAuthenticateWithOtp() throws InterruptedException, RequestError createURI(DEFAULT_BASE_URL), httpClient); AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse, toopherAPI); - authenticationRequest.authenticateWithOtp("testOtp"); + authenticationRequest.grantWithOtp("testOtp"); assertEquals(authenticationRequest.id, id); assertEquals(authenticationRequest.reason, "it is a changed test"); From 2f9779052eba5656500f72e863c33b627b1a540e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 09:32:48 -0600 Subject: [PATCH 060/195] Fix testAdvancedUsersCreateWithExtras() --- src/main/java/com/toopher/ToopherAPI.java | 2 ++ src/test/java/com/toopher/TestToopherAPI.java | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 9969d22..162fff0 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -566,6 +566,8 @@ public User create(String userName, Map extras) throws RequestEr List params = new ArrayList(); JSONObject result; + params.add(new BasicNameValuePair("name", userName)); + for (Map.Entry entry : extras.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index d6379fa..aa58dbc 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -265,9 +265,9 @@ public void testAdvancedUsersCreateWithExtras() throws InterruptedException, Req JSONObject jsonResponse = new JSONObject(); jsonResponse.put("id", id); jsonResponse.put("name", name); - jsonResponse.put("enabled", false); + jsonResponse.put("disable_toopher_auth", "false"); Map extras = new HashMap(); - extras.put("disable_toopher_auth", "false"); + extras.put("foo", "bar"); HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); @@ -278,7 +278,7 @@ public void testAdvancedUsersCreateWithExtras() throws InterruptedException, Req assertEquals(httpClient.getLastCalledMethod(), "POST"); assertEquals(user.id, id); assertEquals(user.name, name); - assertFalse(user.enabled); + assertTrue(user.enabled); } @Test From 6208a4a5119dab3b893e551a6e942f9fe2a7c274 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 09:47:35 -0600 Subject: [PATCH 061/195] Rename User.enabled to User.toopherAuthenticationEnabled --- src/main/java/com/toopher/User.java | 6 +++--- src/test/java/com/toopher/TestToopherAPI.java | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index e398cb7..8c0b683 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -25,7 +25,7 @@ public class User extends ApiResponseObject { /** * Whether or not the user is Toopher-enabled */ - public boolean enabled; + public boolean toopherAuthenticationEnabled; public User (JSONObject json, ToopherAPI toopherAPI) throws JSONException { super(json); @@ -34,14 +34,14 @@ public User (JSONObject json, ToopherAPI toopherAPI) throws JSONException { this.id = json.getString("id"); this.name = json.getString("name"); if (json.has("disable_toopher_auth")) { - this.enabled = (json.getBoolean("disable_toopher_auth") ? false : true); + this.toopherAuthenticationEnabled = (json.getBoolean("disable_toopher_auth") ? false : true); } } public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); if (jsonResponse.has("disable_toopher_auth")) { - this.enabled = (jsonResponse.getBoolean("disable_toopher_auth") ? false : true); + this.toopherAuthenticationEnabled = (jsonResponse.getBoolean("disable_toopher_auth") ? false : true); } } } diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index aa58dbc..eaba2e0 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -278,7 +278,7 @@ public void testAdvancedUsersCreateWithExtras() throws InterruptedException, Req assertEquals(httpClient.getLastCalledMethod(), "POST"); assertEquals(user.id, id); assertEquals(user.name, name); - assertTrue(user.enabled); + assertTrue(user.toopherAuthenticationEnabled); } @Test @@ -298,7 +298,7 @@ public void testAdvancedUsersGetById() throws InterruptedException, RequestError assertEquals(httpClient.getLastCalledMethod(), "GET"); assertEquals(user.id, id); assertEquals(user.name, name); - assertFalse(user.enabled); + assertFalse(user.toopherAuthenticationEnabled); } @Test @@ -325,7 +325,7 @@ public void testAdvancedUsersGetByName() throws InterruptedException, RequestErr assertEquals(expectedResponse, actualResponse); assertEquals(user.id, id); assertEquals(user.name, name); - assertTrue(user.enabled); + assertTrue(user.toopherAuthenticationEnabled); } @Test From 44e80f730a824ab215fb4ec7df6360bea82ad099 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 09:49:36 -0600 Subject: [PATCH 062/195] Update setter for User.toopherAuthenticationEnabled --- src/main/java/com/toopher/User.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index 8c0b683..5318afc 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -34,14 +34,18 @@ public User (JSONObject json, ToopherAPI toopherAPI) throws JSONException { this.id = json.getString("id"); this.name = json.getString("name"); if (json.has("disable_toopher_auth")) { - this.toopherAuthenticationEnabled = (json.getBoolean("disable_toopher_auth") ? false : true); + this.toopherAuthenticationEnabled = !json.getBoolean("disable_toopher_auth"); + } else { + this.toopherAuthenticationEnabled = true; } } public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); if (jsonResponse.has("disable_toopher_auth")) { - this.toopherAuthenticationEnabled = (jsonResponse.getBoolean("disable_toopher_auth") ? false : true); + this.toopherAuthenticationEnabled = !jsonResponse.getBoolean("disable_toopher_auth"); + } else { + this.toopherAuthenticationEnabled = true; } } } From 5886e7efbc6b3fcf0eacffd4171ae6409e351776 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 10:01:00 -0600 Subject: [PATCH 063/195] Use camelCase, not snake_case --- src/main/java/com/toopher/UserTerminal.java | 2 +- src/test/java/com/toopher/TestUserTerminal.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index 628be0e..5f69d0a 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -31,7 +31,7 @@ public String toString() { id, name, requesterSpecifiedId, user.name, user.id); } - public void refresh_from_server() throws RequestError { + public void refreshFromServer() throws RequestError { String endpoint = "user_terminals/{0}".format(id); JSONObject result = api.advanced.raw.get(endpoint); update(result); diff --git a/src/test/java/com/toopher/TestUserTerminal.java b/src/test/java/com/toopher/TestUserTerminal.java index 0e7e2c9..70b8ebd 100644 --- a/src/test/java/com/toopher/TestUserTerminal.java +++ b/src/test/java/com/toopher/TestUserTerminal.java @@ -57,7 +57,7 @@ public void testRefreshFromServer() throws InterruptedException, RequestError { assertEquals(terminal.requesterSpecifiedId, requesterSpecifiedId); assertEquals(terminal.user.name, userName); - terminal.refresh_from_server(); + terminal.refreshFromServer(); assertEquals(terminal.id, id); assertEquals(terminal.name, "terminalNameChanged"); From ce035442b051c6fa69c82a9038841ba61d1ab830 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 10:27:18 -0600 Subject: [PATCH 064/195] Add User.refreshFromServer() --- src/main/java/com/toopher/Pairing.java | 2 +- src/main/java/com/toopher/User.java | 6 +++ src/test/java/com/toopher/TestUser.java | 55 +++++++++++++++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/toopher/TestUser.java diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index 104c5f8..3a1326c 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -58,7 +58,7 @@ public Pairing(JSONObject json, ToopherAPI toopherAPI) throws JSONException { } public void refreshFromServer() throws RequestError { - String endpoint = "pairings/{0}".format(id); + String endpoint = String.format("pairings/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); } diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index 5318afc..8779ab8 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -39,6 +39,12 @@ public User (JSONObject json, ToopherAPI toopherAPI) throws JSONException { this.toopherAuthenticationEnabled = true; } } + + public void refreshFromServer() throws RequestError { + String endpoint = "users/{0}".format(id); + JSONObject result = api.advanced.raw.get(endpoint); + update(result); + } public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); diff --git a/src/test/java/com/toopher/TestUser.java b/src/test/java/com/toopher/TestUser.java new file mode 100644 index 0000000..21fa741 --- /dev/null +++ b/src/test/java/com/toopher/TestUser.java @@ -0,0 +1,55 @@ +package com.toopher; + +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; + +import java.net.URI; +import java.util.UUID; + +import static org.junit.Assert.*; + + +/** + * Created by graceyim on 2/4/15. + */ +public class TestUser { + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; + + private String id; + private String name; + private boolean disableToopherAuthentication; + private JSONObject json; + + @Before + public void setUp() { + this.id = UUID.randomUUID().toString(); + this.name = "userName"; + this.disableToopherAuthentication = false; + this.json = new JSONObject(); + this.json.put("id", id); + this.json.put("name", name); + this.json.put("disable_toopher_auth", disableToopherAuthentication); + } + + @Test + public void testRefreshFromServer() throws InterruptedException, RequestError { + JSONObject newJson = new JSONObject(); + newJson.put("name", "userNameChanged"); + newJson.put("disable_toopher_auth", "true"); + + HttpClientMock httpClient = new HttpClientMock(200, newJson.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + User user = new User(json, toopherAPI); + assertEquals(user.id, id); + assertEquals(user.name, name); + assertTrue(user.toopherAuthenticationEnabled); + + user.refreshFromServer(); + + assertEquals(user.id, id); + assertEquals(user.name, "userNameChanged"); + assertFalse(user.toopherAuthenticationEnabled); + } +} From 3245a80a4b51159f06213727be5857f4a2ee4254 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 10:47:18 -0600 Subject: [PATCH 065/195] Add User.enableToopherAuthentication() --- src/main/java/com/toopher/User.java | 13 +++++++++++++ src/test/java/com/toopher/TestUser.java | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index 8779ab8..9799e2d 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -1,8 +1,13 @@ package com.toopher; +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; +import java.util.ArrayList; +import java.util.List; + /** * Created by graceyim on 1/22/15. */ @@ -46,6 +51,14 @@ public void refreshFromServer() throws RequestError { update(result); } + public void enableToopherAuthentication() throws RequestError { + String endpoint = "users/{0}".format(id); + List params = new ArrayList(); + params.add(new BasicNameValuePair("disable_toopher_auth", "false")); + JSONObject result = api.advanced.raw.post(endpoint, params); + update(result); + } + public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); if (jsonResponse.has("disable_toopher_auth")) { diff --git a/src/test/java/com/toopher/TestUser.java b/src/test/java/com/toopher/TestUser.java index 21fa741..3e31fb3 100644 --- a/src/test/java/com/toopher/TestUser.java +++ b/src/test/java/com/toopher/TestUser.java @@ -52,4 +52,23 @@ public void testRefreshFromServer() throws InterruptedException, RequestError { assertEquals(user.name, "userNameChanged"); assertFalse(user.toopherAuthenticationEnabled); } + + @Test + public void testEnableToopherAuthentication() throws InterruptedException, RequestError { + JSONObject newJson = new JSONObject(); + newJson.put("id", id); + newJson.put("name", name); + newJson.put("disable_toopher_auth", "false"); + + HttpClientMock httpClient = new HttpClientMock(200, newJson.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + User user = new User(json, toopherAPI); + + user.enableToopherAuthentication(); + + assertEquals(user.id, id); + assertEquals(user.name, name); + assertTrue(user.toopherAuthenticationEnabled); + } } From dafc853ad76c9aa7c9f2ea39f24273b5b6135002 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 10:51:40 -0600 Subject: [PATCH 066/195] Add User.disableToopherAuthentication() --- src/main/java/com/toopher/User.java | 8 ++++++++ src/test/java/com/toopher/TestUser.java | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index 9799e2d..5a63705 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -59,6 +59,14 @@ public void enableToopherAuthentication() throws RequestError { update(result); } + public void disableToopherAuthentication() throws RequestError { + String endpoint = "users/{0}".format(id); + List params = new ArrayList(); + params.add(new BasicNameValuePair("disable_toopher_auth", "true")); + JSONObject result = api.advanced.raw.post(endpoint, params); + update(result); + } + public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); if (jsonResponse.has("disable_toopher_auth")) { diff --git a/src/test/java/com/toopher/TestUser.java b/src/test/java/com/toopher/TestUser.java index 3e31fb3..d7961e3 100644 --- a/src/test/java/com/toopher/TestUser.java +++ b/src/test/java/com/toopher/TestUser.java @@ -71,4 +71,22 @@ public void testEnableToopherAuthentication() throws InterruptedException, Reque assertEquals(user.name, name); assertTrue(user.toopherAuthenticationEnabled); } + + @Test + public void testDisableToopherAuthentication() throws InterruptedException, RequestError { + JSONObject newJson = new JSONObject(); + newJson.put("id", id); + newJson.put("name", name); + newJson.put("disable_toopher_auth", "true"); + + HttpClientMock httpClient = new HttpClientMock(200, newJson.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + User user = new User(json, toopherAPI); + user.disableToopherAuthentication(); + + assertEquals(user.id, id); + assertEquals(user.name, name); + assertFalse(user.toopherAuthenticationEnabled); + } } From edf2bf42b18c4e0a96973532fc96c7ad938effa0 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 11:03:46 -0600 Subject: [PATCH 067/195] Add User.reset() --- src/main/java/com/toopher/User.java | 7 +++++++ src/test/java/com/toopher/TestUser.java | 13 +++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index 5a63705..ba41879 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -67,6 +67,13 @@ public void disableToopherAuthentication() throws RequestError { update(result); } + public void reset() throws RequestError { + String endpoint = "/users/reset"; + List params = new ArrayList(); + params.add(new BasicNameValuePair("name", name)); + api.advanced.raw.post(endpoint, params); + } + public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); if (jsonResponse.has("disable_toopher_auth")) { diff --git a/src/test/java/com/toopher/TestUser.java b/src/test/java/com/toopher/TestUser.java index d7961e3..ddec421 100644 --- a/src/test/java/com/toopher/TestUser.java +++ b/src/test/java/com/toopher/TestUser.java @@ -89,4 +89,17 @@ public void testDisableToopherAuthentication() throws InterruptedException, Requ assertEquals(user.name, name); assertFalse(user.toopherAuthenticationEnabled); } + + @Test + public void testReset() throws InterruptedException, RequestError { + HttpClientMock httpClient = new HttpClientMock(200, "{}"); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + User user = new User(json, toopherAPI); + try { + user.reset(); + } catch (RequestError re) { + fail(); + } + } } From 68a10f5cd98ef3232e266fcb490df10e546127d2 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 11:26:15 -0600 Subject: [PATCH 068/195] Rename raw to rawResponse in ApiResponseObject --- src/main/java/com/toopher/ApiResponseObject.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/toopher/ApiResponseObject.java b/src/main/java/com/toopher/ApiResponseObject.java index 49c1b17..fd7bd92 100644 --- a/src/main/java/com/toopher/ApiResponseObject.java +++ b/src/main/java/com/toopher/ApiResponseObject.java @@ -11,10 +11,10 @@ public class ApiResponseObject { /** * A map of the raw API response data */ - public Map raw; + public Map rawResponse; public ApiResponseObject(JSONObject json) throws JSONException { - this.raw = jsonToMap(json); + this.rawResponse = jsonToMap(json); } private Map jsonToMap(JSONObject json) throws JSONException{ From 125abd7478e2a1af23be6326b9e1dd1495723a40 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Wed, 4 Feb 2015 11:29:11 -0600 Subject: [PATCH 069/195] Clean up javadocs --- src/main/java/com/toopher/AuthenticationRequest.java | 2 +- src/main/java/com/toopher/User.java | 3 ++- src/main/java/com/toopher/UserTerminal.java | 3 ++- src/test/java/com/toopher/ResponseMock.java | 3 --- src/test/java/com/toopher/TestAuthenticationRequest.java | 3 --- src/test/java/com/toopher/TestPairing.java | 3 --- src/test/java/com/toopher/TestUser.java | 3 --- src/test/java/com/toopher/TestUserTerminal.java | 3 --- 8 files changed, 5 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index ec95d27..b648ed6 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -10,7 +10,7 @@ import java.util.Map; /** - * Provide information about the status of an authentication request + * Provides information about the status of an authentication request * */ public class AuthenticationRequest extends ApiResponseObject { diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index ba41879..ad1fc42 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -9,7 +9,8 @@ import java.util.List; /** - * Created by graceyim on 1/22/15. + * Provides information about the status of a user + * */ public class User extends ApiResponseObject { /** diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index 5f69d0a..551e95d 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -4,7 +4,8 @@ import org.json.JSONObject; /** - * Created by graceyim on 1/22/15. + * Provides information about the status of a user terminal + * */ public class UserTerminal extends ApiResponseObject { public ToopherAPI api; diff --git a/src/test/java/com/toopher/ResponseMock.java b/src/test/java/com/toopher/ResponseMock.java index 68ce091..d2d8426 100644 --- a/src/test/java/com/toopher/ResponseMock.java +++ b/src/test/java/com/toopher/ResponseMock.java @@ -1,8 +1,5 @@ package com.toopher; -/** - * Created by graceyim on 1/29/15. - */ public class ResponseMock { private int statusCode; private String jsonResponse; diff --git a/src/test/java/com/toopher/TestAuthenticationRequest.java b/src/test/java/com/toopher/TestAuthenticationRequest.java index 8ca5a53..103caeb 100644 --- a/src/test/java/com/toopher/TestAuthenticationRequest.java +++ b/src/test/java/com/toopher/TestAuthenticationRequest.java @@ -12,9 +12,6 @@ import static org.junit.Assert.*; -/** - * Created by graceyim on 1/26/15. - */ public class TestAuthenticationRequest { private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; diff --git a/src/test/java/com/toopher/TestPairing.java b/src/test/java/com/toopher/TestPairing.java index 2046413..e226148 100644 --- a/src/test/java/com/toopher/TestPairing.java +++ b/src/test/java/com/toopher/TestPairing.java @@ -12,9 +12,6 @@ import static org.junit.Assert.*; -/** - * Created by graceyim on 1/26/15. - */ public class TestPairing { private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; diff --git a/src/test/java/com/toopher/TestUser.java b/src/test/java/com/toopher/TestUser.java index ddec421..62a1f79 100644 --- a/src/test/java/com/toopher/TestUser.java +++ b/src/test/java/com/toopher/TestUser.java @@ -10,9 +10,6 @@ import static org.junit.Assert.*; -/** - * Created by graceyim on 2/4/15. - */ public class TestUser { private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; diff --git a/src/test/java/com/toopher/TestUserTerminal.java b/src/test/java/com/toopher/TestUserTerminal.java index 70b8ebd..16bd51e 100644 --- a/src/test/java/com/toopher/TestUserTerminal.java +++ b/src/test/java/com/toopher/TestUserTerminal.java @@ -10,9 +10,6 @@ import static org.junit.Assert.*; -/** - * Created by graceyim on 1/26/15. - */ public class TestUserTerminal { private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; From 82d24b08c9bec2f668beffc6720dd6d5a3aa1ca4 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 5 Feb 2015 12:02:59 -0600 Subject: [PATCH 070/195] Add Pairing.getQrCodeImage() --- src/main/java/com/toopher/Pairing.java | 5 +++ src/main/java/com/toopher/ToopherAPI.java | 28 ++++++++++++++- src/test/java/com/toopher/HttpClientMock.java | 2 +- src/test/java/com/toopher/TestPairing.java | 34 ++++++++++++++++--- 4 files changed, 63 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index 3a1326c..08fc455 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -63,6 +63,11 @@ public void refreshFromServer() throws RequestError { update(result); } + public byte[] getQrCodeImage() throws RequestError { + String endpoint = String.format("qr/pairings/%s", id); + return api.advanced.raw.get(endpoint); + } + private void update(JSONObject jsonResponse) { this.enabled = jsonResponse.getBoolean("enabled"); this.pending = jsonResponse.getBoolean("pending"); diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 162fff0..35e8c43 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -409,6 +409,27 @@ public Object handleResponse(HttpResponse response) throws IOException, ClientPr } }; + private static ResponseHandler qrResponseHandler = new ResponseHandler() { + + @Override + public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException { + StatusLine statusLine = response.getStatusLine(); + if (statusLine.getStatusCode() >= 300) { + parseRequestError(statusLine, response); + } + + HttpEntity entity = response.getEntity(); + byte[] content; + content = (entity != null) ? EntityUtils.toByteArray(entity) : null; + + if (content != null) { + return content; + } else { + throw new RequestError("Empty response body returned"); + } + } + }; + public static String getBaseURL() { return String.format("%s://%s%s", DEFAULT_URI_SCHEME, @@ -701,6 +722,7 @@ public T post(String endpoint, List params, Map T request(HttpRequestBase httpRequest, String endpoint, List queryStringParameters) throws RequestError { + Boolean isQrImageEndpoint = endpoint.contains("qr/pairings/"); try { URIBuilder uriBuilder = new URIBuilder().setScheme(uriScheme).setHost(uriHost) .setPort(uriPort) @@ -717,7 +739,11 @@ private T request(HttpRequestBase httpRequest, String endpoint, List Date: Thu, 5 Feb 2015 12:11:51 -0600 Subject: [PATCH 071/195] Use String.format for strings --- src/main/java/com/toopher/AuthenticationRequest.java | 4 ++-- src/main/java/com/toopher/Pairing.java | 4 ++-- src/main/java/com/toopher/ToopherAPI.java | 8 ++++---- src/main/java/com/toopher/User.java | 6 +++--- src/main/java/com/toopher/UserTerminal.java | 2 +- src/test/java/com/toopher/TestPairing.java | 8 ++++---- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index b648ed6..8ff1559 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -89,7 +89,7 @@ public String toString() { } public void grantWithOtp(String otp) throws RequestError { - String endpoint = "authentication_requests/{0}/otp_auth".format(id); + String endpoint = String.format("authentication_requests/%s/otp_auth", id); List params = new ArrayList(); params.add(new BasicNameValuePair("otp", otp)); @@ -102,7 +102,7 @@ public void grantWithOtp(String otp) throws RequestError { } public void refreshFromServer() throws RequestError { - String endpoint = "authentication_requests{0}".format(id); + String endpoint = String.format("authentication_requests/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); } diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index 08fc455..8702fd9 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -86,7 +86,7 @@ public String getResetLink(Map extras) throws RequestError { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } - String endpoint = "pairings/{0}/generate_reset_link".format(id); + String endpoint = String.format("pairings/%s/generate_reset_link", id); JSONObject result = api.advanced.raw.post(endpoint, params); return result.getString("url"); } @@ -96,7 +96,7 @@ public void emailResetLink(String email) throws RequestError { } public void emailResetLink(String email, Map extras) throws RequestError { - String endpoint = "pairings/{0}/send_reset_link".format(id); + String endpoint = String.format("pairings/%s/send_reset_link", id); List params = new ArrayList(); params.add(new BasicNameValuePair("reset_email", email)); api.advanced.raw.post(endpoint, params, extras); diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 35e8c43..dae2d74 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -361,10 +361,10 @@ public void setToopherEnabledForUser(String userName, boolean toopherEnabled) th // user name should be a unique field per requester - if more than one object is returned, this is gonna be a problem if (result.length() > 1) { - throw new RequestError("More than one user with username {0}".format(userName)); + throw new RequestError(String.format("More than one user with username %s", userName)); } if (result.length() == 0) { - throw new RequestError("No users with user name {0}".format(userName)); + throw new RequestError(String.format("No users with user name %s", userName)); } String userId; @@ -640,10 +640,10 @@ public User getByName(String name) throws RequestError { JSONArray result = (JSONArray) advanced.raw.get(endpoint, params); if (result.length() > 1) { - throw new RequestError("More than one user with name {0}".format(name)); + throw new RequestError(String.format("More than one user with name %s", name)); } if (result.length() == 0) { - throw new RequestError("No users with name {0}".format(name)); + throw new RequestError(String.format("No users with name %s", name)); } String userId = result.getJSONObject(0).getString("id"); return getById(userId); diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index ad1fc42..4ad1582 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -47,13 +47,13 @@ public User (JSONObject json, ToopherAPI toopherAPI) throws JSONException { } public void refreshFromServer() throws RequestError { - String endpoint = "users/{0}".format(id); + String endpoint = String.format("users/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); } public void enableToopherAuthentication() throws RequestError { - String endpoint = "users/{0}".format(id); + String endpoint = String.format("users/%s", id); List params = new ArrayList(); params.add(new BasicNameValuePair("disable_toopher_auth", "false")); JSONObject result = api.advanced.raw.post(endpoint, params); @@ -61,7 +61,7 @@ public void enableToopherAuthentication() throws RequestError { } public void disableToopherAuthentication() throws RequestError { - String endpoint = "users/{0}".format(id); + String endpoint = String.format("users/%s", id); List params = new ArrayList(); params.add(new BasicNameValuePair("disable_toopher_auth", "true")); JSONObject result = api.advanced.raw.post(endpoint, params); diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index 551e95d..508e795 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -33,7 +33,7 @@ public String toString() { } public void refreshFromServer() throws RequestError { - String endpoint = "user_terminals/{0}".format(id); + String endpoint = String.format("user_terminals/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); } diff --git a/src/test/java/com/toopher/TestPairing.java b/src/test/java/com/toopher/TestPairing.java index a41e8c7..691fceb 100644 --- a/src/test/java/com/toopher/TestPairing.java +++ b/src/test/java/com/toopher/TestPairing.java @@ -93,7 +93,7 @@ public void testGetQrCodeImage() throws InterruptedException, RequestError, IOEx @Test public void testGetResetLink() throws InterruptedException, RequestError { JSONObject urlJsonResponse = new JSONObject(); - urlJsonResponse.put("url", "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); + urlJsonResponse.put("url", String.format("http://api.toopher.test/v1/pairings/%s/reset?reset_authorization=abcde", id)); HttpClientMock httpClient = new HttpClientMock(200, urlJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", @@ -101,13 +101,13 @@ public void testGetResetLink() throws InterruptedException, RequestError { Pairing pairing = new Pairing(jsonResponse, toopherAPI); String resetLink = pairing.getResetLink(); - assertEquals(resetLink, "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); + assertEquals(resetLink, String.format("http://api.toopher.test/v1/pairings/%s/reset?reset_authorization=abcde", id)); } @Test public void testGetResetLinkWithExtras() throws InterruptedException, RequestError { JSONObject urlJsonResponse = new JSONObject(); - urlJsonResponse.put("url", "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); + urlJsonResponse.put("url", String.format("http://api.toopher.test/v1/pairings/%s/reset?reset_authorization=abcde", id)); HttpClientMock httpClient = new HttpClientMock(200, urlJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", @@ -118,7 +118,7 @@ public void testGetResetLinkWithExtras() throws InterruptedException, RequestErr Pairing pairing = new Pairing(jsonResponse, toopherAPI); String resetLink = pairing.getResetLink(extras); - assertEquals(resetLink, "http://api.toopher.test/v1/pairings/{0}/reset?reset_authorization=abcde".format(id)); + assertEquals(resetLink, String.format("http://api.toopher.test/v1/pairings/%s/reset?reset_authorization=abcde", id)); } @Test From 97fbb04bec299a4da62870c4658af8f1ad90acf2 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 5 Feb 2015 12:39:42 -0600 Subject: [PATCH 072/195] Use DEFAULT_BASE_URL in ToopherAPI tests --- src/test/java/com/toopher/TestToopherAPI.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index eaba2e0..206bb6c 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -69,7 +69,7 @@ public void testCreatePairing() throws InterruptedException, RequestError { HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); ToopherAPI toopherApi = new ToopherAPI("key", "secret", - createURI("https://api.toopher.test/v1"), httpClient); + createURI(DEFAULT_BASE_URL), httpClient); Pairing pairing = toopherApi.pair("some user", "awkward turtle"); assertEquals(httpClient.getLastCalledMethod(), "POST"); @@ -92,7 +92,7 @@ public void testCreateQrPairing() throws InterruptedException, RequestError { HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); ToopherAPI toopherApi = new ToopherAPI("key", "secret", - createURI("https://api.toopher.test/v1"), httpClient); + createURI(DEFAULT_BASE_URL), httpClient); Pairing pairing = toopherApi.pair(userName); assertEquals(httpClient.getLastCalledMethod(), "POST"); @@ -136,7 +136,7 @@ public void testAdvancedPairingsGetById() throws InterruptedException, RequestEr HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", - createURI("https://api.toopher.test/v1"), httpClient); + createURI(DEFAULT_BASE_URL), httpClient); Pairing pairing = toopherAPI.advanced.pairings.getById(id); assertEquals(httpClient.getLastCalledMethod(), "GET"); @@ -312,7 +312,7 @@ public void testAdvancedUsersGetByName() throws InterruptedException, RequestErr usersJsonArray.put(usersJsonResponse); Map expectedUriResponses = new HashMap(); - expectedUriResponses.put(createURI("https://api.toopher.test/v1/users/" + id), new ResponseMock(200, usersJsonResponse.toString())); + expectedUriResponses.put(createURI(String.format("https://api.toopher.test/v1/users/%s", id)), new ResponseMock(200, usersJsonResponse.toString())); expectedUriResponses.put(createURI("https://api.toopher.test/v1/users?name=name"), new ResponseMock(200, usersJsonArray.toString())); HttpClientMock httpClient = new HttpClientMock(expectedUriResponses); From cb6e2962183bd6090f25f98f0d1aff31437346d7 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 5 Feb 2015 13:18:57 -0600 Subject: [PATCH 073/195] Clean up tests for Pairing --- src/test/java/com/toopher/TestPairing.java | 81 +++++++++---------- src/test/java/com/toopher/TestToopherAPI.java | 1 + 2 files changed, 40 insertions(+), 42 deletions(-) diff --git a/src/test/java/com/toopher/TestPairing.java b/src/test/java/com/toopher/TestPairing.java index 691fceb..687f58e 100644 --- a/src/test/java/com/toopher/TestPairing.java +++ b/src/test/java/com/toopher/TestPairing.java @@ -5,14 +5,9 @@ import org.junit.Test; import javax.imageio.ImageIO; -import javax.imageio.ImageReader; -import javax.imageio.stream.ImageInputStream; import java.awt.image.BufferedImage; import java.io.*; -import java.net.MalformedURLException; import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; import java.util.*; import static org.junit.Assert.*; @@ -22,19 +17,16 @@ public class TestPairing { private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; private String id; - private JSONObject user; - private String userId; private String userName; private JSONObject jsonResponse; - private Pairing pairing; @Before public void setUp() { this.id = UUID.randomUUID().toString(); - this.user = new JSONObject(); - this.user.put("id", UUID.randomUUID().toString()); - this.user.put("name", "userName"); - this.userId = user.getString("id"); + + JSONObject user = new JSONObject(); + user.put("id", UUID.randomUUID().toString()); + user.put("name", "userName"); this.userName = user.getString("name"); this.jsonResponse = new JSONObject(); @@ -46,32 +38,29 @@ public void setUp() { @Test public void testRefreshFromServer() throws InterruptedException, RequestError { - JSONObject newResponse = new JSONObject(); + JSONObject newJsonResponse = new JSONObject(); + newJsonResponse.put("enabled", true); + newJsonResponse.put("pending", false); JSONObject newUser = new JSONObject(); newUser.put("name", "userNameChanged"); - newResponse.put("user", newUser); - newResponse.put("enabled", false); - newResponse.put("pending", true); + newJsonResponse.put("user", newUser); - HttpClientMock httpClient = new HttpClientMock(200, newResponse.toString()); + HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); Pairing pairing = new Pairing(jsonResponse, toopherAPI); - assertEquals(pairing.id, id); - assertEquals(pairing.user.name, userName); - assertTrue(pairing.enabled); - assertFalse(pairing.pending); + + assertEquals(id, pairing.id); + assertEquals(userName, pairing.user.name); pairing.refreshFromServer(); - assertEquals(pairing.id, id); - assertEquals(pairing.user.name, "userNameChanged"); - assertFalse(pairing.enabled); - assertTrue(pairing.pending); + assertEquals(id, pairing.id); + assertEquals("userNameChanged", pairing.user.name); } @Test - public void testGetQrCodeImage() throws InterruptedException, RequestError, IOException { + public void testGetQrCodeImage() throws InterruptedException, IOException { BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, "png", baos); @@ -92,33 +81,39 @@ public void testGetQrCodeImage() throws InterruptedException, RequestError, IOEx @Test public void testGetResetLink() throws InterruptedException, RequestError { + String resetLink = String.format("http://api.toopher.test/v1/pairings/%s/reset?reset_authorization=abcde", id); JSONObject urlJsonResponse = new JSONObject(); - urlJsonResponse.put("url", String.format("http://api.toopher.test/v1/pairings/%s/reset?reset_authorization=abcde", id)); + urlJsonResponse.put("url", resetLink); HttpClientMock httpClient = new HttpClientMock(200, urlJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); Pairing pairing = new Pairing(jsonResponse, toopherAPI); - String resetLink = pairing.getResetLink(); + String returnedResetLink = pairing.getResetLink(); - assertEquals(resetLink, String.format("http://api.toopher.test/v1/pairings/%s/reset?reset_authorization=abcde", id)); + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals(resetLink, returnedResetLink); } @Test public void testGetResetLinkWithExtras() throws InterruptedException, RequestError { + String resetLink = String.format("http://api.toopher.test/v1/pairings/%s/reset?reset_authorization=abcde", id); JSONObject urlJsonResponse = new JSONObject(); - urlJsonResponse.put("url", String.format("http://api.toopher.test/v1/pairings/%s/reset?reset_authorization=abcde", id)); + urlJsonResponse.put("url", resetLink); + Map extras = new HashMap(); + extras.put("security_question", "is this a test?"); + extras.put("security_answer", "yes!"); HttpClientMock httpClient = new HttpClientMock(200, urlJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); - Map extras = new HashMap(); - extras.put("security_question", "is this a test?"); - extras.put("security_answer", "yes!"); Pairing pairing = new Pairing(jsonResponse, toopherAPI); - String resetLink = pairing.getResetLink(extras); + String returnedResetLink = pairing.getResetLink(extras); - assertEquals(resetLink, String.format("http://api.toopher.test/v1/pairings/%s/reset?reset_authorization=abcde", id)); + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals(resetLink, returnedResetLink); + assertEquals("is this a test?", httpClient.getLastCalledData("security_question")); + assertEquals("yes!", httpClient.getLastCalledData("security_answer")); } @Test @@ -128,22 +123,24 @@ public void testEmailResetLink() throws InterruptedException, RequestError { URI.create(DEFAULT_BASE_URL), httpClient); Pairing pairing = new Pairing(jsonResponse, toopherAPI); pairing.emailResetLink("email"); - assertEquals(httpClient.getLastCalledMethod(), "POST"); - assertEquals(httpClient.getLastCalledData("reset_email"), "email"); + + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("email", httpClient.getLastCalledData("reset_email")); } @Test public void testEmailResetLinkWithExtras() throws InterruptedException, RequestError { + Map extras = new HashMap(); + extras.put("one_extra_key", "one_extra_value"); + HttpClientMock httpClient = new HttpClientMock(201, "[]"); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); - Map extras = new HashMap(); - extras.put("one_extra", "one_extra"); Pairing pairing = new Pairing(jsonResponse, toopherAPI); pairing.emailResetLink("email", extras); - assertEquals(httpClient.getLastCalledMethod(), "POST"); - assertEquals(httpClient.getLastCalledData("reset_email"), "email"); - assertEquals(httpClient.getLastCalledData("one_extra"), "one_extra"); + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("email", httpClient.getLastCalledData("reset_email")); + assertEquals("one_extra_value", httpClient.getLastCalledData("one_extra_key")); } } diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 206bb6c..3a4c3a7 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -276,6 +276,7 @@ public void testAdvancedUsersCreateWithExtras() throws InterruptedException, Req User user = toopherAPI.advanced.users.create(name, extras); assertEquals(httpClient.getLastCalledMethod(), "POST"); + assertEquals("bar", httpClient.getLastCalledData("foo")); assertEquals(user.id, id); assertEquals(user.name, name); assertTrue(user.toopherAuthenticationEnabled); From 90ed94589700f5df735a9bd43d1451649bd294eb Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 5 Feb 2015 15:20:29 -0600 Subject: [PATCH 074/195] Clean up tests for AuthenticationRequest --- .../toopher/TestAuthenticationRequest.java | 124 ++++++++++-------- 1 file changed, 72 insertions(+), 52 deletions(-) diff --git a/src/test/java/com/toopher/TestAuthenticationRequest.java b/src/test/java/com/toopher/TestAuthenticationRequest.java index 103caeb..3d4ae07 100644 --- a/src/test/java/com/toopher/TestAuthenticationRequest.java +++ b/src/test/java/com/toopher/TestAuthenticationRequest.java @@ -4,48 +4,48 @@ import org.junit.Before; import org.junit.Test; -import java.net.MalformedURLException; import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; import java.util.UUID; import static org.junit.Assert.*; public class TestAuthenticationRequest { - private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; private String id; private String reason; - private int reasonCode; - private JSONObject terminal; - private JSONObject action; - private JSONObject user; private JSONObject jsonResponse; + private String userName; + private String terminalName; + private String terminalNameExtra; @Before public void setUp() { this.id = UUID.randomUUID().toString(); this.reason = "it is a test"; - this.reasonCode = 111; - this.user = new JSONObject(); - this.user.put("id", UUID.randomUUID().toString()); - this.user.put("name", "userName"); - this.terminal = new JSONObject(); - this.terminal.put("id", UUID.randomUUID().toString()); - this.terminal.put("name", "terminalName"); - this.terminal.put("name_extra", "terminalNameExtra"); - this.terminal.put("user", this.user); - this.action = new JSONObject(); - this.action.put("id", UUID.randomUUID().toString()); - this.action.put("name", "log in"); + + JSONObject user = new JSONObject(); + user.put("id", UUID.randomUUID().toString()); + user.put("name", "userName"); + this.userName = user.getString("name"); + JSONObject terminal = new JSONObject(); + terminal.put("id", UUID.randomUUID().toString()); + terminal.put("name", "terminalName"); + terminal.put("name_extra", "terminalNameExtra"); + terminal.put("user", user); + this.terminalName = terminal.getString("name"); + this.terminalNameExtra = terminal.getString("name_extra"); + JSONObject action = new JSONObject(); + action.put("id", UUID.randomUUID().toString()); + action.put("name", "log in"); + this.jsonResponse = new JSONObject(); jsonResponse.put("id", id); jsonResponse.put("pending", true); - jsonResponse.put("granted", true); - jsonResponse.put("automated", true); + jsonResponse.put("granted", false); + jsonResponse.put("automated", false); jsonResponse.put("reason", reason); - jsonResponse.put("reason_code", reasonCode); + jsonResponse.put("reason_code", 200); jsonResponse.put("user", user); jsonResponse.put("terminal", terminal); jsonResponse.put("action", action); @@ -53,49 +53,69 @@ public void setUp() { @Test public void testGrantWithOtp() throws InterruptedException, RequestError { - JSONObject newJsonResponse = jsonResponse; - newJsonResponse.remove("reason"); - newJsonResponse.put("reason", "it is a changed test"); + JSONObject newJsonResponse = new JSONObject(jsonResponse, JSONObject.getNames(jsonResponse)); + newJsonResponse.remove("pending"); + newJsonResponse.remove("granted"); + newJsonResponse.put("pending", false); + newJsonResponse.put("granted", true); + HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", - createURI(DEFAULT_BASE_URL), httpClient); - + URI.create(DEFAULT_BASE_URL), httpClient); AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse, toopherAPI); - authenticationRequest.grantWithOtp("testOtp"); - assertEquals(authenticationRequest.id, id); - assertEquals(authenticationRequest.reason, "it is a changed test"); + assertEquals(id, authenticationRequest.id); + assertTrue(authenticationRequest.pending); + assertFalse(authenticationRequest.granted); + + authenticationRequest.grantWithOtp("123456"); + + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals(String.format("authentication_requests/%s/otp_auth", authenticationRequest.id), httpClient.getLastCalledEndpoint()); + assertEquals(id, authenticationRequest.id); + assertFalse(authenticationRequest.pending); + assertTrue(authenticationRequest.granted); } @Test public void testRefreshFromServer() throws InterruptedException, RequestError { - JSONObject newJsonResponse = jsonResponse; - newJsonResponse.remove("pending"); - newJsonResponse.remove("granted"); - jsonResponse.put("pending", false); - jsonResponse.put("granted", false); + JSONObject newJsonResponse = new JSONObject(); + newJsonResponse.put("pending", true); + newJsonResponse.put("granted", false); + newJsonResponse.put("automated", false); + newJsonResponse.put("reason", "it is a test CHANGED"); + newJsonResponse.put("reason_code", 200); + JSONObject newUser = new JSONObject(); + newUser.put("name", "userNameChanged"); + newJsonResponse.put("user", newUser); + JSONObject newTerminal = new JSONObject(); + newTerminal.put("name", "terminalNameChanged"); + newTerminal.put("name_extra", "terminalNameExtraChanged"); + newTerminal.put("user", newUser); + newJsonResponse.put("terminal", newTerminal); + JSONObject newAction = new JSONObject(); + newAction.put("name", "log in"); + newJsonResponse.put("action", newAction); HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", - createURI(DEFAULT_BASE_URL), httpClient); - + URI.create(DEFAULT_BASE_URL), httpClient); AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse, toopherAPI); - authenticationRequest.refreshFromServer(); - assertEquals(authenticationRequest.id, id); - assertEquals(authenticationRequest.reasonCode, reasonCode); - assertFalse(authenticationRequest.pending); - assertFalse(authenticationRequest.granted); - } + assertEquals(userName, authenticationRequest.user.name); + assertEquals(reason, authenticationRequest.reason); + assertEquals(terminalName, authenticationRequest.terminal.name); + assertEquals(terminalNameExtra, authenticationRequest.terminal.requesterSpecifiedId); + + authenticationRequest.refreshFromServer(); - private URI createURI(String url) { - try { - return new URL(url).toURI(); - } catch (MalformedURLException e) { - return null; - } catch (URISyntaxException e) { - return null; - } + assertEquals("GET", httpClient.getLastCalledMethod()); + assertEquals(String.format("authentication_requests/%s", authenticationRequest.id), httpClient.getLastCalledEndpoint()); + assertEquals(id, authenticationRequest.id); + assertEquals("it is a test CHANGED", authenticationRequest.reason); + assertEquals("userNameChanged", authenticationRequest.user.name); + assertEquals("terminalNameChanged", authenticationRequest.terminal.name); + assertEquals("terminalNameExtraChanged", authenticationRequest.terminal.requesterSpecifiedId); } } From 13d560f5e99e7c74db2d6187ffb3f8414e4b65d4 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 09:05:04 -0600 Subject: [PATCH 075/195] Update HttpClientMock.getLastCalledEndpoint() to return endpoint without DEFAULT_BASE_URL --- src/test/java/com/toopher/HttpClientMock.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/toopher/HttpClientMock.java b/src/test/java/com/toopher/HttpClientMock.java index 5b02fc5..1cbcc8d 100644 --- a/src/test/java/com/toopher/HttpClientMock.java +++ b/src/test/java/com/toopher/HttpClientMock.java @@ -25,6 +25,8 @@ @Ignore public class HttpClientMock extends DefaultHttpClient { + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; + public HttpParams lastParams; public Semaphore done; @@ -64,8 +66,9 @@ public String getLastCalledData(String key) { return null; } - public URI getLastCalledEndpoint() { - return lastURI; + public String getLastCalledEndpoint() { + String fullUri = lastURI.toString(); + return fullUri.replace(DEFAULT_BASE_URL, ""); } public String getExpectedResponse() { From ac2ef13c87a1390dc86211dd3f5410615c91162e Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Thu, 5 Feb 2015 15:20:29 -0600 Subject: [PATCH 076/195] Clean up tests for AuthenticationRequest --- .../toopher/TestAuthenticationRequest.java | 124 ++++++++++-------- 1 file changed, 72 insertions(+), 52 deletions(-) diff --git a/src/test/java/com/toopher/TestAuthenticationRequest.java b/src/test/java/com/toopher/TestAuthenticationRequest.java index 103caeb..8a6bb48 100644 --- a/src/test/java/com/toopher/TestAuthenticationRequest.java +++ b/src/test/java/com/toopher/TestAuthenticationRequest.java @@ -4,48 +4,48 @@ import org.junit.Before; import org.junit.Test; -import java.net.MalformedURLException; import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; import java.util.UUID; import static org.junit.Assert.*; public class TestAuthenticationRequest { - private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; private String id; private String reason; - private int reasonCode; - private JSONObject terminal; - private JSONObject action; - private JSONObject user; private JSONObject jsonResponse; + private String userName; + private String terminalName; + private String terminalNameExtra; @Before public void setUp() { this.id = UUID.randomUUID().toString(); this.reason = "it is a test"; - this.reasonCode = 111; - this.user = new JSONObject(); - this.user.put("id", UUID.randomUUID().toString()); - this.user.put("name", "userName"); - this.terminal = new JSONObject(); - this.terminal.put("id", UUID.randomUUID().toString()); - this.terminal.put("name", "terminalName"); - this.terminal.put("name_extra", "terminalNameExtra"); - this.terminal.put("user", this.user); - this.action = new JSONObject(); - this.action.put("id", UUID.randomUUID().toString()); - this.action.put("name", "log in"); + + JSONObject user = new JSONObject(); + user.put("id", UUID.randomUUID().toString()); + user.put("name", "userName"); + this.userName = user.getString("name"); + JSONObject terminal = new JSONObject(); + terminal.put("id", UUID.randomUUID().toString()); + terminal.put("name", "terminalName"); + terminal.put("name_extra", "terminalNameExtra"); + terminal.put("user", user); + this.terminalName = terminal.getString("name"); + this.terminalNameExtra = terminal.getString("name_extra"); + JSONObject action = new JSONObject(); + action.put("id", UUID.randomUUID().toString()); + action.put("name", "log in"); + this.jsonResponse = new JSONObject(); jsonResponse.put("id", id); jsonResponse.put("pending", true); - jsonResponse.put("granted", true); - jsonResponse.put("automated", true); + jsonResponse.put("granted", false); + jsonResponse.put("automated", false); jsonResponse.put("reason", reason); - jsonResponse.put("reason_code", reasonCode); + jsonResponse.put("reason_code", 200); jsonResponse.put("user", user); jsonResponse.put("terminal", terminal); jsonResponse.put("action", action); @@ -53,49 +53,69 @@ public void setUp() { @Test public void testGrantWithOtp() throws InterruptedException, RequestError { - JSONObject newJsonResponse = jsonResponse; - newJsonResponse.remove("reason"); - newJsonResponse.put("reason", "it is a changed test"); + JSONObject newJsonResponse = new JSONObject(jsonResponse, JSONObject.getNames(jsonResponse)); + newJsonResponse.remove("pending"); + newJsonResponse.remove("granted"); + newJsonResponse.put("pending", false); + newJsonResponse.put("granted", true); + HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", - createURI(DEFAULT_BASE_URL), httpClient); - + URI.create(DEFAULT_BASE_URL), httpClient); AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse, toopherAPI); - authenticationRequest.grantWithOtp("testOtp"); - assertEquals(authenticationRequest.id, id); - assertEquals(authenticationRequest.reason, "it is a changed test"); + assertEquals(id, authenticationRequest.id); + assertTrue("Authentication request pending should be True.", authenticationRequest.pending); + assertFalse("Authentication request granted should be False.", authenticationRequest.granted); + + authenticationRequest.grantWithOtp("123456"); + + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals(String.format("authentication_requests/%s/otp_auth", authenticationRequest.id), httpClient.getLastCalledEndpoint()); + assertEquals(id, authenticationRequest.id); + assertFalse("Authentication request pending should be False.", authenticationRequest.pending); + assertTrue("Authentication request granted should be True.", authenticationRequest.granted); } @Test public void testRefreshFromServer() throws InterruptedException, RequestError { - JSONObject newJsonResponse = jsonResponse; - newJsonResponse.remove("pending"); - newJsonResponse.remove("granted"); - jsonResponse.put("pending", false); - jsonResponse.put("granted", false); + JSONObject newJsonResponse = new JSONObject(); + newJsonResponse.put("pending", true); + newJsonResponse.put("granted", false); + newJsonResponse.put("automated", false); + newJsonResponse.put("reason", "it is a test CHANGED"); + newJsonResponse.put("reason_code", 200); + JSONObject newUser = new JSONObject(); + newUser.put("name", "userNameChanged"); + newJsonResponse.put("user", newUser); + JSONObject newTerminal = new JSONObject(); + newTerminal.put("name", "terminalNameChanged"); + newTerminal.put("name_extra", "terminalNameExtraChanged"); + newTerminal.put("user", newUser); + newJsonResponse.put("terminal", newTerminal); + JSONObject newAction = new JSONObject(); + newAction.put("name", "log in"); + newJsonResponse.put("action", newAction); HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", - createURI(DEFAULT_BASE_URL), httpClient); - + URI.create(DEFAULT_BASE_URL), httpClient); AuthenticationRequest authenticationRequest = new AuthenticationRequest(jsonResponse, toopherAPI); - authenticationRequest.refreshFromServer(); - assertEquals(authenticationRequest.id, id); - assertEquals(authenticationRequest.reasonCode, reasonCode); - assertFalse(authenticationRequest.pending); - assertFalse(authenticationRequest.granted); - } + assertEquals(userName, authenticationRequest.user.name); + assertEquals(reason, authenticationRequest.reason); + assertEquals(terminalName, authenticationRequest.terminal.name); + assertEquals(terminalNameExtra, authenticationRequest.terminal.requesterSpecifiedId); + + authenticationRequest.refreshFromServer(); - private URI createURI(String url) { - try { - return new URL(url).toURI(); - } catch (MalformedURLException e) { - return null; - } catch (URISyntaxException e) { - return null; - } + assertEquals("GET", httpClient.getLastCalledMethod()); + assertEquals(String.format("authentication_requests/%s", authenticationRequest.id), httpClient.getLastCalledEndpoint()); + assertEquals(id, authenticationRequest.id); + assertEquals("it is a test CHANGED", authenticationRequest.reason); + assertEquals("userNameChanged", authenticationRequest.user.name); + assertEquals("terminalNameChanged", authenticationRequest.terminal.name); + assertEquals("terminalNameExtraChanged", authenticationRequest.terminal.requesterSpecifiedId); } } From 1a288fe49759202471066ede82988cfe14cdbc06 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 09:05:04 -0600 Subject: [PATCH 077/195] Update HttpClientMock.getLastCalledEndpoint() to return endpoint without DEFAULT_BASE_URL --- src/test/java/com/toopher/HttpClientMock.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/toopher/HttpClientMock.java b/src/test/java/com/toopher/HttpClientMock.java index 5b02fc5..1cbcc8d 100644 --- a/src/test/java/com/toopher/HttpClientMock.java +++ b/src/test/java/com/toopher/HttpClientMock.java @@ -25,6 +25,8 @@ @Ignore public class HttpClientMock extends DefaultHttpClient { + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; + public HttpParams lastParams; public Semaphore done; @@ -64,8 +66,9 @@ public String getLastCalledData(String key) { return null; } - public URI getLastCalledEndpoint() { - return lastURI; + public String getLastCalledEndpoint() { + String fullUri = lastURI.toString(); + return fullUri.replace(DEFAULT_BASE_URL, ""); } public String getExpectedResponse() { From 9976b68e8767bd640f5b4b1c080d54c477fe8e98 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 12:00:00 -0600 Subject: [PATCH 078/195] Remove methods from ToopherAPI that have been moved to AuthenticationRequest and User --- src/main/java/com/toopher/ToopherAPI.java | 57 ----------------------- 1 file changed, 57 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index dae2d74..6b3b23d 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -300,20 +300,6 @@ public AuthenticationRequest authenticate(String pairingIdOrUsername, String ter throw new RequestError(e); } } - - public AuthenticationRequest getAuthenticationStatusWithOTP(String authenticationRequestId,String OTP) throws RequestError { - final String endpoint = String.format("authentication_requests/%s/otp_auth", authenticationRequestId); - List params = new ArrayList(); - params.add(new BasicNameValuePair("otp", OTP)); - JSONObject json = advanced.raw.post(endpoint, params); - try { - return new AuthenticationRequest(json, this); - } catch (Exception e) { - throw new RequestError(e); - } - } - - /** * Associates a per-user "Friendly Name" to a given terminal * @@ -339,49 +325,6 @@ public void assignUserFriendlyNameToTerminal(String userName, String terminalNam advanced.raw.post(endpoint, params); } - /** - * Toggle whether a user is Toopher-Enabled - * - * @param userName - * The name of the user - * @param toopherEnabled - * Whether or not the user is Toopher-enabled - * @throws RequestError - * Thrown when an exceptional condition is encountered, or the - */ - public void setToopherEnabledForUser(String userName, boolean toopherEnabled) throws RequestError { - final String searchEndpoint = "users"; - final String updateEndpoint = "users/%s"; - - // first, look up the Toopher User ID - List params = new ArrayList(); - params.add(new BasicNameValuePair("name", userName)); - - JSONArray result = advanced.raw.get(searchEndpoint, params); - - // user name should be a unique field per requester - if more than one object is returned, this is gonna be a problem - if (result.length() > 1) { - throw new RequestError(String.format("More than one user with username %s", userName)); - } - if (result.length() == 0) { - throw new RequestError(String.format("No users with user name %s", userName)); - } - - String userId; - try { - JSONObject userJson = result.getJSONObject(0); - userId = userJson.getString("id"); - } catch (JSONException e) { - throw new RequestError(e); - } - - - // now, we can use that User ID to update the disable_toopher_auth field - params = new ArrayList(); - params.add(new BasicNameValuePair("disable_toopher_auth", toopherEnabled ? "false" : "true")); - - advanced.raw.post(String.format(updateEndpoint, userId), params); - } private static ResponseHandler jsonHandler = new ResponseHandler() { From c4d9bfd056cd2f3199248763299c588737fbccdf Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 12:01:34 -0600 Subject: [PATCH 079/195] Add UserTerminals.create to replace assignUserFriendlyNameToTerminal --- src/main/java/com/toopher/ToopherAPI.java | 81 ++++++++++++++++------- 1 file changed, 56 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 6b3b23d..f7dcfab 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -300,31 +300,6 @@ public AuthenticationRequest authenticate(String pairingIdOrUsername, String ter throw new RequestError(e); } } - /** - * Associates a per-user "Friendly Name" to a given terminal - * - * @param userName - * The name of the user - * @param terminalName - * The user-facing descriptive name for the terminal from which the request originates - * @param terminalNameExtra - * The requester-specific key that uniquely identifies this terminal. Can be shared - * across multiple users. The combination of userName and terminalNameExtra should - * be unique for a requester - * @throws RequestError - * Thrown when an exceptional condition is encountered, or the - */ - public void assignUserFriendlyNameToTerminal(String userName, String terminalName, String terminalNameExtra) throws RequestError { - final String endpoint = "user_terminals/create"; - - List params = new ArrayList(); - params.add(new BasicNameValuePair("user_name", userName)); - params.add(new BasicNameValuePair("name", terminalName)); - params.add(new BasicNameValuePair("name_extra", terminalNameExtra)); - - advanced.raw.post(endpoint, params); - } - private static ResponseHandler jsonHandler = new ResponseHandler() { @@ -600,6 +575,62 @@ public UserTerminals(ToopherAPI toopherAPI) { api = toopherAPI; } + /** + * + * @param userName + * The name of the user + * @param terminalName + * The user-facing descriptive name for the terminal from which the request originates + * @param requesterSpecifiedId + * The requester specified id that uniquely identifies this terminal. Can be shared + * across multiple users. The combination of userName and requesterSpecifiedId should + * be unique for a requester + * @return + * A UserTerminal object + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ + public UserTerminal create(String userName, String terminalName, String requesterSpecifiedId) throws RequestError { + return create(userName, terminalName, requesterSpecifiedId, null); + } + + /** + * Create a new user terminal + * + * @param userName + * The name of the user + * @param terminalName + * The user-facing descriptive name for the terminal from which the request originates + * @param requesterSpecifiedId + * The requester specified id that uniquely identifies this terminal. Can be shared + * across multiple users. The combination of userName and terminalNameExtra should + * be unique for a requester + * @param extras + * An optional Map of extra parameters to provide to the API + * @return + * A UserTerminal object + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ + public UserTerminal create(String userName, String terminalName, String requesterSpecifiedId, Map extras) throws RequestError { + final String endpoint = "user_terminals/create"; + List params = new ArrayList(); + JSONObject result; + + params.add(new BasicNameValuePair("user_name", userName)); + params.add(new BasicNameValuePair("name", terminalName)); + params.add(new BasicNameValuePair("name_extra", requesterSpecifiedId)); + + if (extras != null) { + for (Map.Entry entry : extras.entrySet()) { + params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + } + + result = advanced.raw.post(endpoint, params); + return new UserTerminal(result, api); + } + /** * Retrieve the current status of a user terminal by terminal id * From 09f4dcdf974070844bd7389071f069b93e7331c1 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 12:03:15 -0600 Subject: [PATCH 080/195] Clean up ApiRawRequester.get() and post() --- src/main/java/com/toopher/ToopherAPI.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index f7dcfab..243fb40 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -659,9 +659,6 @@ public T get(String endpoint, List params) throws RequestErro } public T get(String endpoint, List params, Map extras) throws RequestError { - if (params == null) { - params = new ArrayList(); - } if (extras != null && extras.size() > 0) { for (Map.Entry e : extras.entrySet()){ params.add(new BasicNameValuePair(e.getKey(), e.getValue())); @@ -671,7 +668,7 @@ public T get(String endpoint, List params, Map T post(String endpoint) throws RequestError { - return post(endpoint, null, null); + return request(new HttpPost(), endpoint, null); } public T post(String endpoint, List params) throws RequestError { @@ -724,7 +721,6 @@ private T request(HttpRequestBase httpRequest, String endpoint, List Date: Fri, 6 Feb 2015 12:41:34 -0600 Subject: [PATCH 081/195] Update HttpClientMock.getExpectedResponse to return expectedResponseBody if expectedUriResponses is null --- src/test/java/com/toopher/HttpClientMock.java | 2 +- src/test/java/com/toopher/TestToopherAPI.java | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/toopher/HttpClientMock.java b/src/test/java/com/toopher/HttpClientMock.java index 1cbcc8d..bf0209b 100644 --- a/src/test/java/com/toopher/HttpClientMock.java +++ b/src/test/java/com/toopher/HttpClientMock.java @@ -75,7 +75,7 @@ public String getExpectedResponse() { if (expectedUriResponses != null) { return expectedUriResponses.get(lastURI).getResponseBody(); } - return null; + return expectedResponseBody; } public int getExpectedResponseStatus() { diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 3a4c3a7..4554b81 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -3,6 +3,7 @@ import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.net.MalformedURLException; From 43d28a305a0a61de965199be914e0cdf39c0a8d0 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 12:44:53 -0600 Subject: [PATCH 082/195] Clean up and add tests for ToopherAPI --- src/test/java/com/toopher/TestToopherAPI.java | 483 +++++++++--------- 1 file changed, 237 insertions(+), 246 deletions(-) diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index 4554b81..a8f2380 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -1,5 +1,7 @@ package com.toopher; +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; @@ -10,370 +12,359 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; +import java.util.*; import static org.junit.Assert.*; public class TestToopherAPI { private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; - private String id; - private String name; - private JSONObject user; - private String userId; - private String userName; - private JSONObject action; - private String actionId; - private String actionName; - private String reason; - private int reasonCode; - private JSONObject terminal; - private String terminalId; - private String terminalName; - private String terminalNameExtra; + private static String id; + private static JSONObject user; + private static String userId; + private static String userName; + private static JSONObject action; + private static String actionId; + private static String actionName; + private static JSONObject terminal; + private static String terminalId; + private static String terminalName; + private static String terminalNameExtra; + + private static JSONObject pairingJsonResponse; + private static JSONObject authenticationJsonResponse; + private static JSONObject userJsonResponse; + private static JSONObject userTerminalJsonResponse; + + @BeforeClass + public static void setUpBeforeClass() { + id = UUID.randomUUID().toString(); + + user = new JSONObject(); + userId = UUID.randomUUID().toString(); + userName = "userName"; + user.put("id", userId); + user.put("name", userName); + + action = new JSONObject(); + actionId = UUID.randomUUID().toString(); + actionName = "log in"; + action.put("id", actionId); + action.put("name", actionName); + + terminal = new JSONObject(); + terminalId = UUID.randomUUID().toString(); + terminalName = "terminalName"; + terminalNameExtra = "terminalNameExtra"; + terminal.put("id", terminalId); + terminal.put("name", terminalName); + terminal.put("name_extra", terminalNameExtra); + terminal.put("user", user); + } @Before public void setUp() { - this.id = UUID.randomUUID().toString(); - this.name = "name"; - this.user = new JSONObject(); - this.user.put("id", UUID.randomUUID().toString()); - this.user.put("name", "userName"); - this.userId = this.user.getString("id"); - this.userName = this.user.getString("name"); - this.action = new JSONObject(); - this.action.put("id", UUID.randomUUID().toString()); - this.action.put("name", "log in"); - this.actionId = this.action.getString("id"); - this.actionName = this.action.getString("name"); - this.reason = "it is a test"; - this.reasonCode = 111; - this.terminal = new JSONObject(); - this.terminal.put("id", UUID.randomUUID().toString()); - this.terminal.put("name", "terminalName"); - this.terminal.put("name_extra", "terminalNameExtra"); - this.terminal.put("user", this.user); - this.terminalId = this.terminal.getString("id"); - this.terminalName = this.terminal.getString("name"); - this.terminalNameExtra = this.terminal.getString("name_extra"); + this.pairingJsonResponse = new JSONObject(); + pairingJsonResponse.put("id", id); + pairingJsonResponse.put("enabled", true); + pairingJsonResponse.put("pending", false); + pairingJsonResponse.put("user", user); + + this.authenticationJsonResponse = new JSONObject(); + authenticationJsonResponse.put("id", id); + authenticationJsonResponse.put("pending", false); + authenticationJsonResponse.put("granted", false); + authenticationJsonResponse.put("automated", false); + authenticationJsonResponse.put("reason", "it is a test"); + authenticationJsonResponse.put("reason_code", 111); + authenticationJsonResponse.put("terminal", terminal); + authenticationJsonResponse.put("action", action); + authenticationJsonResponse.put("user", user); + + this.userJsonResponse = new JSONObject(); + userJsonResponse.put("id", userId); + userJsonResponse.put("name", userName); + userJsonResponse.put("disable_toopher_auth", false); + + this.userTerminalJsonResponse = new JSONObject(); + userTerminalJsonResponse.put("id", terminalId); + userTerminalJsonResponse.put("name", terminalName); + userTerminalJsonResponse.put("name_extra", terminalNameExtra); + userTerminalJsonResponse.put("user", user); } @Test - public void testCreatePairing() throws InterruptedException, RequestError { - JSONObject jsonResponse = new JSONObject(); - jsonResponse.put("id", id); - jsonResponse.put("enabled", true); - jsonResponse.put("pending", true); - jsonResponse.put("user", user); - HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); - + public void testCreatePairingWithPairingPhrase() throws InterruptedException, RequestError { + HttpClientMock httpClient = new HttpClientMock(200, pairingJsonResponse.toString()); ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); - Pairing pairing = toopherApi.pair("some user", "awkward turtle"); - - assertEquals(httpClient.getLastCalledMethod(), "POST"); - assertEquals(httpClient.getLastCalledData("pairing_phrase"), "awkward turtle"); - - assertEquals(pairing.user.id, userId); - assertEquals(pairing.user.name, userName); - assertTrue(pairing.pending); - assertTrue(pairing.enabled); + Pairing pairing = toopherApi.pair(userName, "awkward turtle"); + + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("pairings/create", httpClient.getLastCalledEndpoint()); + assertEquals("awkward turtle", httpClient.getLastCalledData("pairing_phrase")); + assertEquals(userName, httpClient.getLastCalledData("user_name")); + assertEquals(id, pairing.id); + assertEquals(userId, pairing.user.id); } @Test public void testCreateQrPairing() throws InterruptedException, RequestError { - JSONObject jsonResponse = new JSONObject(); - jsonResponse.put("id", id); - jsonResponse.put("enabled", true); - jsonResponse.put("pending", true); - jsonResponse.put("user", user); - - HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); - + HttpClientMock httpClient = new HttpClientMock(200, pairingJsonResponse.toString()); ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); Pairing pairing = toopherApi.pair(userName); - assertEquals(httpClient.getLastCalledMethod(), "POST"); - assertEquals(pairing.user.id, userId); - assertEquals(pairing.user.name, userName); - assertTrue(pairing.pending); - assertTrue(pairing.enabled); + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("pairings/create/qr", httpClient.getLastCalledEndpoint()); + assertEquals(userName, httpClient.getLastCalledData("user_name")); + assertEquals(id, pairing.id); + assertEquals(userId, pairing.user.id); } @Test public void testCreateSmsPairing() throws InterruptedException, RequestError { - JSONObject jsonResponse = new JSONObject(); - jsonResponse.put("id", id); - jsonResponse.put("enabled", true); - jsonResponse.put("pending", true); - jsonResponse.put("user", user); - - HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); + HttpClientMock httpClient = new HttpClientMock(200, pairingJsonResponse.toString()); ToopherAPI toopherApi = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); Pairing pairing = toopherApi.pair(userName, "123456"); - assertEquals(httpClient.getLastCalledMethod(), "POST"); - assertEquals(httpClient.getLastCalledData("phone_number"), "123456"); - - assertEquals(pairing.user.id, userId); - assertEquals(pairing.user.name, userName); - assertTrue(pairing.pending); - assertTrue(pairing.enabled); + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("pairings/create/sms", httpClient.getLastCalledEndpoint()); + assertEquals("123456", httpClient.getLastCalledData("phone_number")); + assertEquals(userName, httpClient.getLastCalledData("user_name")); + assertEquals(id, pairing.id); + assertEquals(userId, pairing.user.id); } @Test public void testAdvancedPairingsGetById() throws InterruptedException, RequestError { - JSONObject jsonResponse = new JSONObject(); - jsonResponse.put("id", id); - jsonResponse.put("enabled", true); - jsonResponse.put("pending", true); - jsonResponse.put("user", user); - - HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); - + HttpClientMock httpClient = new HttpClientMock(200, pairingJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); Pairing pairing = toopherAPI.advanced.pairings.getById(id); - assertEquals(httpClient.getLastCalledMethod(), "GET"); - assertEquals(pairing.user.id, userId); - assertEquals(pairing.user.name, userName); - assertTrue(pairing.pending); - assertTrue(pairing.enabled); + assertEquals("GET", httpClient.getLastCalledMethod()); + assertEquals(String.format("pairings/%s", pairing.id), httpClient.getLastCalledEndpoint()); + assertEquals(id, pairing.id); + assertEquals(userId, pairing.user.id); } @Test public void testCreateAuthenticationRequestWithPairingId() throws InterruptedException, RequestError { - JSONObject response = new JSONObject(); - response.put("id", id); - response.put("pending", true); - response.put("granted", true); - response.put("automated", false); - response.put("reason", reason); - response.put("reason_code", reasonCode); - response.put("terminal", terminal); - response.put("action", action); - - HttpClientMock httpClient = new HttpClientMock(200, response.toString()); - + HttpClientMock httpClient = new HttpClientMock(200, authenticationJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); AuthenticationRequest authenticationRequest = toopherAPI.authenticate(id, terminalName, actionName); - assertEquals(httpClient.getLastCalledMethod(), "POST"); - assertEquals(authenticationRequest.id, id); - assertTrue(authenticationRequest.pending); - assertTrue(authenticationRequest.granted); - assertFalse(authenticationRequest.automated); - assertEquals(authenticationRequest.reason, reason); - assertEquals(authenticationRequest.reasonCode, reasonCode); - assertEquals(authenticationRequest.terminal.id, terminalId); - assertEquals(authenticationRequest.terminal.name, terminalName); - assertEquals(authenticationRequest.action.id, actionId); - assertEquals(authenticationRequest.action.name, actionName); + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("authentication_requests/initiate", httpClient.getLastCalledEndpoint()); + assertEquals(id, httpClient.getLastCalledData("pairing_id")); + assertEquals(terminalName, httpClient.getLastCalledData("terminal_name")); + assertEquals(id, authenticationRequest.id); + assertEquals(terminalId, authenticationRequest.terminal.id); + assertEquals(actionId, authenticationRequest.action.id); + assertEquals(userId, authenticationRequest.user.id); } @Test public void testCreateAuthenticationRequestWithUsername() throws InterruptedException, RequestError { - JSONObject response = new JSONObject(); - response.put("id", id); - response.put("pending", true); - response.put("granted", true); - response.put("automated", false); - response.put("reason", reason); - response.put("reason_code", reasonCode); - response.put("terminal", terminal); - response.put("action", action); - - HttpClientMock httpClient = new HttpClientMock(200, response.toString()); - + HttpClientMock httpClient = new HttpClientMock(200, authenticationJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); AuthenticationRequest authenticationRequest = toopherAPI.authenticate(userName, terminalNameExtra, actionName); - assertEquals(httpClient.getLastCalledMethod(), "POST"); - assertEquals(authenticationRequest.id, id); - assertTrue(authenticationRequest.pending); - assertTrue(authenticationRequest.granted); - assertFalse(authenticationRequest.automated); - assertEquals(authenticationRequest.reason, reason); - assertEquals(authenticationRequest.reasonCode, reasonCode); - assertEquals(authenticationRequest.terminal.id, terminalId); - assertEquals(authenticationRequest.terminal.name, terminalName); - assertEquals(authenticationRequest.action.id, actionId); - assertEquals(authenticationRequest.action.name, actionName); + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("authentication_requests/initiate", httpClient.getLastCalledEndpoint()); + assertEquals(userName, httpClient.getLastCalledData("user_name")); + assertEquals(terminalNameExtra, httpClient.getLastCalledData("terminal_name_extra")); + assertEquals(id, authenticationRequest.id); + assertEquals(terminalId, authenticationRequest.terminal.id); + assertEquals(actionId, authenticationRequest.action.id); + assertEquals(userId, authenticationRequest.user.id); } - - @Test public void testAdvancedAuthenticationRequestsGetById() throws InterruptedException, RequestError { - JSONObject jsonResponse = new JSONObject(); - jsonResponse.put("id", id); - jsonResponse.put("pending", true); - jsonResponse.put("granted", true); - jsonResponse.put("automated", false); - jsonResponse.put("reason", reason); - jsonResponse.put("reason_code", reasonCode); - jsonResponse.put("action", action); - jsonResponse.put("terminal", terminal); - - HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); - + HttpClientMock httpClient = new HttpClientMock(200, authenticationJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); AuthenticationRequest authenticationRequest = toopherAPI.advanced.authenticationRequests.getById(id); - assertEquals(httpClient.getLastCalledMethod(), "GET"); - assertEquals(authenticationRequest.id, id); - assertEquals(authenticationRequest.reason, reason); - assertEquals(authenticationRequest.reasonCode, reasonCode); - assertEquals(authenticationRequest.terminal.id, terminalId); - assertEquals(authenticationRequest.terminal.name, terminalName); - assertEquals(authenticationRequest.terminal.user.id, userId); - assertEquals(authenticationRequest.terminal.user.name, userName); - assertEquals(authenticationRequest.action.id, actionId); - assertEquals(authenticationRequest.action.name, actionName); - assertTrue(authenticationRequest.pending); - assertTrue(authenticationRequest.granted); - assertFalse(authenticationRequest.automated); + assertEquals("GET", httpClient.getLastCalledMethod()); + assertEquals(String.format("authentication_requests/%s", authenticationRequest.id), httpClient.getLastCalledEndpoint()); + assertEquals(id, authenticationRequest.id); + assertEquals(terminalId, authenticationRequest.terminal.id); + assertEquals(actionId, authenticationRequest.action.id); + assertEquals(userId, authenticationRequest.terminal.user.id); } @Test public void testAdvancedUsersCreate() throws InterruptedException, RequestError { - JSONObject jsonResponse = new JSONObject(); - jsonResponse.put("id", id); - jsonResponse.put("name", name); - - HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); - + HttpClientMock httpClient = new HttpClientMock(200, userJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); - User user = toopherAPI.advanced.users.create(name); - - assertEquals(httpClient.getLastCalledMethod(), "POST"); - assertEquals(user.id, id); - assertEquals(user.name, name); + User user = toopherAPI.advanced.users.create(userName); + + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("users/create", httpClient.getLastCalledEndpoint()); + assertEquals(userName, httpClient.getLastCalledData("name")); + assertEquals(userId, user.id); + assertEquals(userName, user.name); + assertTrue("Toopher authentication should be enabled for user.", user.toopherAuthenticationEnabled); } @Test public void testAdvancedUsersCreateWithExtras() throws InterruptedException, RequestError { - JSONObject jsonResponse = new JSONObject(); - jsonResponse.put("id", id); - jsonResponse.put("name", name); - jsonResponse.put("disable_toopher_auth", "false"); Map extras = new HashMap(); extras.put("foo", "bar"); - HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); - + HttpClientMock httpClient = new HttpClientMock(200, userJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); - User user = toopherAPI.advanced.users.create(name, extras); + User user = toopherAPI.advanced.users.create(userName, extras); - assertEquals(httpClient.getLastCalledMethod(), "POST"); + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("users/create", httpClient.getLastCalledEndpoint()); assertEquals("bar", httpClient.getLastCalledData("foo")); - assertEquals(user.id, id); - assertEquals(user.name, name); - assertTrue(user.toopherAuthenticationEnabled); + assertEquals(userId, user.id); + assertEquals(userName, user.name); + assertTrue("Toopher authentication should be enabled for user.", user.toopherAuthenticationEnabled); } @Test public void testAdvancedUsersGetById() throws InterruptedException, RequestError { - JSONObject jsonResponse = new JSONObject(); - jsonResponse.put("id", id); - jsonResponse.put("name", name); - jsonResponse.put("enabled", true); - jsonResponse.put("disable_toopher_auth", true); - - HttpClientMock httpClient = new HttpClientMock(200, jsonResponse.toString()); - + HttpClientMock httpClient = new HttpClientMock(200, userJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); - User user = toopherAPI.advanced.users.getById(id); + User user = toopherAPI.advanced.users.getById(userId); - assertEquals(httpClient.getLastCalledMethod(), "GET"); - assertEquals(user.id, id); - assertEquals(user.name, name); - assertFalse(user.toopherAuthenticationEnabled); + assertEquals("GET", httpClient.getLastCalledMethod()); + assertEquals(String.format("users/%s", userId), httpClient.getLastCalledEndpoint()); + assertEquals(userId, user.id); + assertEquals(userName, user.name); + assertTrue("Toopher authentication should be enabled for user.", user.toopherAuthenticationEnabled); } @Test public void testAdvancedUsersGetByName() throws InterruptedException, RequestError { - JSONObject usersJsonResponse = new JSONObject(); - usersJsonResponse.put("id", id); - usersJsonResponse.put("name", name); - usersJsonResponse.put("enabled", true); - usersJsonResponse.put("disable_toopher_auth", false); JSONArray usersJsonArray = new JSONArray(); - usersJsonArray.put(usersJsonResponse); + usersJsonArray.put(userJsonResponse); Map expectedUriResponses = new HashMap(); - expectedUriResponses.put(createURI(String.format("https://api.toopher.test/v1/users/%s", id)), new ResponseMock(200, usersJsonResponse.toString())); - expectedUriResponses.put(createURI("https://api.toopher.test/v1/users?name=name"), new ResponseMock(200, usersJsonArray.toString())); + expectedUriResponses.put(createURI(String.format("https://api.toopher.test/v1/users?name=%s", userName)), new ResponseMock(200, usersJsonArray.toString())); + expectedUriResponses.put(createURI(String.format("https://api.toopher.test/v1/users/%s", userId)), new ResponseMock(200, userJsonResponse.toString())); HttpClientMock httpClient = new HttpClientMock(expectedUriResponses); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); - User user = toopherAPI.advanced.users.getByName(name); - String actualResponse = httpClient.getExpectedResponse(); - String expectedResponse = usersJsonResponse.toString(); - - assertEquals(expectedResponse, actualResponse); - assertEquals(user.id, id); - assertEquals(user.name, name); - assertTrue(user.toopherAuthenticationEnabled); + User user = toopherAPI.advanced.users.getByName(userName); + + assertEquals("GET", httpClient.getLastCalledMethod()); + assertEquals(String.format("users/%s", userId), httpClient.getLastCalledEndpoint()); + assertEquals(userId, user.id); + assertEquals(userName, user.name); + assertTrue("Toopher authentication should be enabled for user.", user.toopherAuthenticationEnabled); } @Test - public void testAdvancedUserTerminalsGetById() throws InterruptedException, RequestError { - JSONObject response = new JSONObject(); - response.put("id", id); - response.put("name", name); - response.put("name_extra", terminalNameExtra); - response.put("user", user); + public void testAdvancedUserTerminalsCreate() throws InterruptedException, RequestError { + HttpClientMock httpClient = new HttpClientMock(200, userTerminalJsonResponse.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + UserTerminal userTerminal = toopherAPI.advanced.userTerminals.create(userName, terminalName, terminalNameExtra); + + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("user_terminals/create", httpClient.getLastCalledEndpoint()); + assertEquals(userName, httpClient.getLastCalledData("user_name")); + assertEquals(terminalName, httpClient.getLastCalledData("name")); + assertEquals(terminalNameExtra, httpClient.getLastCalledData("name_extra")); + assertEquals(terminalId, userTerminal.id); + } - HttpClientMock httpClient = new HttpClientMock(200, response.toString()); + @Test + public void testAdvancedUserTerminalsCreateWithExtras() throws InterruptedException, RequestError { + Map extras = new HashMap(); + extras.put("foo", "bar"); + HttpClientMock httpClient = new HttpClientMock(200, userTerminalJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", createURI(DEFAULT_BASE_URL), httpClient); - UserTerminal userTerminal = toopherAPI.advanced.userTerminals.getById(id); - - assertEquals(httpClient.getLastCalledMethod(), "GET"); - assertEquals(userTerminal.id, id); - assertEquals(userTerminal.name, name); - assertEquals(userTerminal.requesterSpecifiedId, terminalNameExtra); - assertEquals(userTerminal.user.id, userId); - assertEquals(userTerminal.user.name, userName); + UserTerminal userTerminal = toopherAPI.advanced.userTerminals.create(userName, terminalName, terminalNameExtra, extras); + + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("user_terminals/create", httpClient.getLastCalledEndpoint()); + assertEquals("bar", httpClient.getLastCalledData("foo")); + assertEquals(userName, httpClient.getLastCalledData("user_name")); + assertEquals(terminalName, httpClient.getLastCalledData("name")); + assertEquals(terminalNameExtra, httpClient.getLastCalledData("name_extra")); + assertEquals(terminalId, userTerminal.id); } - private URI createURI(String url) { - try { - return new URL(url).toURI(); - } catch (MalformedURLException e) { - return null; - } catch (URISyntaxException e) { - return null; - } + @Test + public void testAdvancedUserTerminalsGetById() throws InterruptedException, RequestError { + HttpClientMock httpClient = new HttpClientMock(200, userTerminalJsonResponse.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + UserTerminal userTerminal = toopherAPI.advanced.userTerminals.getById(terminalId); + + assertEquals("GET", httpClient.getLastCalledMethod()); + assertEquals(String.format("user_terminals/%s", terminalId), httpClient.getLastCalledEndpoint()); + assertEquals(terminalId, userTerminal.id); + assertEquals(userId, userTerminal.user.id); + } + + @Test + public void testRawGet() throws InterruptedException, RequestError { + String endpoint = String.format("pairings/%s", id); + + HttpClientMock httpClient = new HttpClientMock(200, pairingJsonResponse.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + toopherAPI.advanced.raw.get(endpoint); + + assertEquals("GET", httpClient.getLastCalledMethod()); + assertEquals(endpoint, httpClient.getLastCalledEndpoint()); + assertEquals(pairingJsonResponse.toString(), httpClient.getExpectedResponse()); } - private boolean isValidURL(String url) { - return createURI(url) != null; + @Test + public void testRawPost() throws InterruptedException, RequestError { + String endpoint = "users/create"; + List params = new ArrayList(); + params.add(new BasicNameValuePair("name", userName)); + + HttpClientMock httpClient = new HttpClientMock(200, userJsonResponse.toString()); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + createURI(DEFAULT_BASE_URL), httpClient); + toopherAPI.advanced.raw.post(endpoint, params); + + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals(endpoint, httpClient.getLastCalledEndpoint()); + assertEquals(userJsonResponse.toString(), httpClient.getExpectedResponse()); } @Test public void testBaseURL() { + boolean isValidURL = createURI((ToopherAPI.getBaseURL())) != null; + assertNotNull("Base URL is null.", ToopherAPI.getBaseURL()); - assertTrue("Base URL is not valid.", isValidURL(ToopherAPI.getBaseURL())); + assertTrue("Base URL is not valid.", isValidURL); } @Test public void testVersion() { assertNotNull("Version is not null.", ToopherAPI.VERSION); } + + private URI createURI(String url) { + try { + return new URL(url).toURI(); + } catch (MalformedURLException e) { + return null; + } catch (URISyntaxException e) { + return null; + } + } } From c2787bfff456c35be00d2961dc9d37a6bf6b9944 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 13:10:23 -0600 Subject: [PATCH 083/195] Clean up tests for ToopherIframe --- .../java/com/toopher/TestToopherIframe.java | 67 +++++++++---------- 1 file changed, 31 insertions(+), 36 deletions(-) diff --git a/src/test/java/com/toopher/TestToopherIframe.java b/src/test/java/com/toopher/TestToopherIframe.java index d5db6c7..5008437 100644 --- a/src/test/java/com/toopher/TestToopherIframe.java +++ b/src/test/java/com/toopher/TestToopherIframe.java @@ -12,12 +12,13 @@ import static org.junit.Assert.*; public class TestToopherIframe { - static private final String TOOPHER_CONSUMER_KEY = "abcdefg"; - static private final String TOOPHER_CONSUMER_SECRET = "hijklmnop"; - static private final String REQUEST_TOKEN = "s9s7vsb"; - static private final long REQUEST_TTL = 100L; - static private final String OAUTH_NONCE = "12345678"; - static private final Date TEST_DATE = new Date(1000000); + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; + private static final String TOOPHER_CONSUMER_KEY = "abcdefg"; + private static final String TOOPHER_CONSUMER_SECRET = "hijklmnop"; + private static final String REQUEST_TOKEN = "s9s7vsb"; + private static final long REQUEST_TTL = 100L; + private static final String OAUTH_NONCE = "12345678"; + private static final Date TEST_DATE = new Date(1000000); private ToopherIframe iframeApi; @@ -30,7 +31,7 @@ static Map nvp2map(List lnvp) { } @Before public void setUp() { - this.iframeApi = new ToopherIframe(TOOPHER_CONSUMER_KEY, TOOPHER_CONSUMER_SECRET, "https://api.toopher.test/v1/"); + this.iframeApi = new ToopherIframe(TOOPHER_CONSUMER_KEY, TOOPHER_CONSUMER_SECRET, DEFAULT_BASE_URL); } @Test @@ -38,56 +39,51 @@ public void testGetAuthenticationUrl(){ ToopherIframe.setDateOverride(TEST_DATE); ToopherIframe.setNonceOverride(OAUTH_NONCE); String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1300&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=YN%2BkKNTaoypsB37fsjvMS8vsG5A%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; - assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN)); + String authenticationUrl = iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN); + + assertEquals(expected, authenticationUrl); } @Test public void testGetAuthenticationUrlWithExtras() { - ToopherIframe.setDateOverride(TEST_DATE); - ToopherIframe.setNonceOverride(OAUTH_NONCE); - String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1100&automation_allowed=false&challenge_required=true&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=TUgywVd77mWpffzdwjjQJ7ooYPM%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; Map extras = new HashMap(); extras.put("allow_inline_pairing", "false"); extras.put("automation_allowed", "false"); extras.put("challenge_required", "true"); extras.put("ttl", Long.toString(REQUEST_TTL)); - assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN,extras)); + ToopherIframe.setDateOverride(TEST_DATE); + ToopherIframe.setNonceOverride(OAUTH_NONCE); + String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=Log+In&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=None&expires=1100&automation_allowed=false&challenge_required=true&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=TUgywVd77mWpffzdwjjQJ7ooYPM%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + String authenticationUrl = iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN, extras); + + assertEquals(expected, authenticationUrl); } @Test public void testGetAuthenticationUrlWithOptionalArgsAndExtras() { - ToopherIframe.setDateOverride(TEST_DATE); - ToopherIframe.setNonceOverride(OAUTH_NONCE); - String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=it+is+a+test&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=metadata&expires=1100&automation_allowed=false&challenge_required=true&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=61dqeQNPFxNy8PyEFB9e5UfgN8s%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; Map extras = new HashMap(); extras.put("allow_inline_pairing", "false"); extras.put("automation_allowed", "false"); extras.put("challenge_required", "true"); extras.put("ttl", Long.toString(REQUEST_TTL)); - assertEquals(expected, iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN, "it is a test", "metadata", extras)); - } -// Do we prefer this type of test or the one above? -// @Test -// public void testGetAuthenticationUrlWithOptionalArgsAndExtras() { -// ToopherIframe.setDateOverride(TEST_DATE); -// ToopherIframe.setNonceOverride(OAUTH_NONCE); -// Map extras = new HashMap(); -// extras.put("allowInlinePairing", "false"); -// extras.put("automationAllowed", "false"); -// extras.put("challengeRequired", "true"); -// extras.put("ttl", Long.toString(REQUEST_TTL)); -// Map params = nvp2map(URLEncodedUtils.parse(iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN, "it is a test", "metadata", extras), Charset.forName("UTF-8"))); -// assertEquals("hKogqI/gjKXpYIH+jNDhRSi22b4=", params.get("oauth_signature")); -// } + ToopherIframe.setDateOverride(TEST_DATE); + ToopherIframe.setNonceOverride(OAUTH_NONCE); + String expected = "https://api.toopher.test/v1/web/authenticate?v=2&username=jdoe&action_name=it+is+a+test&reset_email=jdoe%40example.com&session_token=s9s7vsb&requester_metadata=metadata&expires=1100&automation_allowed=false&challenge_required=true&allow_inline_pairing=false&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=61dqeQNPFxNy8PyEFB9e5UfgN8s%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; + String authenticationUrl = iframeApi.getAuthenticationUrl("jdoe", "jdoe@example.com", REQUEST_TOKEN, "it is a test", "metadata", extras); + + assertEquals(expected, authenticationUrl); + } @Test public void testGetUserManagementUrl() { ToopherIframe.setDateOverride(TEST_DATE); ToopherIframe.setNonceOverride(OAUTH_NONCE); String expected = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1300&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=NjwH5yWPE2CCJL8v%2FMNknL%2BeTpE%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; - assertEquals(expected, iframeApi.getUserManagementUrl("jdoe", "jdoe@example.com")); + String userManagementUrl = iframeApi.getUserManagementUrl("jdoe", "jdoe@example.com"); + + assertEquals(expected, userManagementUrl); } @Test @@ -97,11 +93,13 @@ public void testGetUserManagementUrlWithExtras() { Map extras = new HashMap(); extras.put("ttl", Long.toString(REQUEST_TTL)); String expected = "https://api.toopher.test/v1/web/manage_user?v=2&username=jdoe&reset_email=jdoe%40example.com&expires=1100&oauth_consumer_key=abcdefg&oauth_nonce=12345678&oauth_signature=sV8qoKnxJ3fxfP6AHNa0eNFxzJs%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1000&oauth_version=1.0"; - assertEquals(expected, iframeApi.getUserManagementUrl("jdoe", "jdoe@example.com", extras)); + String userManagementUrl = iframeApi.getUserManagementUrl("jdoe", "jdoe@example.com", extras); + + assertEquals(expected, userManagementUrl); } @Test - public void testValidateGoodSignatureIsSuccessful(){ + public void testValidateGoodSignatureIsSuccessful() { Map data = new HashMap(); data.put("foo", new String[] {"bar"}); data.put("timestamp", new String[] { String.valueOf(TEST_DATE.getTime() / 1000)}); @@ -109,7 +107,6 @@ public void testValidateGoodSignatureIsSuccessful(){ data.put("toopher_sig", new String[] { "6d2c7GlQssGmeYYGpcf+V/kirOI=" }); ToopherIframe.setDateOverride(TEST_DATE); - try { assertNotNull(iframeApi.validatePostback(data, REQUEST_TOKEN, 5)); } catch (ToopherIframe.SignatureValidationError e) { @@ -144,7 +141,6 @@ public void testValidateExpiredSignatureFails() { // set ToopherIframe reference clock 6 seconds ahead ToopherIframe.setDateOverride(new Date(TEST_DATE.getTime() + (1000 * 6))); - try { iframeApi.validatePostback(data, REQUEST_TOKEN, 5); fail(); @@ -161,7 +157,6 @@ public void testValidateMissingTimestampFails() { data.put("toopher_sig", new String[] { "6d2c7GlQssGmeYYGpcf+V/kirOI=" }); ToopherIframe.setDateOverride(TEST_DATE); - try { iframeApi.validatePostback(data, REQUEST_TOKEN, 5); fail(); From 1136bb41a744210ef24242e0b8f5d965d7850521 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 13:28:10 -0600 Subject: [PATCH 084/195] Remove leading / from User.reset endpoint --- src/main/java/com/toopher/User.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index 4ad1582..0b1d236 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -69,7 +69,7 @@ public void disableToopherAuthentication() throws RequestError { } public void reset() throws RequestError { - String endpoint = "/users/reset"; + String endpoint = "users/reset"; List params = new ArrayList(); params.add(new BasicNameValuePair("name", name)); api.advanced.raw.post(endpoint, params); From 463276b2abef94cba6d3dbb4f41d1b077c9123ae Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 13:55:07 -0600 Subject: [PATCH 085/195] Initialize json responses in @BeforeClass --- src/test/java/com/toopher/TestToopherAPI.java | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/src/test/java/com/toopher/TestToopherAPI.java b/src/test/java/com/toopher/TestToopherAPI.java index a8f2380..58177fd 100644 --- a/src/test/java/com/toopher/TestToopherAPI.java +++ b/src/test/java/com/toopher/TestToopherAPI.java @@ -31,10 +31,10 @@ public class TestToopherAPI { private static String terminalName; private static String terminalNameExtra; - private static JSONObject pairingJsonResponse; - private static JSONObject authenticationJsonResponse; - private static JSONObject userJsonResponse; - private static JSONObject userTerminalJsonResponse; + private static JSONObject pairingJsonResponse = new JSONObject(); + private static JSONObject authenticationJsonResponse = new JSONObject(); + private static JSONObject userJsonResponse = new JSONObject(); + private static JSONObject userTerminalJsonResponse = new JSONObject(); @BeforeClass public static void setUpBeforeClass() { @@ -60,17 +60,12 @@ public static void setUpBeforeClass() { terminal.put("name", terminalName); terminal.put("name_extra", terminalNameExtra); terminal.put("user", user); - } - @Before - public void setUp() { - this.pairingJsonResponse = new JSONObject(); pairingJsonResponse.put("id", id); pairingJsonResponse.put("enabled", true); pairingJsonResponse.put("pending", false); pairingJsonResponse.put("user", user); - this.authenticationJsonResponse = new JSONObject(); authenticationJsonResponse.put("id", id); authenticationJsonResponse.put("pending", false); authenticationJsonResponse.put("granted", false); @@ -81,12 +76,10 @@ public void setUp() { authenticationJsonResponse.put("action", action); authenticationJsonResponse.put("user", user); - this.userJsonResponse = new JSONObject(); userJsonResponse.put("id", userId); userJsonResponse.put("name", userName); userJsonResponse.put("disable_toopher_auth", false); - this.userTerminalJsonResponse = new JSONObject(); userTerminalJsonResponse.put("id", terminalId); userTerminalJsonResponse.put("name", terminalName); userTerminalJsonResponse.put("name_extra", terminalNameExtra); From 93998ee2ecc68769caa4e85d01f9dc443f359f7c Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 13:58:13 -0600 Subject: [PATCH 086/195] Clean up and add tests for User --- src/test/java/com/toopher/TestUser.java | 100 +++++++++++++++--------- 1 file changed, 64 insertions(+), 36 deletions(-) diff --git a/src/test/java/com/toopher/TestUser.java b/src/test/java/com/toopher/TestUser.java index 62a1f79..62a55f1 100644 --- a/src/test/java/com/toopher/TestUser.java +++ b/src/test/java/com/toopher/TestUser.java @@ -2,6 +2,7 @@ import org.json.JSONObject; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.net.URI; @@ -11,43 +12,45 @@ public class TestUser { - private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; - - private String id; - private String name; - private boolean disableToopherAuthentication; - private JSONObject json; - - @Before - public void setUp() { - this.id = UUID.randomUUID().toString(); - this.name = "userName"; - this.disableToopherAuthentication = false; - this.json = new JSONObject(); - this.json.put("id", id); - this.json.put("name", name); - this.json.put("disable_toopher_auth", disableToopherAuthentication); + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; + + private static String id; + private static String name; + private static JSONObject json; + + @BeforeClass + public static void setUp() { + id = UUID.randomUUID().toString(); + name = "userName"; + + json = new JSONObject(); + json.put("id", id); + json.put("name", name); + json.put("disable_toopher_auth", false); } @Test public void testRefreshFromServer() throws InterruptedException, RequestError { JSONObject newJson = new JSONObject(); newJson.put("name", "userNameChanged"); - newJson.put("disable_toopher_auth", "true"); + newJson.put("disable_toopher_auth", true); HttpClientMock httpClient = new HttpClientMock(200, newJson.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); User user = new User(json, toopherAPI); - assertEquals(user.id, id); - assertEquals(user.name, name); - assertTrue(user.toopherAuthenticationEnabled); + + assertEquals(id, user.id); + assertEquals(name, user.name); + assertTrue("User should be Toopher authentication enabled.", user.toopherAuthenticationEnabled); user.refreshFromServer(); - assertEquals(user.id, id); - assertEquals(user.name, "userNameChanged"); - assertFalse(user.toopherAuthenticationEnabled); + assertEquals("GET", httpClient.getLastCalledMethod()); + assertEquals(String.format("users/%s", id), httpClient.getLastCalledEndpoint()); + assertEquals(id, user.id); + assertEquals("userNameChanged", user.name); + assertFalse("User should not be Toopher authentication enabled.", user.toopherAuthenticationEnabled); } @Test @@ -55,18 +58,20 @@ public void testEnableToopherAuthentication() throws InterruptedException, Reque JSONObject newJson = new JSONObject(); newJson.put("id", id); newJson.put("name", name); - newJson.put("disable_toopher_auth", "false"); + newJson.put("disable_toopher_auth", false); HttpClientMock httpClient = new HttpClientMock(200, newJson.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); User user = new User(json, toopherAPI); - user.enableToopherAuthentication(); - assertEquals(user.id, id); - assertEquals(user.name, name); - assertTrue(user.toopherAuthenticationEnabled); + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals(String.format("users/%s", id), httpClient.getLastCalledEndpoint()); + assertEquals("false", httpClient.getLastCalledData("disable_toopher_auth")); + assertEquals(id, user.id); + assertEquals(name, user.name); + assertTrue("User should be Toopher authentication enabled.", user.toopherAuthenticationEnabled); } @Test @@ -82,9 +87,12 @@ public void testDisableToopherAuthentication() throws InterruptedException, Requ User user = new User(json, toopherAPI); user.disableToopherAuthentication(); - assertEquals(user.id, id); - assertEquals(user.name, name); - assertFalse(user.toopherAuthenticationEnabled); + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals(String.format("users/%s", id), httpClient.getLastCalledEndpoint()); + assertEquals("true", httpClient.getLastCalledData("disable_toopher_auth")); + assertEquals(id, user.id); + assertEquals(name, user.name); + assertFalse("User should not be Toopher authentication enabled.", user.toopherAuthenticationEnabled); } @Test @@ -93,10 +101,30 @@ public void testReset() throws InterruptedException, RequestError { ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); User user = new User(json, toopherAPI); - try { - user.reset(); - } catch (RequestError re) { - fail(); - } + user.reset(); + + assertEquals("POST", httpClient.getLastCalledMethod()); + assertEquals("users/reset", httpClient.getLastCalledEndpoint()); + assertEquals(name, httpClient.getLastCalledData("name")); + } + + @Test + public void testUpdate() throws InterruptedException { + JSONObject updatedJson = new JSONObject(); + updatedJson.put("name", "userNameChanged"); + updatedJson.put("disable_toopher_auth", true); + + HttpClientMock httpClient = new HttpClientMock(200, "{}"); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + User user = new User(json, toopherAPI); + + assertEquals(name, user.name); + assertTrue("User should be Toopher authentication enabled.", user.toopherAuthenticationEnabled); + + user.update(updatedJson); + + assertEquals("userNameChanged", user.name); + assertFalse("User should not be Toopher authentication enabled.", user.toopherAuthenticationEnabled); } } From 53b6310319e3132e1227bdefed83cce32c7f8023 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 13:58:13 -0600 Subject: [PATCH 087/195] Clean up and add tests for User --- src/test/java/com/toopher/TestUser.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/com/toopher/TestUser.java b/src/test/java/com/toopher/TestUser.java index 62a55f1..03e3337 100644 --- a/src/test/java/com/toopher/TestUser.java +++ b/src/test/java/com/toopher/TestUser.java @@ -1,7 +1,6 @@ package com.toopher; import org.json.JSONObject; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; From 401a531a127d332fd1148e91cde0ab44d58d3f01 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 14:15:41 -0600 Subject: [PATCH 088/195] Clean up and add tests for UserTerminal --- .../java/com/toopher/TestUserTerminal.java | 90 ++++++++++++------- 1 file changed, 57 insertions(+), 33 deletions(-) diff --git a/src/test/java/com/toopher/TestUserTerminal.java b/src/test/java/com/toopher/TestUserTerminal.java index 16bd51e..569ce71 100644 --- a/src/test/java/com/toopher/TestUserTerminal.java +++ b/src/test/java/com/toopher/TestUserTerminal.java @@ -1,7 +1,7 @@ package com.toopher; import org.json.JSONObject; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.net.URI; @@ -11,33 +11,33 @@ public class TestUserTerminal { - private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1"; - - private String id; - private String name; - private String requesterSpecifiedId; - public JSONObject user; - public String userName; - - @Before - public void setUp() { - this.id = UUID.randomUUID().toString(); - this.name = "terminalName"; - this.requesterSpecifiedId = "terminalNameExtra"; - this.user = new JSONObject(); - this.user.put("id", UUID.randomUUID().toString()); - this.user.put("name", "userName"); - this.userName = this.user.getString("name"); + private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; + + private static String id; + private static String name; + private static String requesterSpecifiedId; + private static JSONObject terminalJson = new JSONObject(); + private static JSONObject user = new JSONObject(); + private static String userName; + + @BeforeClass + public static void setUp() { + id = UUID.randomUUID().toString(); + name = "terminalName"; + requesterSpecifiedId = "terminalNameExtra"; + + user.put("id", UUID.randomUUID().toString()); + user.put("name", "userName"); + userName = user.getString("name"); + + terminalJson.put("id", id); + terminalJson.put("name", name); + terminalJson.put("name_extra", requesterSpecifiedId); + terminalJson.put("user", user); } @Test public void testRefreshFromServer() throws InterruptedException, RequestError { - JSONObject jsonResponse = new JSONObject(); - jsonResponse.put("id", id); - jsonResponse.put("name", name); - jsonResponse.put("name_extra", requesterSpecifiedId); - jsonResponse.put("user", user); - JSONObject newJsonResponse = new JSONObject(); newJsonResponse.put("name", "terminalNameChanged"); newJsonResponse.put("name_extra", "terminalNameExtraChanged"); @@ -48,17 +48,41 @@ public void testRefreshFromServer() throws InterruptedException, RequestError { HttpClientMock httpClient = new HttpClientMock(200, newJsonResponse.toString()); ToopherAPI toopherAPI = new ToopherAPI("key", "secret", URI.create(DEFAULT_BASE_URL), httpClient); - UserTerminal terminal = new UserTerminal(jsonResponse, toopherAPI); - assertEquals(terminal.id, id); - assertEquals(terminal.name, name); - assertEquals(terminal.requesterSpecifiedId, requesterSpecifiedId); - assertEquals(terminal.user.name, userName); + UserTerminal terminal = new UserTerminal(terminalJson, toopherAPI); + + assertEquals(id, terminal.id, id); + assertEquals(name, terminal.name, name); + assertEquals(requesterSpecifiedId, terminal.requesterSpecifiedId); + assertEquals(userName, terminal.user.name, userName); terminal.refreshFromServer(); - assertEquals(terminal.id, id); - assertEquals(terminal.name, "terminalNameChanged"); - assertEquals(terminal.requesterSpecifiedId, "terminalNameExtraChanged"); - assertEquals(terminal.user.name, "userNameChanged"); + assertEquals("GET", httpClient.getLastCalledMethod()); + assertEquals(String.format("user_terminals/%s", id), httpClient.getLastCalledEndpoint()); + assertEquals(id, terminal.id); + assertEquals("terminalNameChanged", terminal.name); + assertEquals("terminalNameExtraChanged", terminal.requesterSpecifiedId); + assertEquals("userNameChanged", terminal.user.name); + } + + @Test + public void testUpdate() throws InterruptedException { + JSONObject updatedJson = new JSONObject(); + updatedJson.put("name", "terminalNameChanged"); + updatedJson.put("name_extra", "terminalNameExtraChanged"); + JSONObject updatedUser = new JSONObject(); + updatedUser.put("name", "userNameChanged"); + updatedJson.put("user", updatedUser); + + HttpClientMock httpClient = new HttpClientMock(200, "{}"); + ToopherAPI toopherAPI = new ToopherAPI("key", "secret", + URI.create(DEFAULT_BASE_URL), httpClient); + UserTerminal terminal = new UserTerminal(terminalJson, toopherAPI); + terminal.update(updatedJson); + + assertEquals(id, terminal.id); + assertEquals("terminalNameChanged", terminal.name); + assertEquals("terminalNameExtraChanged", terminal.requesterSpecifiedId); + assertEquals("userNameChanged", terminal.user.name); } } From 49fc0baa1ff333ad910dcd50bad5181f27586cd7 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 14:31:06 -0600 Subject: [PATCH 089/195] Use @BeforeClass instead of @Before for TestAuthenticationRequest --- .../toopher/TestAuthenticationRequest.java | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/src/test/java/com/toopher/TestAuthenticationRequest.java b/src/test/java/com/toopher/TestAuthenticationRequest.java index 8a6bb48..5e67868 100644 --- a/src/test/java/com/toopher/TestAuthenticationRequest.java +++ b/src/test/java/com/toopher/TestAuthenticationRequest.java @@ -1,7 +1,7 @@ package com.toopher; import org.json.JSONObject; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import java.net.URI; @@ -12,34 +12,35 @@ public class TestAuthenticationRequest { private static final String DEFAULT_BASE_URL = "https://api.toopher.test/v1/"; - private String id; - private String reason; - private JSONObject jsonResponse; - private String userName; - private String terminalName; - private String terminalNameExtra; + private static String id; + private static String reason; + private static JSONObject jsonResponse = new JSONObject(); + private static String userName; + private static String terminalName; + private static String terminalNameExtra; - @Before - public void setUp() { - this.id = UUID.randomUUID().toString(); - this.reason = "it is a test"; + @BeforeClass + public static void setUp() { + id = UUID.randomUUID().toString(); + reason = "it is a test"; JSONObject user = new JSONObject(); user.put("id", UUID.randomUUID().toString()); user.put("name", "userName"); - this.userName = user.getString("name"); + userName = user.getString("name"); + JSONObject terminal = new JSONObject(); terminal.put("id", UUID.randomUUID().toString()); terminal.put("name", "terminalName"); terminal.put("name_extra", "terminalNameExtra"); terminal.put("user", user); - this.terminalName = terminal.getString("name"); - this.terminalNameExtra = terminal.getString("name_extra"); + terminalName = terminal.getString("name"); + terminalNameExtra = terminal.getString("name_extra"); + JSONObject action = new JSONObject(); action.put("id", UUID.randomUUID().toString()); action.put("name", "log in"); - this.jsonResponse = new JSONObject(); jsonResponse.put("id", id); jsonResponse.put("pending", true); jsonResponse.put("granted", false); From 6d4fcb3b375f1969b8941a591f452ace11063df9 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 14:47:41 -0600 Subject: [PATCH 090/195] Add javadocs and clean up UserTerminal --- src/main/java/com/toopher/UserTerminal.java | 43 +++++++++++++++++---- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index 508e795..20f9aa6 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -8,10 +8,29 @@ * */ public class UserTerminal extends ApiResponseObject { + /** + * The ToopherAPI object associated with this user terminal + */ public ToopherAPI api; + + /** + * The unique id for the user terminal + */ public String id; + + /** + * The name of the user terminal + */ public String name; + + /** + * The unique id specified by the requester + */ public String requesterSpecifiedId; + + /** + * The User object associated with the user terminal + */ public User user; public UserTerminal (JSONObject json, ToopherAPI toopherAPI) throws JSONException { @@ -20,29 +39,37 @@ public UserTerminal (JSONObject json, ToopherAPI toopherAPI) throws JSONExceptio this.api = toopherAPI; this.id = json.getString("id"); this.name = json.getString("name"); - if (json.has("name_extra")) { - this.requesterSpecifiedId = json.getString("name_extra"); - } + this.requesterSpecifiedId = json.getString("name_extra"); this.user = new User(json.getJSONObject("user"), toopherAPI); } @Override public String toString() { - return String.format("[UserTerminal: id=%s; name=%s; requesterSpecifiedId=%s; userName=%s; userId=%s]", - id, name, requesterSpecifiedId, user.name, user.id); + return String.format("[UserTerminal: id=%s; name=%s; requesterSpecifiedId=%s; userName=%s; userId=%s; userToopherAuthenticationEnabled=%b]", + id, name, requesterSpecifiedId, user.name, user.id, user.toopherAuthenticationEnabled); } + /** + * Update the UserTerminal object with JSON response from the server + * + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public void refreshFromServer() throws RequestError { String endpoint = String.format("user_terminals/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); } + /** + * Update the UserTerminal object with JSON response + * + * @param jsonResponse + * The JSON response received from the server + */ public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); - if (jsonResponse.has("name_extra")) { - this.requesterSpecifiedId = jsonResponse.getString("name_extra"); - } + this.requesterSpecifiedId = jsonResponse.getString("name_extra"); this.user.update(jsonResponse.getJSONObject("user")); } } From 383d5bea9da17ceffda1a8240716651bc007eff6 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 15:06:41 -0600 Subject: [PATCH 091/195] Add ApiResponseObject.updateRawResponse for updates --- src/main/java/com/toopher/ApiResponseObject.java | 4 ++++ src/main/java/com/toopher/UserTerminal.java | 1 + 2 files changed, 5 insertions(+) diff --git a/src/main/java/com/toopher/ApiResponseObject.java b/src/main/java/com/toopher/ApiResponseObject.java index fd7bd92..2446de0 100644 --- a/src/main/java/com/toopher/ApiResponseObject.java +++ b/src/main/java/com/toopher/ApiResponseObject.java @@ -17,6 +17,10 @@ public ApiResponseObject(JSONObject json) throws JSONException { this.rawResponse = jsonToMap(json); } + public void updateRawResponse(JSONObject json) { + this.rawResponse = jsonToMap(json); + } + private Map jsonToMap(JSONObject json) throws JSONException{ Map result = new HashMap(); diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index 20f9aa6..d5826fc 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -71,5 +71,6 @@ public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); this.requesterSpecifiedId = jsonResponse.getString("name_extra"); this.user.update(jsonResponse.getJSONObject("user")); + this.updateRawResponse(jsonResponse); } } From 4d70f0692855896785d17ab7597911495154d402 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 15:08:21 -0600 Subject: [PATCH 092/195] Add javadocs and clean up User --- src/main/java/com/toopher/User.java | 43 +++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index 0b1d236..2dbd133 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -14,7 +14,7 @@ */ public class User extends ApiResponseObject { /** - * The ToopherAPI associated with this user + * The ToopherAPI object associated with this user */ public ToopherAPI api; @@ -29,7 +29,7 @@ public class User extends ApiResponseObject { public String name; /** - * Whether or not the user is Toopher-enabled + * The Toopher-enabled status of the user */ public boolean toopherAuthenticationEnabled; @@ -45,13 +45,31 @@ public User (JSONObject json, ToopherAPI toopherAPI) throws JSONException { this.toopherAuthenticationEnabled = true; } } - + + @Override + public String toString() { + return String.format("[User: id=%s, name=%s, toopherAuthenticationEnabled=%b]", + id, name, toopherAuthenticationEnabled); + } + + /** + * Update the User object with JSON response from the API + * + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public void refreshFromServer() throws RequestError { String endpoint = String.format("users/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); } + /** + * Enable Toopher authentication for the user + * + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public void enableToopherAuthentication() throws RequestError { String endpoint = String.format("users/%s", id); List params = new ArrayList(); @@ -60,6 +78,12 @@ public void enableToopherAuthentication() throws RequestError { update(result); } + /** + * Disable Toopher authentication for the user + * + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public void disableToopherAuthentication() throws RequestError { String endpoint = String.format("users/%s", id); List params = new ArrayList(); @@ -68,6 +92,12 @@ public void disableToopherAuthentication() throws RequestError { update(result); } + /** + * Remove all pairings for the user + * + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public void reset() throws RequestError { String endpoint = "users/reset"; List params = new ArrayList(); @@ -75,6 +105,12 @@ public void reset() throws RequestError { api.advanced.raw.post(endpoint, params); } + /** + * Update the User object with JSON response + * + * @param jsonResponse + * The JSON response from the API + */ public void update(JSONObject jsonResponse) { this.name = jsonResponse.getString("name"); if (jsonResponse.has("disable_toopher_auth")) { @@ -82,5 +118,6 @@ public void update(JSONObject jsonResponse) { } else { this.toopherAuthenticationEnabled = true; } + this.updateRawResponse(jsonResponse); } } From 45963715a7c307ae1fd5606d63f050a89df255c3 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 15:50:20 -0600 Subject: [PATCH 093/195] Add javadocs and clean up Pairing --- src/main/java/com/toopher/Pairing.java | 91 ++++++++++++++++++-------- 1 file changed, 65 insertions(+), 26 deletions(-) diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index 8702fd9..cd9deff 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -6,7 +6,6 @@ import org.json.JSONObject; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -16,7 +15,7 @@ */ public class Pairing extends ApiResponseObject { /** - * The ToopherAPI associated with this pairing + * The ToopherAPI object associated with this pairing */ public ToopherAPI api; @@ -31,22 +30,15 @@ public class Pairing extends ApiResponseObject { public boolean enabled; /** - * Indicates if the user has reacted to the pairing request + * Indicates if the user has responded to the pairing request */ public boolean pending; /** - * Contains the unique id and description name for the user associated - * with the pairing request + * The User object associated with the pairing request */ public User user; - @Override - public String toString() { - return String.format("[Pairing: id=%s; userId=%s, userName=%s, pending=%b, enabled=%b]", id, - user.id, user.name, pending, enabled); - } - public Pairing(JSONObject json, ToopherAPI toopherAPI) throws JSONException { super(json); @@ -57,48 +49,95 @@ public Pairing(JSONObject json, ToopherAPI toopherAPI) throws JSONException { this.user = new User(json.getJSONObject("user"), toopherAPI); } + @Override + public String toString() { + return String.format("[Pairing: id=%s; enabled=%b; pending=%b; userId=%s, userName=%s, userToopherAuthenticationEnabled=%b]", + id, enabled, pending, user.id, user.name, user.toopherAuthenticationEnabled); + } + + /** + * Update the Pairing object with JSON response from the API + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public void refreshFromServer() throws RequestError { String endpoint = String.format("pairings/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); } + /** + * Retrieves QR code image for the pairing from the API + * @return QR code image stored in a byte[] + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public byte[] getQrCodeImage() throws RequestError { String endpoint = String.format("qr/pairings/%s", id); return api.advanced.raw.get(endpoint); } - private void update(JSONObject jsonResponse) { - this.enabled = jsonResponse.getBoolean("enabled"); - this.pending = jsonResponse.getBoolean("pending"); - this.user.update(jsonResponse.getJSONObject("user")); - } - + /** + * Retrieves link to allow user to reset the pairing + * @return Reset link stored as a String + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public String getResetLink() throws RequestError { - Map extras = new HashMap(); - return getResetLink(extras); + return getResetLink(null); } + /** + * Retrieves link to allow user to reset the pairing + * @param extras + * An optional Map of extra parameters to provide to the API + * @return Reset link stored as a String + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public String getResetLink(Map extras) throws RequestError { - List params = new ArrayList(); - - for (Map.Entry entry : extras.entrySet()) { - params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } - String endpoint = String.format("pairings/%s/generate_reset_link", id); - JSONObject result = api.advanced.raw.post(endpoint, params); + JSONObject result = api.advanced.raw.post(endpoint, extras); return result.getString("url"); } + /** + * Sends reset link to user via email + * @param email + * The email address where the reset link is sent + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public void emailResetLink(String email) throws RequestError { emailResetLink(email, null); } + /** + * Sends reset link to user via email + * @param email + * The email address where the reset link is sent + * @param extras + * An optional Map of extra parameters to provide to the API + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public void emailResetLink(String email, Map extras) throws RequestError { String endpoint = String.format("pairings/%s/send_reset_link", id); List params = new ArrayList(); params.add(new BasicNameValuePair("reset_email", email)); api.advanced.raw.post(endpoint, params, extras); } + + /** + * Update the Pairing object with JSON response + * + * @param jsonResponse + * The JSON response from the API + */ + private void update(JSONObject jsonResponse) { + this.enabled = jsonResponse.getBoolean("enabled"); + this.pending = jsonResponse.getBoolean("pending"); + this.user.update(jsonResponse.getJSONObject("user")); + this.updateRawResponse(jsonResponse); + } } From c0733fc3ae6b2ad98caaa9be81d8f0522c2fb7e0 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 16:27:37 -0600 Subject: [PATCH 094/195] Update javadocs and clean up Pairing --- src/main/java/com/toopher/Pairing.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index cd9deff..0a0f979 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -25,7 +25,7 @@ public class Pairing extends ApiResponseObject { public String id; /** - * Indicates if the pairing has been enabled by the user + * Indicates if the pairing was enabled by the user */ public boolean enabled; @@ -35,7 +35,7 @@ public class Pairing extends ApiResponseObject { public boolean pending; /** - * The User object associated with the pairing request + * The User associated with the pairing request */ public User user; From d8e15e2dd6fe772eb8331e58e416823fb2766a36 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 16:28:17 -0600 Subject: [PATCH 095/195] Update javadocs and clean up ToopherAPI --- src/main/java/com/toopher/ToopherAPI.java | 159 ++++++++-------------- 1 file changed, 59 insertions(+), 100 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 243fb40..255162e 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -51,7 +51,7 @@ public class ToopherAPI { /** * The ToopherJava binding library version */ - public static final String VERSION = "1.0.0"; + public static final String VERSION = "2.0.0"; /** * Create an API object with the supplied credentials @@ -114,7 +114,6 @@ public ToopherAPI(String consumerKey, String consumerSecret, URI uri) { this(consumerKey, consumerSecret, uri, null); } - /** * Create an API object with the supplied credentials and API URI, * overriding the default HTTP client. @@ -129,7 +128,7 @@ public ToopherAPI(String consumerKey, String consumerSecret, URI uri) { * The alternate HTTP client */ public ToopherAPI(String consumerKey, String consumerSecret, URI uri, HttpClient httpClient) { - this.advanced = new AdvancedApiUsageFactory(consumerKey, consumerSecret, this); + this.advanced = new AdvancedApiUsageFactory(this); if (httpClient == null) { this.httpClient = new DefaultHttpClient(); HttpProtocolParams.setUserAgent(this.httpClient.getParams(), @@ -152,7 +151,6 @@ public ToopherAPI(String consumerKey, String consumerSecret, URI uri, HttpClient } } - /** * Create a QR pairing * @param userName @@ -162,8 +160,7 @@ public ToopherAPI(String consumerKey, String consumerSecret, URI uri, HttpClient * Thrown when an exceptional condition is encountered */ public Pairing pair(String userName) throws RequestError { - Map extras = new HashMap(); - return this.pair(userName, "", extras); + return this.pair(userName, null, null); } /** @@ -178,12 +175,11 @@ public Pairing pair(String userName) throws RequestError { * Thrown when an exceptional condition is encountered */ public Pairing pair(String userName, String pairingPhraseOrNum) throws RequestError { - Map extras = new HashMap(); - return this.pair(userName, pairingPhraseOrNum, extras); + return this.pair(userName, pairingPhraseOrNum, null); } /** - * Create an SMS pairing or regular pairing + * Create an SMS pairing, QR pairing or regular pairing * * @param pairingPhraseOrNum * The pairing phrase or phone number supplied by the user @@ -197,16 +193,11 @@ public Pairing pair(String userName, String pairingPhraseOrNum) throws RequestEr */ public Pairing pair( String userName, String pairingPhraseOrNum, Map extras) throws RequestError { String endpoint; - JSONObject result; - List params = new ArrayList(); - params.add(new BasicNameValuePair("user_name", userName)); - for (Map.Entry entry : extras.entrySet()) { - params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } + params.add(new BasicNameValuePair("user_name", userName)); - if (!pairingPhraseOrNum.isEmpty()) { + if (pairingPhraseOrNum != null) { if (pairingPhraseOrNum.matches("\\d+")) { params.add(new BasicNameValuePair("phone_number", pairingPhraseOrNum)); endpoint = "pairings/create/sms"; @@ -218,13 +209,8 @@ public Pairing pair( String userName, String pairingPhraseOrNum, Map extras = new HashMap(); - return authenticate(pairingIdOrUsername, terminalNameOrTerminalNameExtra, actionName, extras); + return authenticate(pairingIdOrUsername, terminalNameOrTerminalNameExtra, actionName, null); } /** @@ -294,13 +279,17 @@ public AuthenticationRequest authenticate(String pairingIdOrUsername, String ter } JSONObject json = advanced.raw.post(endpoint, params, extras); - try { - return new AuthenticationRequest(json, this); - } catch (Exception e) { - throw new RequestError(e); - } + return new AuthenticationRequest(json, this); } - + + public static String getBaseURL() { + return String.format("%s://%s%s", DEFAULT_URI_SCHEME, + DEFAULT_URI_HOST, DEFAULT_URI_BASE); + } + + /** + * Extracts JSON response object from API response + */ private static ResponseHandler jsonHandler = new ResponseHandler() { @Override @@ -310,7 +299,7 @@ public Object handleResponse(HttpResponse response) throws IOException, ClientPr parseRequestError(statusLine, response); } - HttpEntity entity = response.getEntity(); // TODO: check entity == null + HttpEntity entity = response.getEntity(); String json; json = (entity != null) ? EntityUtils.toString(entity) : null; @@ -323,10 +312,12 @@ public Object handleResponse(HttpResponse response) throws IOException, ClientPr } else { throw new RequestError("Empty response body returned"); } - } }; + /** + * Extracts QR image byte[] from API response + */ private static ResponseHandler qrResponseHandler = new ResponseHandler() { @Override @@ -348,12 +339,16 @@ public Object handleResponse(HttpResponse response) throws ClientProtocolExcepti } }; - - public static String getBaseURL() { - return String.format("%s://%s%s", DEFAULT_URI_SCHEME, - DEFAULT_URI_HOST, DEFAULT_URI_BASE); - } - + /** + * Throws new error message based on status code provided in API response + * + * @param statusLine + * StatusLine object from API response + * @param response + * API response + * @throws RequestError + * Thrown when exceptional condition is encountered + */ private static void parseRequestError(StatusLine statusLine, HttpResponse response) throws RequestError { HttpEntity errEntity = response.getEntity(); String errBody; @@ -386,7 +381,6 @@ private static void parseRequestError(StatusLine statusLine, HttpResponse respon throw new RequestError(errBody, new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase())); } } else { - // Complete error info is in the HTTP StatusLine throw new RequestError(new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase())); @@ -400,7 +394,7 @@ class AdvancedApiUsageFactory { public final UserTerminals userTerminals; public final ApiRawRequester raw; - public AdvancedApiUsageFactory(String consumerKey, String consumerSecret, ToopherAPI api) { + public AdvancedApiUsageFactory(ToopherAPI api) { pairings = new Pairings(api); authenticationRequests = new AuthenticationRequests(api); users = new Users(api); @@ -420,20 +414,14 @@ public Pairings(ToopherAPI toopherAPI) { * * @param pairingId * The unique id for a pairing - * @return - * A Pairing object + * @return A Pairing object * @throws RequestError * Thrown when an exceptional condition is encountered */ public Pairing getById(String pairingId) throws RequestError { final String endpoint = String.format("pairings/%s", pairingId); - JSONObject json = advanced.raw.get(endpoint); - try { - return new Pairing(json, api); - } catch (Exception e) { - throw new RequestError(e); - } + return new Pairing(json, api); } } @@ -449,20 +437,14 @@ public AuthenticationRequests(ToopherAPI toopherAPI) { * * @param authenticationRequestId * The unique id for an authentication request - * @return - * An AuthenticationRequest object + * @return An AuthenticationRequest object * @throws RequestError * Thrown when an exceptional condition is encountered */ public AuthenticationRequest getById(String authenticationRequestId) throws RequestError { final String endpoint = String.format("authentication_requests/%s", authenticationRequestId); - JSONObject json = advanced.raw.get(endpoint); - try { - return new AuthenticationRequest(json, api); - } catch (Exception e) { - throw new RequestError(e); - } + return new AuthenticationRequest(json, api); } } @@ -478,14 +460,12 @@ public Users(ToopherAPI toopherAPI) { * * @param userName * The name of the user - * @return - * A User object + * @return A User object * @throws RequestError * Thrown when an exceptional condition is encountered */ public User create(String userName) throws RequestError { - Map extras = new HashMap(); - return create(userName, extras); + return create(userName, null); } /** @@ -495,28 +475,16 @@ public User create(String userName) throws RequestError { * The name of the user * @param extras * An optional Map of extra parameters to provide to the API - * @return - * A User object + * @return A User object * @throws RequestError * Thrown when an exceptional condition is encountered */ public User create(String userName, Map extras) throws RequestError { final String endpoint = "users/create"; List params = new ArrayList(); - JSONObject result; - params.add(new BasicNameValuePair("name", userName)); - for (Map.Entry entry : extras.entrySet()) { - params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } - - try { - result = advanced.raw.post(endpoint, params); - } catch (Exception e) { - throw new RequestError(e); - } - + JSONObject result = advanced.raw.post(endpoint, params, extras); return new User(result, api); } @@ -525,36 +493,29 @@ public User create(String userName, Map extras) throws RequestEr * * @param userId * The unique id for a user - * @return - * A User object + * @return A User object * @throws RequestError * Thrown when an exceptional condition is encountered */ public User getById(String userId) throws RequestError { final String endpoint = String.format("users/%s", userId); - JSONObject json = advanced.raw.get(endpoint); - try { - return new User(json, api); - } catch (Exception e) { - throw new RequestError(e); - } + return new User(json, api); } /** * Retrieve the current status of a user with the user name * @param name * The name of the user - * @return - * A User object + * @return A User object * @throws RequestError * Thrown when an exceptional condition is encountered */ public User getByName(String name) throws RequestError { final String endpoint = "users"; - List params = new ArrayList(); params.add(new BasicNameValuePair("name", name)); + JSONArray result = (JSONArray) advanced.raw.get(endpoint, params); if (result.length() > 1) { @@ -563,6 +524,7 @@ public User getByName(String name) throws RequestError { if (result.length() == 0) { throw new RequestError(String.format("No users with name %s", name)); } + String userId = result.getJSONObject(0).getString("id"); return getById(userId); } @@ -607,27 +569,19 @@ public UserTerminal create(String userName, String terminalName, String requeste * be unique for a requester * @param extras * An optional Map of extra parameters to provide to the API - * @return - * A UserTerminal object + * @return A UserTerminal object * @throws RequestError * Thrown when an exceptional condition is encountered */ public UserTerminal create(String userName, String terminalName, String requesterSpecifiedId, Map extras) throws RequestError { final String endpoint = "user_terminals/create"; List params = new ArrayList(); - JSONObject result; params.add(new BasicNameValuePair("user_name", userName)); params.add(new BasicNameValuePair("name", terminalName)); params.add(new BasicNameValuePair("name_extra", requesterSpecifiedId)); - if (extras != null) { - for (Map.Entry entry : extras.entrySet()) { - params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); - } - } - - result = advanced.raw.post(endpoint, params); + JSONObject result = advanced.raw.post(endpoint, params, extras); return new UserTerminal(result, api); } @@ -636,8 +590,7 @@ public UserTerminal create(String userName, String terminalName, String requeste * * @param terminalId * The unique id for a user terminal - * @return - * A UserTerminal object + * @return A UserTerminal object * @throws RequestError * Thrown when an exceptional condition is encountered */ @@ -646,7 +599,6 @@ public UserTerminal getById(String terminalId) throws RequestError { JSONObject result = advanced.raw.get(endpoint); return new UserTerminal(result, api); } - } class ApiRawRequester { @@ -675,14 +627,21 @@ public T post(String endpoint, List params) throws RequestErr return post(endpoint, params, null); } + public T post(String endpoint, Map extras) throws RequestError { + return post(endpoint, null, extras); + } + public T post(String endpoint, List params, Map extras) throws RequestError { HttpPost post = new HttpPost(); + if (params == null) { + params = new ArrayList(); + } if (extras != null && extras.size() > 0) { for (Map.Entry e : extras.entrySet()){ params.add(new BasicNameValuePair(e.getKey(), e.getValue())); } } - if (params != null && params.size() > 0) { + if (params.size() > 0) { try { post.setEntity(new UrlEncodedFormEntity(params)); } catch (Exception e) { From 70a894ba1c5880834e1afb8760685b4e6f47b65a Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Fri, 6 Feb 2015 16:28:32 -0600 Subject: [PATCH 096/195] Update javadocs and clean up AuthenticationRequest --- .../com/toopher/AuthenticationRequest.java | 73 +++++++++++-------- 1 file changed, 42 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index 8ff1559..8a7fd8e 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -7,7 +7,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.Map; /** * Provides information about the status of an authentication request @@ -15,7 +14,7 @@ */ public class AuthenticationRequest extends ApiResponseObject { /** - * The ToopherAPI associated with this request + * The ToopherAPI object associated with this authentication request */ public ToopherAPI api; @@ -25,47 +24,44 @@ public class AuthenticationRequest extends ApiResponseObject { public String id; /** - * Indicates if the request is still pending + * Indicates if the user has responded to the authentication request */ public boolean pending; /** - * Indicates if the request was granted + * Indicates if the authentication request was granted */ public boolean granted; /** - * Indicates if the request was automated + * Indicates if the authentication request was automated */ public boolean automated; /** - * Indicates the reason (if any) for the request's outcome + * Indicates the reason (if any) for the authentication request's outcome */ public String reason; /** - * Indicates the code associated with the reason for the request's outcome + * Indicates the code associated with the reason for the authentication request's outcome */ public int reasonCode; /** - * Contains the unique id and descriptive name for the terminal - * associated with the request + * The UserTerminal associated with the authentication request */ public UserTerminal terminal; /** - * Contains the unique id and descriptive name for the user - * associated with the request + * The Action associated with the request */ - public User user; + public Action action; /** - * Contains the unique id and descriptive name for the action - * associated with the request + * The User associated with the authentication request */ - public Action action; + public User user; public AuthenticationRequest(JSONObject json, ToopherAPI toopherAPI) throws JSONException{ super(json); @@ -79,34 +75,49 @@ public AuthenticationRequest(JSONObject json, ToopherAPI toopherAPI) throws JSON this.reasonCode = json.getInt("reason_code"); this.terminal = new UserTerminal(json.getJSONObject("terminal"), toopherAPI); this.action = new Action(json.getJSONObject("action")); - this.user = terminal.user; + this.user = new User(json.getJSONObject("user"), toopherAPI); } @Override public String toString() { - return String.format("[AuthenticationRequest: id=%s; pending=%b; granted=%b; automated=%b; reason=%s; terminalId=%s; terminalName=%s]", - id, pending, granted, automated, reason, terminal.id, terminal.name); + return String.format("[AuthenticationRequest: id=%s; pending=%b; granted=%b; automated=%b; reason=%s; reasonCode=%d; terminalId=%s, terminalName=%s, terminalRequesterSpecifiedId=%s, actionId=%s, actionName=%s, userId=%s, userName=%s, userToopherAuthenticationEnabled=%b]", + id, pending, granted, automated, reason, reasonCode, terminal.id, terminal.name, terminal.requesterSpecifiedId, action.id, action.name, user.id, user.name, user.toopherAuthenticationEnabled); + } + + /** + * Update the AuthenticationRequest object with JSON response from the API + * + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ + public void refreshFromServer() throws RequestError { + String endpoint = String.format("authentication_requests/%s", id); + JSONObject result = api.advanced.raw.get(endpoint); + update(result); } + /** + * Grants authentication request with OTP + * + * @param otp + * One-time password for authentication request + * @throws RequestError + * Thrown when an exceptional condition is encountered + */ public void grantWithOtp(String otp) throws RequestError { String endpoint = String.format("authentication_requests/%s/otp_auth", id); List params = new ArrayList(); params.add(new BasicNameValuePair("otp", otp)); - - JSONObject json = api.advanced.raw.post(endpoint, params, null); - try { - update(json); - } catch (Exception e) { - throw new RequestError(e); - } - } - - public void refreshFromServer() throws RequestError { - String endpoint = String.format("authentication_requests/%s", id); - JSONObject result = api.advanced.raw.get(endpoint); + JSONObject result = api.advanced.raw.post(endpoint, params); update(result); } + /** + * Update the AuthenticationRequest object with JSON response + * + * @param jsonResponse + * The JSON response from the API + */ private void update(JSONObject jsonResponse) { this.pending = jsonResponse.getBoolean("pending"); this.granted = jsonResponse.getBoolean("granted"); @@ -116,6 +127,6 @@ private void update(JSONObject jsonResponse) { this.terminal.update(jsonResponse.getJSONObject("terminal")); this.action.update(jsonResponse.getJSONObject("action")); this.user.update(jsonResponse.getJSONObject("user")); + this.updateRawResponse(jsonResponse); } - } From 84b694882818353af2144feb653a36fba392c129 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 10:42:10 -0600 Subject: [PATCH 097/195] Update ToopherAPIDemo --- src/main/java/com/toopher/ToopherAPIDemo.java | 116 +++++++++--------- 1 file changed, 60 insertions(+), 56 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPIDemo.java b/src/main/java/com/toopher/ToopherAPIDemo.java index 5481a4b..5b13a5e 100644 --- a/src/main/java/com/toopher/ToopherAPIDemo.java +++ b/src/main/java/com/toopher/ToopherAPIDemo.java @@ -16,7 +16,7 @@ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("======================================"); - System.out.println("Library Usage Demo"); + System.out.println("Toopher Library Demo"); System.out.println("======================================"); URI base_uri = null; @@ -36,72 +36,76 @@ public static void main(String[] args) { System.out.println(""); System.out.println("Setup Credentials"); System.out.println("--------------------------------------"); - System.out.println("Enter your requester credentials (from https://dev.toopher.com)"); - System.out.print("Consumer key: "); + System.out.println("Enter your requester credential details (from https://dev.toopher.com)"); + System.out.print("Toopher Consumer Key: "); String consumerKey = in.nextLine(); - System.out.print("Consumer secret: "); + System.out.print("Toopher Consumer Secret: "); String consumerSecret = in.nextLine(); api = new ToopherAPI (consumerKey, consumerSecret, base_uri); } - - String pairingId; - while (true) { - String pairingPhrase; - while (true) { - System.out.println("Step 1: Pair requester with phone"); - System.out.println("--------------------------------------"); - System.out.println("Pairing phrases are generated on the mobile app"); - System.out.print("Enter pairing phrase: "); - pairingPhrase = in.nextLine(); - - if (pairingPhrase.length() == 0) { - System.out.println("Please enter a pairing phrase to continue"); - } else { - break; - } - } - - System.out.print(String.format("Enter a username for this pairing [%s]: ", DEFAULT_USERNAME)); - String userName = in.nextLine(); - if (userName.length() == 0) { - userName = DEFAULT_USERNAME; - } - - System.out.println("Sending pairing request..."); - - try { - Pairing pairing = api.pair(pairingPhrase, userName); - pairingId = pairing.id; - break; - } catch (RequestError err) { - System.out.println(String.format("The pairing phrase was not accepted (reason:%s)", err.getMessage())); - } - } - while (true) { - System.out.println("Authorize pairing on phone and then press return to continue."); - in.nextLine(); - System.out.println("Checking status of pairing request..."); + String pairingId; + while (true) { + String pairingPhrase; + while (true) { + System.out.println("Step 1: Pair requester with phone"); + System.out.println("--------------------------------------"); + System.out.println("Pairing phrases are generated on the mobile app"); + System.out.print("Enter pairing phrase: "); + pairingPhrase = in.nextLine(); + + if (pairingPhrase.replaceAll("\\s", "").length() == 0) { + System.out.println("Please enter a pairing phrase to continue"); + } else { + break; + } + } + + System.out.print(String.format("Enter a username for this pairing [%s]: ", DEFAULT_USERNAME)); + String userName = in.nextLine(); + + if (userName.length() == 0) { + userName = DEFAULT_USERNAME; + } + + System.out.println("Sending pairing request..."); + + try { + Pairing pairing = api.pair(userName, pairingPhrase); + pairingId = pairing.id; + break; + } catch (RequestError err) { + System.out.println(String.format("The pairing phrase was not accepted (reason:%s)", err.getMessage())); + } + } - try { - Pairing pairing = api.advanced.pairings.getById(pairingId); - if (pairing.enabled) { - System.out.println("Pairing complete"); + while (true) { + System.out.println("Authorize pairing on phone and then press return to continue."); + in.nextLine(); + System.out.println("Checking status of pairing request..."); + + try { + Pairing pairing = api.advanced.pairings.getById(pairingId); + if (pairing.pending) { + System.out.println("The pairing has not been authorized by the phone yet."); + } else if (pairing.enabled) { + System.out.println("Pairing complete"); System.out.println(); - break; - } else { - System.out.println("The pairing has not been authorized by the phone yet."); - } - } catch (RequestError err) { - System.out.println(String.format("Could not check pairing status (reason:%s)", err.getMessage())); - } - } + break; + } else { + System.out.println("The pairing has been denied"); + System.exit(0); + } + } catch (RequestError err) { + System.out.println(String.format("Could not check pairing status (reason:%s)", err.getMessage())); + } + } while (true) { System.out.println("Step 2: Authenticate log in"); System.out.println("--------------------------------------"); - System.out.print(String.format("Enter a terminal name for this authentication request [\"%s\"]: ", DEFAULT_TERMINAL_NAME)); + System.out.print(String.format("Enter a terminal name for this authentication request [%s]: ", DEFAULT_TERMINAL_NAME)); String terminalName = in.nextLine(); if (terminalName.length() == 0) { terminalName = DEFAULT_TERMINAL_NAME; @@ -125,7 +129,7 @@ public static void main(String[] args) { AuthenticationRequest requestStatus; try { - requestStatus = api.authenticate(requestId, terminalName); + requestStatus = api.advanced.authenticationRequests.getById(requestId); } catch (RequestError err) { System.out.println(String.format("Could not check authentication status (reason:%s)", err.getMessage())); continue; From c74c5e93ad5e675f16c2685e74e51a0a238035e5 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 10:59:36 -0600 Subject: [PATCH 098/195] Update ApiResponseObject.updateRawResponse to throw JSONException --- src/main/java/com/toopher/ApiResponseObject.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/toopher/ApiResponseObject.java b/src/main/java/com/toopher/ApiResponseObject.java index 2446de0..a983f15 100644 --- a/src/main/java/com/toopher/ApiResponseObject.java +++ b/src/main/java/com/toopher/ApiResponseObject.java @@ -17,7 +17,7 @@ public ApiResponseObject(JSONObject json) throws JSONException { this.rawResponse = jsonToMap(json); } - public void updateRawResponse(JSONObject json) { + public void updateRawResponse(JSONObject json) throws JSONException { this.rawResponse = jsonToMap(json); } From ea0334f00c21813ffd5a0d8deb927799685c45c5 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 11:00:34 -0600 Subject: [PATCH 099/195] Update Action.update to throw JSONException --- src/main/java/com/toopher/Action.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/toopher/Action.java b/src/main/java/com/toopher/Action.java index d0df02b..ce5c8e0 100644 --- a/src/main/java/com/toopher/Action.java +++ b/src/main/java/com/toopher/Action.java @@ -24,7 +24,7 @@ public Action (JSONObject json) throws JSONException { this.name = json.getString("name"); } - public void update(JSONObject jsonResponse) { + public void update(JSONObject jsonResponse) throws JSONException { this.name = jsonResponse.getString("name"); } } From 39419105670cdffef6360d59f17e63a50cf88d9a Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 11:01:40 -0600 Subject: [PATCH 100/195] Update AuthenticationRequest to throw JSONException --- src/main/java/com/toopher/AuthenticationRequest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/toopher/AuthenticationRequest.java b/src/main/java/com/toopher/AuthenticationRequest.java index 8a7fd8e..03eb52f 100644 --- a/src/main/java/com/toopher/AuthenticationRequest.java +++ b/src/main/java/com/toopher/AuthenticationRequest.java @@ -90,7 +90,7 @@ public String toString() { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public void refreshFromServer() throws RequestError { + public void refreshFromServer() throws RequestError, JSONException { String endpoint = String.format("authentication_requests/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); @@ -104,7 +104,7 @@ public void refreshFromServer() throws RequestError { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public void grantWithOtp(String otp) throws RequestError { + public void grantWithOtp(String otp) throws RequestError, JSONException { String endpoint = String.format("authentication_requests/%s/otp_auth", id); List params = new ArrayList(); params.add(new BasicNameValuePair("otp", otp)); @@ -118,7 +118,7 @@ public void grantWithOtp(String otp) throws RequestError { * @param jsonResponse * The JSON response from the API */ - private void update(JSONObject jsonResponse) { + private void update(JSONObject jsonResponse) throws JSONException { this.pending = jsonResponse.getBoolean("pending"); this.granted = jsonResponse.getBoolean("granted"); this.automated = jsonResponse.getBoolean("automated"); From 9620d5a0edcb47956e2294406dd0a2e15200d820 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 12:13:31 -0600 Subject: [PATCH 101/195] Update Pairing to throw JSONException --- src/main/java/com/toopher/Pairing.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/toopher/Pairing.java b/src/main/java/com/toopher/Pairing.java index 0a0f979..13f27ed 100644 --- a/src/main/java/com/toopher/Pairing.java +++ b/src/main/java/com/toopher/Pairing.java @@ -60,7 +60,7 @@ public String toString() { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public void refreshFromServer() throws RequestError { + public void refreshFromServer() throws RequestError, JSONException { String endpoint = String.format("pairings/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); @@ -83,7 +83,7 @@ public byte[] getQrCodeImage() throws RequestError { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public String getResetLink() throws RequestError { + public String getResetLink() throws RequestError, JSONException { return getResetLink(null); } @@ -95,7 +95,7 @@ public String getResetLink() throws RequestError { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public String getResetLink(Map extras) throws RequestError { + public String getResetLink(Map extras) throws RequestError, JSONException { String endpoint = String.format("pairings/%s/generate_reset_link", id); JSONObject result = api.advanced.raw.post(endpoint, extras); return result.getString("url"); @@ -134,7 +134,7 @@ public void emailResetLink(String email, Map extras) throws Requ * @param jsonResponse * The JSON response from the API */ - private void update(JSONObject jsonResponse) { + private void update(JSONObject jsonResponse) throws JSONException { this.enabled = jsonResponse.getBoolean("enabled"); this.pending = jsonResponse.getBoolean("pending"); this.user.update(jsonResponse.getJSONObject("user")); From c306d73c3cec70b61eaaf82bf88f6ce5d11f1cff Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 12:14:06 -0600 Subject: [PATCH 102/195] Update ToopherAPI to throw JSONException --- src/main/java/com/toopher/ToopherAPI.java | 46 +++++++++++------------ 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPI.java b/src/main/java/com/toopher/ToopherAPI.java index 255162e..4ffb7f7 100644 --- a/src/main/java/com/toopher/ToopherAPI.java +++ b/src/main/java/com/toopher/ToopherAPI.java @@ -159,7 +159,7 @@ public ToopherAPI(String consumerKey, String consumerSecret, URI uri, HttpClient * @throws RequestError * Thrown when an exceptional condition is encountered */ - public Pairing pair(String userName) throws RequestError { + public Pairing pair(String userName) throws RequestError, JSONException { return this.pair(userName, null, null); } @@ -174,7 +174,7 @@ public Pairing pair(String userName) throws RequestError { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public Pairing pair(String userName, String pairingPhraseOrNum) throws RequestError { + public Pairing pair(String userName, String pairingPhraseOrNum) throws RequestError, JSONException { return this.pair(userName, pairingPhraseOrNum, null); } @@ -191,7 +191,7 @@ public Pairing pair(String userName, String pairingPhraseOrNum) throws RequestEr * @throws RequestError * Thrown when an exceptional condition is encountered */ - public Pairing pair( String userName, String pairingPhraseOrNum, Map extras) throws RequestError { + public Pairing pair( String userName, String pairingPhraseOrNum, Map extras) throws RequestError, JSONException { String endpoint; List params = new ArrayList(); @@ -224,7 +224,7 @@ public Pairing pair( String userName, String pairingPhraseOrNum, Map extras) throws RequestError { + public AuthenticationRequest authenticate(String pairingIdOrUsername, String terminalNameOrTerminalNameExtra, String actionName, Map extras) throws RequestError, JSONException { final String endpoint = "authentication_requests/initiate"; List params = new ArrayList(); @@ -418,7 +418,7 @@ public Pairings(ToopherAPI toopherAPI) { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public Pairing getById(String pairingId) throws RequestError { + public Pairing getById(String pairingId) throws RequestError, JSONException { final String endpoint = String.format("pairings/%s", pairingId); JSONObject json = advanced.raw.get(endpoint); return new Pairing(json, api); @@ -441,7 +441,7 @@ public AuthenticationRequests(ToopherAPI toopherAPI) { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public AuthenticationRequest getById(String authenticationRequestId) throws RequestError { + public AuthenticationRequest getById(String authenticationRequestId) throws RequestError, JSONException { final String endpoint = String.format("authentication_requests/%s", authenticationRequestId); JSONObject json = advanced.raw.get(endpoint); return new AuthenticationRequest(json, api); @@ -464,7 +464,7 @@ public Users(ToopherAPI toopherAPI) { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public User create(String userName) throws RequestError { + public User create(String userName) throws RequestError, JSONException { return create(userName, null); } @@ -479,7 +479,7 @@ public User create(String userName) throws RequestError { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public User create(String userName, Map extras) throws RequestError { + public User create(String userName, Map extras) throws RequestError, JSONException { final String endpoint = "users/create"; List params = new ArrayList(); params.add(new BasicNameValuePair("name", userName)); @@ -497,7 +497,7 @@ public User create(String userName, Map extras) throws RequestEr * @throws RequestError * Thrown when an exceptional condition is encountered */ - public User getById(String userId) throws RequestError { + public User getById(String userId) throws RequestError, JSONException { final String endpoint = String.format("users/%s", userId); JSONObject json = advanced.raw.get(endpoint); return new User(json, api); @@ -511,7 +511,7 @@ public User getById(String userId) throws RequestError { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public User getByName(String name) throws RequestError { + public User getByName(String name) throws RequestError, JSONException { final String endpoint = "users"; List params = new ArrayList(); params.add(new BasicNameValuePair("name", name)); @@ -552,7 +552,7 @@ public UserTerminals(ToopherAPI toopherAPI) { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public UserTerminal create(String userName, String terminalName, String requesterSpecifiedId) throws RequestError { + public UserTerminal create(String userName, String terminalName, String requesterSpecifiedId) throws RequestError, JSONException { return create(userName, terminalName, requesterSpecifiedId, null); } @@ -573,7 +573,7 @@ public UserTerminal create(String userName, String terminalName, String requeste * @throws RequestError * Thrown when an exceptional condition is encountered */ - public UserTerminal create(String userName, String terminalName, String requesterSpecifiedId, Map extras) throws RequestError { + public UserTerminal create(String userName, String terminalName, String requesterSpecifiedId, Map extras) throws RequestError, JSONException { final String endpoint = "user_terminals/create"; List params = new ArrayList(); @@ -594,7 +594,7 @@ public UserTerminal create(String userName, String terminalName, String requeste * @throws RequestError * Thrown when an exceptional condition is encountered */ - public UserTerminal getById(String terminalId) throws RequestError { + public UserTerminal getById(String terminalId) throws RequestError, JSONException { final String endpoint = String.format("user_terminals/%s", terminalId); JSONObject result = advanced.raw.get(endpoint); return new UserTerminal(result, api); @@ -602,15 +602,15 @@ public UserTerminal getById(String terminalId) throws RequestError { } class ApiRawRequester { - public T get(String endpoint) throws RequestError { + public T get(String endpoint) throws RequestError, JSONException { return request(new HttpGet(), endpoint, null); } - public T get(String endpoint, List params) throws RequestError { + public T get(String endpoint, List params) throws RequestError, JSONException { return request(new HttpGet(), endpoint, params); } - public T get(String endpoint, List params, Map extras) throws RequestError { + public T get(String endpoint, List params, Map extras) throws RequestError, JSONException { if (extras != null && extras.size() > 0) { for (Map.Entry e : extras.entrySet()){ params.add(new BasicNameValuePair(e.getKey(), e.getValue())); @@ -619,19 +619,19 @@ public T get(String endpoint, List params, Map T post(String endpoint) throws RequestError { + public T post(String endpoint) throws RequestError, JSONException { return request(new HttpPost(), endpoint, null); } - public T post(String endpoint, List params) throws RequestError { + public T post(String endpoint, List params) throws RequestError, JSONException { return post(endpoint, params, null); } - public T post(String endpoint, Map extras) throws RequestError { + public T post(String endpoint, Map extras) throws RequestError, JSONException { return post(endpoint, null, extras); } - public T post(String endpoint, List params, Map extras) throws RequestError { + public T post(String endpoint, List params, Map extras) throws RequestError, JSONException { HttpPost post = new HttpPost(); if (params == null) { params = new ArrayList(); @@ -651,7 +651,7 @@ public T post(String endpoint, List params, Map T request(HttpRequestBase httpRequest, String endpoint, List queryStringParameters) throws RequestError { + private T request(HttpRequestBase httpRequest, String endpoint, List queryStringParameters) throws RequestError, JSONException { Boolean isQrImageEndpoint = endpoint.contains("qr/pairings/"); try { URIBuilder uriBuilder = new URIBuilder().setScheme(uriScheme).setHost(uriHost) From ff5f4797f65f331bc233e1d6c01a5a52890dffa4 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 12:14:34 -0600 Subject: [PATCH 103/195] Update ToopherAPIDemo to catch JSONException --- src/main/java/com/toopher/ToopherAPIDemo.java | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/toopher/ToopherAPIDemo.java b/src/main/java/com/toopher/ToopherAPIDemo.java index 5b13a5e..3193371 100644 --- a/src/main/java/com/toopher/ToopherAPIDemo.java +++ b/src/main/java/com/toopher/ToopherAPIDemo.java @@ -1,5 +1,7 @@ package com.toopher; +import org.json.JSONException; + import java.net.URI; import java.net.URISyntaxException; import java.util.Map; @@ -77,6 +79,8 @@ public static void main(String[] args) { break; } catch (RequestError err) { System.out.println(String.format("The pairing phrase was not accepted (reason:%s)", err.getMessage())); + } catch (JSONException je) { + System.out.println(String.format("The JSON response could not be processed (reason: %s)", je.getMessage())); } } @@ -99,6 +103,8 @@ public static void main(String[] args) { } } catch (RequestError err) { System.out.println(String.format("Could not check pairing status (reason:%s)", err.getMessage())); + } catch (JSONException je) { + System.out.println(String.format("The JSON response could not be processed (reason: %s)", je.getMessage())); } } @@ -120,7 +126,10 @@ public static void main(String[] args) { } catch (RequestError err) { System.out.println(String.format("Error initiating authentication (reason:%s)", err.getMessage())); continue; - } + } catch (JSONException je) { + System.out.println(String.format("The JSON response could not be processed (reason: %s)", je.getMessage())); + continue; + } while (true) { System.out.println("Respond to authentication request on phone (if prompted) and then press return to continue."); @@ -133,7 +142,10 @@ public static void main(String[] args) { } catch (RequestError err) { System.out.println(String.format("Could not check authentication status (reason:%s)", err.getMessage())); continue; - } + } catch (JSONException je) { + System.out.println(String.format("The JSON response could not be processed (reason: %s)", je.getMessage())); + continue; + } if (requestStatus.pending) { System.out.println("The authentication request has not received a response from the phone yet."); From 753737005c63d16d82f23796053e8430a7963e71 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 12:14:52 -0600 Subject: [PATCH 104/195] Update User to throw JSONException --- src/main/java/com/toopher/User.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/toopher/User.java b/src/main/java/com/toopher/User.java index 2dbd133..51143a4 100644 --- a/src/main/java/com/toopher/User.java +++ b/src/main/java/com/toopher/User.java @@ -58,7 +58,7 @@ public String toString() { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public void refreshFromServer() throws RequestError { + public void refreshFromServer() throws RequestError, JSONException { String endpoint = String.format("users/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); @@ -70,7 +70,7 @@ public void refreshFromServer() throws RequestError { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public void enableToopherAuthentication() throws RequestError { + public void enableToopherAuthentication() throws RequestError, JSONException { String endpoint = String.format("users/%s", id); List params = new ArrayList(); params.add(new BasicNameValuePair("disable_toopher_auth", "false")); @@ -84,7 +84,7 @@ public void enableToopherAuthentication() throws RequestError { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public void disableToopherAuthentication() throws RequestError { + public void disableToopherAuthentication() throws RequestError, JSONException { String endpoint = String.format("users/%s", id); List params = new ArrayList(); params.add(new BasicNameValuePair("disable_toopher_auth", "true")); @@ -98,7 +98,7 @@ public void disableToopherAuthentication() throws RequestError { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public void reset() throws RequestError { + public void reset() throws RequestError, JSONException { String endpoint = "users/reset"; List params = new ArrayList(); params.add(new BasicNameValuePair("name", name)); @@ -111,7 +111,7 @@ public void reset() throws RequestError { * @param jsonResponse * The JSON response from the API */ - public void update(JSONObject jsonResponse) { + public void update(JSONObject jsonResponse) throws JSONException { this.name = jsonResponse.getString("name"); if (jsonResponse.has("disable_toopher_auth")) { this.toopherAuthenticationEnabled = !jsonResponse.getBoolean("disable_toopher_auth"); From 0a75c6bc1602ed897dba87d17ccb8ee52ac08299 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 12:15:05 -0600 Subject: [PATCH 105/195] Update UserTerminal to throw JSONException --- src/main/java/com/toopher/UserTerminal.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/toopher/UserTerminal.java b/src/main/java/com/toopher/UserTerminal.java index d5826fc..78eedf5 100644 --- a/src/main/java/com/toopher/UserTerminal.java +++ b/src/main/java/com/toopher/UserTerminal.java @@ -55,7 +55,7 @@ public String toString() { * @throws RequestError * Thrown when an exceptional condition is encountered */ - public void refreshFromServer() throws RequestError { + public void refreshFromServer() throws RequestError, JSONException { String endpoint = String.format("user_terminals/%s", id); JSONObject result = api.advanced.raw.get(endpoint); update(result); @@ -67,7 +67,7 @@ public void refreshFromServer() throws RequestError { * @param jsonResponse * The JSON response received from the server */ - public void update(JSONObject jsonResponse) { + public void update(JSONObject jsonResponse) throws JSONException { this.name = jsonResponse.getString("name"); this.requesterSpecifiedId = jsonResponse.getString("name_extra"); this.user.update(jsonResponse.getJSONObject("user")); From 9ae00c4a0cd02b38206d6f1a6e2358f447d95690 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 12:39:04 -0600 Subject: [PATCH 106/195] Update README with new pair() and authenticate() --- README.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f217cd1..83a41f8 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Make sure you visit (http://dev.toopher.com) to get acquainted with the Toopher The first step to accessing the Toopher API is to sign up for an account at the development portal (http://dev.toopher.com) and create a "requester". When that process is complete, your requester is issued OAuth 1.0a credentials in the form of a consumer key and secret. Your key is used to identify your requester when Toopher interacts with your customers, and the secret is used to sign each request so that we know it is generated by you. This library properly formats each request with your credentials automatically. #### The Toopher Two-Step -Interacting with the Toopher web service involves two steps: pairing, and authenticating. +Interacting with the Toopher web service involves two steps: pairing and authenticating. ##### Pair Before you can enhance your website's actions with Toopher, your customers will need to pair their phone's Toopher app with your website. To do this, they generate a unique, nonsensical "pairing phrase" from within the app on their phone. You will need to prompt them for a pairing phrase as part of the Toopher enrollment process. Once you have a pairing phrase, just send it to the Toopher API along with your requester credentials and we'll return a pairing ID that you can use whenever you want to authenticate an action for that user. @@ -34,13 +34,21 @@ import com.toopher.*; ToopherAPI api = new ToopherAPI("", ""); // Step 1 - Pair with their phone's Toopher app -PairingStatus pairing = api.pair("pairing phrase", "username@yourservice.com"); +// With pairing phrase +Pairing pairing = api.pair("username@yourservice.com", "pairing phrase"); +// With SMS +Pairing pairing = api.pair("username@yourservice.com", "555-555-5555") +// With QR code +Pairing pairing = api.pair("username@yourservice.com") // Step 2 - Authenticate a log in -AuthenticationStatus auth = api.authenticate(pairing.id, "my computer"); +// With pairingId +AuthenticationRequest auth = api.authenticate(pairing.id, "my computer"); +// With username +AuthenticationRequest auth = api.authenticate("username", "requesterSpecifiedId") // Once they've responded you can then check the status -AuthenticationStatus status = api.getAuthenticationStatus(auth.id); +auth.refreshFromServer() if (status.pending == false && status.granted == true) { // Success! } From 908b880746a3a24164447675bfa5431872acf998 Mon Sep 17 00:00:00 2001 From: Grace Yim Date: Mon, 9 Feb 2015 13:17:36 -0600 Subject: [PATCH 107/195] Update Iframe README --- README-Iframe.md | 101 +++++++---------------------------------------- 1 file changed, 14 insertions(+), 87 deletions(-) diff --git a/README-Iframe.md b/README-Iframe.md index f999ca9..a1d4e46 100644 --- a/README-Iframe.md +++ b/README-Iframe.md @@ -1,25 +1,22 @@ # Authenticating using the Toopher `iframe` -Toopher's `iframe`-based authentication flow is the simplest way for web developers to integrate Toopher Two-Factor Authentication into an application. +Toopher's ` - -There is no difference in the markup required for a Pairing vs. an Authentication `iframe` request (the generated URI embeds all relevant information). - -## Examples - -### All-in-one iframe - -#### Generating an iframe URL - -Every Toopher Authentication session should include a unique `requestToken` - a randomized `String` that is included in the signed request to the Toopher API and returned in the signed response from the Toopher `