From 8d5a9fffede4bad2cc6ac76871a7ae1238048fba Mon Sep 17 00:00:00 2001 From: Chris Paul Date: Thu, 19 Jan 2017 13:20:28 -0800 Subject: [PATCH 01/17] Initial refactor for tests with mocks. --- generate-fixtures.sh | 3 + pom.xml | 482 +++---- .../com/hellosign/sdk/HelloSignClient.java | 916 ++++++------ .../sdk/http/AbstractHttpRequest.java | 108 +- .../hellosign/sdk/http/Authentication.java | 2 +- .../com/hellosign/sdk/http/HttpClient.java | 347 +++++ .../hellosign/sdk/http/HttpDeleteRequest.java | 44 +- .../hellosign/sdk/http/HttpGetRequest.java | 166 +-- .../sdk/http/HttpOptionsRequest.java | 24 + .../hellosign/sdk/http/HttpPostRequest.java | 63 +- .../com/hellosign/sdk/resource/Account.java | 13 +- .../sdk/resource/SignatureRequest.java | 11 + .../sdk/resource/UnclaimedDraft.java | 10 + .../sdk/resource/support/CustomField.java | 81 ++ .../sdk/resource/support/FormField.java | 73 +- .../support/types/ApiAppOauthScopeType.java | 7 +- .../hellosign/sdk/AbstractHelloSignTest.java | 309 ---- .../hellosign/sdk/HelloSignClientTest.java | 825 ++++++++++- .../hellosign/sdk/resource/AccountTest.java | 91 -- .../hellosign/sdk/resource/ApiAppTest.java | 171 --- .../com/hellosign/sdk/resource/EventTest.java | 53 - .../MultiTemplateSignatureRequestTest.java | 113 -- .../SignatureRequestMetadataTest.java | 26 - .../sdk/resource/SignatureRequestTest.java | 318 ----- .../com/hellosign/sdk/resource/TeamTest.java | 183 --- .../sdk/resource/TemplateDraftTest.java | 79 -- .../TemplateSignatureRequestTest.java | 146 -- .../hellosign/sdk/resource/TemplateTest.java | 116 -- .../resource/support/TemplateListTest.java | 62 - .../test/EmbeddedSignatureRequestTest.java | 82 -- .../EmbeddedTemplateSignatureRequestTest.java | 105 -- .../sdk/test/EmbeddedTemplateTest.java | 141 -- .../sdk/test/SignatureRequestRemindTest.java | 75 - .../sdk/test/TemplateFieldsRequestTest.java | 124 -- .../sdk/test/UnclaimedDraftTest.java | 65 - .../resources/AccountTest/invalidAccount.txt | 1 - .../resources/AccountTest/validAccount.txt | 1 - .../ApiAppTest/apiAppWithWhiteLabeling.txt | 1 - .../resources/ApiAppTest/expectedFields.txt | 6 - src/test/resources/ApiAppTest/validApiApp.txt | 23 - .../expectedFields.txt | 8 - .../EmbeddedSignatureRequestTest/nda.pdf | Bin 121522 -> 0 bytes .../expectedFields.txt | 10 - .../resources/EmbeddedTemplateTest/nda.pdf | Bin 121522 -> 0 bytes .../resources/EventTest/expectedResponse.txt | 1 - .../testAddTemplateUser.json | 253 ++++ .../testAddTemplateUserInvalid.json | 6 + .../testCancelSignatureRequestInvalid.json | 6 + .../testCreateAccount.json | 15 + .../testCreateAccountExisting.json | 6 + .../testCreateAccountWithOAuthData.json | 21 + .../HelloSignClientTest/testCreateApiApp.json | 16 + .../testCreateApiAppInvalid.json | 6 + .../testCreateEmbeddedRequest.json | 42 + .../testCreateEmbeddedRequestInvalid.json | 6 + .../testCreateEmbeddedTemplateDraft.json | 7 + ...estCreateEmbeddedTemplateDraftInvalid.json | 6 + .../HelloSignClientTest/testCreateTeam.json | 33 + .../testCreateTeamInvalid.json | 6 + .../testCreateUnclaimedDraft.json | 9 + .../testCreateUnclaimedDraftInvalid.json | 6 + .../testDeleteApiAppInvalid.json | 6 + .../testDeleteTemplate.json | 0 .../testDeleteTemplateInvalid.json | 6 + .../testDestroyTeamInvalid.json | 6 + .../HelloSignClientTest/testGetAccount.json | 15 + .../HelloSignClientTest/testGetApiApp.json | 16 + .../testGetApiAppInvalid.json | 6 + .../HelloSignClientTest/testGetApiApps.json | 66 + .../testGetApiAppsInvalid.json | 6 + .../testGetEmbeddedSignUrl.json | 6 + .../testGetEmbeddedSignUrlInvalid.json | 6 + .../testGetEmbeddedTemplateEditUrl.json | 6 + ...testGetEmbeddedTemplateEditUrlInvalid.json | 6 + .../testGetFilesInvalid.json | 6 + .../HelloSignClientTest/testGetOauthData.json | 7 + .../testGetSignatureRequest.json | 41 + .../testGetSignatureRequestInvalid.json | 6 + .../testGetSignatureRequests.json | 96 ++ .../testGetSignatureRequestsInvalid.json | 6 + .../testGetSignatureRequestsPage.json | 96 ++ .../testGetSignatureRequestsPageInvalid.json | 10 + .../HelloSignClientTest/testGetTeam.json | 33 + .../testGetTeamInvalid.json | 6 + .../HelloSignClientTest/testGetTemplate.json | 242 ++++ .../testGetTemplateFileInvalid.json | 6 + .../testGetTemplateFilesUrl.json | 4 + .../testGetTemplateInvalid.json | 6 + .../HelloSignClientTest/testGetTemplates.json | 317 +++++ .../testGetTemplatesInvalid.json | 1 + .../testGetTemplatesPage.json | 291 ++++ .../testGetTemplatesPageInvalid.json | 10 + .../testInviteTeamMember.json | 50 + .../testInviteTeamMemberInvalid.json | 6 + .../testIsAccountInvalid.json | 2 + .../testIsAccountValid.json | 5 + .../testRemoveTeamMember.json | 32 + .../testRemoveTeamMemberInvalid.json | 6 + .../testRemoveTemplateUser.json | 242 ++++ .../testRemoveTemplateUserInvalid.json | 6 + .../testRequestEmailReminder.json | 85 ++ .../testRequestEmailReminderInvalid.json | 6 + .../testSendSignatureRequest.json | 41 + .../testSendSignatureRequestInvalid.json | 6 + .../testSendTemplateSignatureRequest.json | 85 ++ ...stSendTemplateSignatureRequestInvalid.json | 6 + .../testSetAccountCallback.json | 15 + .../testSetAccountCallbackInvalid.json | 6 + .../HelloSignClientTest/testUpdateApiApp.json | 16 + .../testUpdateApiAppInvalid.json | 6 + .../testUpdateSignatureRequest.json | 41 + .../testUpdateSignatureRequestInvalid.json | 6 + .../testUpdateTeamName.json | 32 + .../testUpdateTeamNameInvalid.json | 6 + .../expectedFields.txt | 9 - .../expectedResponse.txt | 1 - .../expectedFields.txt | 8 - .../expectedResponse.txt | 53 - .../SignatureRequestRemindTest/nda.pdf | Bin 121522 -> 0 bytes .../SignatureRequestTest/AppendixA.pdf | Bin 194064 -> 0 bytes .../SignatureRequestTest/expectedFields.txt | 13 - .../SignatureRequestTest/expectedResponse.txt | 1 - .../resources/SignatureRequestTest/nda.pdf | Bin 121522 -> 0 bytes .../test_white_text_tags.pdf | Bin 110463 -> 0 bytes .../SignatureRequestTest/text_tags_test.pdf | Bin 110643 -> 0 bytes .../TemplateDraftTest/expectedFields.txt | 9 - src/test/resources/TemplateDraftTest/nda.pdf | Bin 121522 -> 0 bytes .../TemplateFieldsRequestTest/AppendixA.docx | Bin 6446 -> 0 bytes .../expectedFields.txt | 8 - .../TemplateFieldsRequestTest/nda.docx | Bin 8602 -> 0 bytes .../resources/TemplateListTest/page1.json | 1238 ----------------- .../resources/TemplateListTest/page2.json | 528 ------- .../expectedFields.txt | 8 - .../expectedResponse.txt | 1 - .../UnclaimedDraftTest/expectedFields.txt | 5 - src/test/resources/UnclaimedDraftTest/nda.pdf | Bin 121522 -> 0 bytes src/test/resources/test.properties.sample | 45 - 137 files changed, 4581 insertions(+), 5316 deletions(-) create mode 100644 generate-fixtures.sh create mode 100644 src/main/java/com/hellosign/sdk/http/HttpClient.java create mode 100644 src/main/java/com/hellosign/sdk/http/HttpOptionsRequest.java delete mode 100644 src/test/java/com/hellosign/sdk/AbstractHelloSignTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/AccountTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/ApiAppTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/EventTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/MultiTemplateSignatureRequestTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/SignatureRequestMetadataTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/SignatureRequestTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/TeamTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/TemplateDraftTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/TemplateSignatureRequestTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/TemplateTest.java delete mode 100644 src/test/java/com/hellosign/sdk/resource/support/TemplateListTest.java delete mode 100644 src/test/java/com/hellosign/sdk/test/EmbeddedSignatureRequestTest.java delete mode 100644 src/test/java/com/hellosign/sdk/test/EmbeddedTemplateSignatureRequestTest.java delete mode 100644 src/test/java/com/hellosign/sdk/test/EmbeddedTemplateTest.java delete mode 100644 src/test/java/com/hellosign/sdk/test/SignatureRequestRemindTest.java delete mode 100644 src/test/java/com/hellosign/sdk/test/TemplateFieldsRequestTest.java delete mode 100644 src/test/java/com/hellosign/sdk/test/UnclaimedDraftTest.java delete mode 100644 src/test/resources/AccountTest/invalidAccount.txt delete mode 100644 src/test/resources/AccountTest/validAccount.txt delete mode 100644 src/test/resources/ApiAppTest/apiAppWithWhiteLabeling.txt delete mode 100644 src/test/resources/ApiAppTest/expectedFields.txt delete mode 100644 src/test/resources/ApiAppTest/validApiApp.txt delete mode 100644 src/test/resources/EmbeddedSignatureRequestTest/expectedFields.txt delete mode 100644 src/test/resources/EmbeddedSignatureRequestTest/nda.pdf delete mode 100644 src/test/resources/EmbeddedTemplateSignatureRequestTest/expectedFields.txt delete mode 100644 src/test/resources/EmbeddedTemplateTest/nda.pdf delete mode 100644 src/test/resources/EventTest/expectedResponse.txt create mode 100644 src/test/resources/HelloSignClientTest/testAddTemplateUser.json create mode 100644 src/test/resources/HelloSignClientTest/testAddTemplateUserInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testCancelSignatureRequestInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateAccount.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateAccountExisting.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateAccountWithOAuthData.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateApiApp.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateApiAppInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateEmbeddedRequest.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateEmbeddedRequestInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateEmbeddedTemplateDraft.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateEmbeddedTemplateDraftInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateTeam.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateTeamInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateUnclaimedDraft.json create mode 100644 src/test/resources/HelloSignClientTest/testCreateUnclaimedDraftInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testDeleteApiAppInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testDeleteTemplate.json create mode 100644 src/test/resources/HelloSignClientTest/testDeleteTemplateInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testDestroyTeamInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetAccount.json create mode 100644 src/test/resources/HelloSignClientTest/testGetApiApp.json create mode 100644 src/test/resources/HelloSignClientTest/testGetApiAppInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetApiApps.json create mode 100644 src/test/resources/HelloSignClientTest/testGetApiAppsInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetEmbeddedSignUrl.json create mode 100644 src/test/resources/HelloSignClientTest/testGetEmbeddedSignUrlInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetEmbeddedTemplateEditUrl.json create mode 100644 src/test/resources/HelloSignClientTest/testGetEmbeddedTemplateEditUrlInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetFilesInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetOauthData.json create mode 100644 src/test/resources/HelloSignClientTest/testGetSignatureRequest.json create mode 100644 src/test/resources/HelloSignClientTest/testGetSignatureRequestInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetSignatureRequests.json create mode 100644 src/test/resources/HelloSignClientTest/testGetSignatureRequestsInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetSignatureRequestsPage.json create mode 100644 src/test/resources/HelloSignClientTest/testGetSignatureRequestsPageInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetTeam.json create mode 100644 src/test/resources/HelloSignClientTest/testGetTeamInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetTemplate.json create mode 100644 src/test/resources/HelloSignClientTest/testGetTemplateFileInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetTemplateFilesUrl.json create mode 100644 src/test/resources/HelloSignClientTest/testGetTemplateInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetTemplates.json create mode 100644 src/test/resources/HelloSignClientTest/testGetTemplatesInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testGetTemplatesPage.json create mode 100644 src/test/resources/HelloSignClientTest/testGetTemplatesPageInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testInviteTeamMember.json create mode 100644 src/test/resources/HelloSignClientTest/testInviteTeamMemberInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testIsAccountInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testIsAccountValid.json create mode 100644 src/test/resources/HelloSignClientTest/testRemoveTeamMember.json create mode 100644 src/test/resources/HelloSignClientTest/testRemoveTeamMemberInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testRemoveTemplateUser.json create mode 100644 src/test/resources/HelloSignClientTest/testRemoveTemplateUserInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testRequestEmailReminder.json create mode 100644 src/test/resources/HelloSignClientTest/testRequestEmailReminderInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testSendSignatureRequest.json create mode 100644 src/test/resources/HelloSignClientTest/testSendSignatureRequestInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testSendTemplateSignatureRequest.json create mode 100644 src/test/resources/HelloSignClientTest/testSendTemplateSignatureRequestInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testSetAccountCallback.json create mode 100644 src/test/resources/HelloSignClientTest/testSetAccountCallbackInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testUpdateApiApp.json create mode 100644 src/test/resources/HelloSignClientTest/testUpdateApiAppInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testUpdateSignatureRequest.json create mode 100644 src/test/resources/HelloSignClientTest/testUpdateSignatureRequestInvalid.json create mode 100644 src/test/resources/HelloSignClientTest/testUpdateTeamName.json create mode 100644 src/test/resources/HelloSignClientTest/testUpdateTeamNameInvalid.json delete mode 100644 src/test/resources/MultiTemplateSignatureRequestTest/expectedFields.txt delete mode 100644 src/test/resources/MultiTemplateSignatureRequestTest/expectedResponse.txt delete mode 100644 src/test/resources/SignatureRequestMetadataTest/expectedFields.txt delete mode 100644 src/test/resources/SignatureRequestMetadataTest/expectedResponse.txt delete mode 100644 src/test/resources/SignatureRequestRemindTest/nda.pdf delete mode 100644 src/test/resources/SignatureRequestTest/AppendixA.pdf delete mode 100644 src/test/resources/SignatureRequestTest/expectedFields.txt delete mode 100644 src/test/resources/SignatureRequestTest/expectedResponse.txt delete mode 100644 src/test/resources/SignatureRequestTest/nda.pdf delete mode 100644 src/test/resources/SignatureRequestTest/test_white_text_tags.pdf delete mode 100644 src/test/resources/SignatureRequestTest/text_tags_test.pdf delete mode 100644 src/test/resources/TemplateDraftTest/expectedFields.txt delete mode 100644 src/test/resources/TemplateDraftTest/nda.pdf delete mode 100644 src/test/resources/TemplateFieldsRequestTest/AppendixA.docx delete mode 100644 src/test/resources/TemplateFieldsRequestTest/expectedFields.txt delete mode 100644 src/test/resources/TemplateFieldsRequestTest/nda.docx delete mode 100644 src/test/resources/TemplateListTest/page1.json delete mode 100644 src/test/resources/TemplateListTest/page2.json delete mode 100644 src/test/resources/TemplateSignatureRequestTest/expectedFields.txt delete mode 100644 src/test/resources/TemplateSignatureRequestTest/expectedResponse.txt delete mode 100644 src/test/resources/UnclaimedDraftTest/expectedFields.txt delete mode 100644 src/test/resources/UnclaimedDraftTest/nda.pdf delete mode 100644 src/test/resources/test.properties.sample diff --git a/generate-fixtures.sh b/generate-fixtures.sh new file mode 100644 index 00000000..7a693aac --- /dev/null +++ b/generate-fixtures.sh @@ -0,0 +1,3 @@ +#!/bin/bash + + diff --git a/pom.xml b/pom.xml index f79acc08..96fa45cd 100644 --- a/pom.xml +++ b/pom.xml @@ -1,240 +1,248 @@ - 4.0.0 - com.hellosign - hellosign-java-sdk - jar - 3.5.6 - HelloSign Java SDK - https://github.com/HelloFax/hellosign-java-sdk - - Chris Paul (chris@hellosign.com) - 7.6.14.v20131031 - 1.7.5 - UTF-8 - - - - org.json - json - 20090211 - - - org.slf4j - slf4j-api - ${slf4jVersion} - - - junit - junit - 4.11 - test - - - commons-fileupload - commons-fileupload - 1.3 - test - - - javax.servlet - javax.servlet-api - 3.0.1 - test - - - org.slf4j - slf4j-simple - ${slf4jVersion} - test - - - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - src/main/resources - true - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.7 - true - - ossrh - https://oss.sonatype.org/ - true - - - - maven-compiler-plugin - 3.0 - - 1.7 - 1.7 - - - - test-compile - process-test-sources - - testCompile - - - 1.7 - 1.7 - - - - - - maven-assembly-plugin - - - package - - single - - - - - - jar-with-dependencies - - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - org.mortbay.jetty - jetty-maven-plugin - ${jettyVersion} - - 10 - true - ${basedir}/src/test/webapp - ${basedir}/target/classes - ${basedir}/target/test-classes - src/test/webapp/WEB-INF/web.properties - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - - java - - - - - com.hellosign.sdk.callback.ExampleCallbackServer - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - true - - - - sign-artifacts - verify - - sign - - - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - ${basedir}/src/test/webapp/javadoc - - - - - Use the HelloSign Java SDK to connect your Java app to HelloSign's service in microseconds! - - HelloSign - https://www.hellosign.com/ - - - https://github.com/HelloFax/hellosign-java-sdk - scm:git:git@github.com:HelloFax/hellosign-java-sdk.git - scm:git:git://github.com/HelloFax/hellosign-java-sdk.git - - - - MIT License - http://www.opensource.org/licenses/mit-license.php - repo - - - - - chris-hellosign - Chris Paul - chris@hellosign.com - https://www.hellosign.com - HelloSign - https://www.hellosign.com - - architect - developer - - America/Los_Angeles - - https://www.gravatar.com/avatar/7970e197406612872f6895a71a803f08 - - - + 4.0.0 + com.hellosign + hellosign-java-sdk + jar + 3.6.0-SNAPSHOT + HelloSign Java SDK + https://github.com/HelloFax/hellosign-java-sdk + + Chris Paul (chris@hellosign.com) + 7.6.14.v20131031 + 1.7.5 + UTF-8 + true + true + + + + org.json + json + 20090211 + + + org.slf4j + slf4j-api + ${slf4jVersion} + + + junit + junit + 4.11 + test + + + commons-fileupload + commons-fileupload + 1.3 + test + + + javax.servlet + javax.servlet-api + 3.0.1 + test + + + org.slf4j + slf4j-simple + ${slf4jVersion} + test + + + org.mockito + mockito-core + 2.3.4 + test + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + + src/main/resources + true + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.7 + true + + ossrh + https://oss.sonatype.org/ + true + + + + maven-compiler-plugin + 3.0 + + 1.7 + 1.7 + + + + test-compile + process-test-sources + + testCompile + + + 1.7 + 1.7 + + + + + + maven-assembly-plugin + + + package + + single + + + + + + jar-with-dependencies + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + org.mortbay.jetty + jetty-maven-plugin + ${jettyVersion} + + 10 + true + ${basedir}/src/test/webapp + ${basedir}/target/classes + ${basedir}/target/test-classes + src/test/webapp/WEB-INF/web.properties + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + + java + + + + + com.hellosign.sdk.callback.ExampleCallbackServer + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + true + + + + sign-artifacts + verify + + sign + + + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + ${basedir}/src/test/webapp/javadoc + + + + + Use the HelloSign Java SDK to connect your Java app to HelloSign's service in microseconds! + + HelloSign + https://www.hellosign.com/ + + + https://github.com/HelloFax/hellosign-java-sdk + scm:git:git@github.com:HelloFax/hellosign-java-sdk.git + scm:git:git://github.com/HelloFax/hellosign-java-sdk.git + + + + MIT License + http://www.opensource.org/licenses/mit-license.php + repo + + + + + chris-hellosign + Chris Paul + chris@hellosign.com + https://www.hellosign.com + HelloSign + https://www.hellosign.com + + architect + developer + + America/Los_Angeles + + https://www.gravatar.com/avatar/7970e197406612872f6895a71a803f08 + + + diff --git a/src/main/java/com/hellosign/sdk/HelloSignClient.java b/src/main/java/com/hellosign/sdk/HelloSignClient.java index 01187af0..76d4ee99 100644 --- a/src/main/java/com/hellosign/sdk/HelloSignClient.java +++ b/src/main/java/com/hellosign/sdk/HelloSignClient.java @@ -25,30 +25,14 @@ */ import java.io.File; -import java.io.Serializable; import java.lang.reflect.Constructor; import java.net.HttpURLConnection; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import java.util.HashMap; -import java.util.Map; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; import org.json.JSONException; import org.json.JSONObject; -import com.hellosign.sdk.http.AbstractHttpRequest; import com.hellosign.sdk.http.Authentication; -import com.hellosign.sdk.http.HttpDeleteRequest; -import com.hellosign.sdk.http.HttpGetRequest; -import com.hellosign.sdk.http.HttpPostRequest; -import com.hellosign.sdk.http.HttpPutRequest; +import com.hellosign.sdk.http.HttpClient; import com.hellosign.sdk.resource.AbstractRequest; import com.hellosign.sdk.resource.AbstractResourceList; import com.hellosign.sdk.resource.Account; @@ -83,169 +67,125 @@ public class HelloSignClient { public static final String DEFAULT_ENCODING = "UTF-8"; - - // ====================================================================== - // HelloSign API URL Endpoints - // ====================================================================== - - private static final String API_VERSION = "v3"; - - private String URL_HELLOSIGN; - - // The base URL can be overridden by setting the "hellosign.base.url" - // system property. - private static final String URL_API_BASE = "https://api.hellosign.com"; - - private String URL_OAUTH_TOKEN; - - // The base URL can be overridden by setting the "hellosign.oauth.base.url" - // system property. - private static final String URL_OAUTH_TOKEN_PRODUCTION = "https://www.hellosign.com/oauth/token"; - - private String URL_API; - private String URL_ACCOUNT; - private String URL_VALIDATE_ACCOUNT; - private String URL_ACCOUNT_CREATE; - private String URL_TEAM; - private String URL_TEAM_CREATE; - private String URL_TEAM_DESTROY; - private String URL_TEAM_ADD_MEMBER; - private String URL_TEAM_REMOVE_MEMBER; - private String URL_SIGNATURE_REQUEST; - private String URL_SIGNATURE_REQUEST_LIST; - private String URL_SIGNATURE_REQUEST_SEND; - private String URL_TEMPLATE; - private String URL_TEMPLATE_FILE; - private String URL_TEMPLATE_LIST; - private String URL_TEMPLATE_ADD_USER; - private String URL_TEMPLATE_REMOVE_USER; - private String URL_TEMPLATE_DELETE; - private String URL_TEMPLATE_CREATE_EMBEDDED_DRAFT; // Embedded Templates - private String URL_TEMPLATE_SIGNATURE_REQUEST; - private String URL_SIGNATURE_REQUEST_CANCEL; - private String URL_SIGNATURE_REQUEST_REMIND; - private String URL_SIGNATURE_REQUEST_FINAL_COPY; - private String URL_SIGNATURE_REQUEST_FILES; - private String URL_SIGNATURE_REQUEST_UPDATE; - private String URL_SIGNATURE_REQUEST_EMBEDDED; - private String URL_SIGNATURE_REQUEST_EMBEDDED_TEMPLATE; - private String URL_EMBEDDED_SIGN_URL; - private String URL_EMBEDDED_EDIT_URL; // Embedded Templates - private String URL_UNCLAIMED_DRAFT_CREATE; - private String URL_UNCLAIMED_DRAFT_CREATE_EMBEDDED; - private String URL_UNCLAIMED_DRAFT_CREATE_EMBEDDED_WITH_TEMPLATE; - private String URL_API_APP; - private String URL_API_APP_LIST; - - private String URL_PARAM_FILE_TYPE = "file_type"; - + public static final String DEFAULT_BASE_API_URL = "https://api.hellosign.com/v3"; + public static final String DEFAULT_OAUTH_TOKEN_URL = "https://www.hellosign.com/oauth/token"; + + public static final String ACCOUNT_URI = "/account"; + public static final String VALIDATE_ACCOUNT_URI = "/account/validate"; + public static final String ACCOUNT_CREATE_URI = "/account/create"; + public static final String TEAM_URI = "/team"; + public static final String TEAM_CREATE_URI = "/team/create"; + public static final String TEAM_DESTROY_URI = "/team/destroy"; + public static final String TEAM_ADD_MEMBER_URI = "/team/add_member"; + public static final String TEAM_REMOVE_MEMBER_URI = "/team/remove_member"; + public static final String SIGNATURE_REQUEST_URI = "/signature_request"; + public static final String SIGNATURE_REQUEST_LIST_URI = "/signature_request/list"; + public static final String SIGNATURE_REQUEST_SEND_URI = "/signature_request/send"; + public static final String TEMPLATE_URI = "/template"; + public static final String TEMPLATE_FILE_URI = "/template/files"; + public static final String TEMPLATE_LIST_URI = "/template/list"; + public static final String TEMPLATE_ADD_USER_URI = "/template/add_user"; + public static final String TEMPLATE_REMOVE_USER_URI = "/template/remove_user"; + public static final String TEMPLATE_DELETE_URI = "/template/delete"; + public static final String TEMPLATE_CREATE_EMBEDDED_DRAFT_URI = "/template/create_embedded_draft"; + public static final String TEMPLATE_SIGNATURE_REQUEST_URI = "/signature_request/send_with_template"; + public static final String SIGNATURE_REQUEST_CANCEL_URI = "/signature_request/cancel"; + public static final String SIGNATURE_REQUEST_REMIND_URI = "/signature_request/remind"; + public static final String SIGNATURE_REQUEST_FINAL_COPY_URI = "/signature_request/final_copy"; + public static final String SIGNATURE_REQUEST_FILES_URI = "/signature_request/files"; + public static final String SIGNATURE_REQUEST_UPDATE_URI = "/signature_request/update"; + public static final String SIGNATURE_REQUEST_EMBEDDED_URI = "/signature_request/create_embedded"; + public static final String SIGNATURE_REQUEST_EMBEDDED_TEMPLATE_URI = "/signature_request/create_embedded_with_template"; + public static final String EMBEDDED_SIGN_URL_URI = "/embedded/sign_url"; + public static final String EMBEDDED_EDIT_URL_URI = "/embedded/edit_url"; + public static final String UNCLAIMED_DRAFT_CREATE_URI = "/unclaimed_draft/create"; + public static final String UNCLAIMED_DRAFT_CREATE_EMBEDDED_URI = "/unclaimed_draft/create_embedded"; + public static final String UNCLAIMED_DRAFT_CREATE_EMBEDDED_WITH_TEMPLATE_URI = "/unclaimed_draft/create_embedded_with_template"; + public static final String API_APP_URI = "/api_app"; + public static final String API_APP_LIST_URI = "/api_app/list"; + + public static final String PARAM_FILE_TYPE_URI = "file_type"; + public static final String PARAM_TEMPLATE_GET_URL = "get_url"; public static final String FINAL_COPY_FILE_NAME = "final-copy"; public static final String FINAL_COPY_FILE_EXT = "pdf"; - public static final String FILES_FILE_NAME = "files"; public static final String FILES_FILE_EXT = "pdf"; - public static final String TEMPLATE_FILE_NAME = "template"; public static final String TEMPLATE_FILE_EXT = "pdf"; - public static final String OAUTH_CODE = "code"; public static final String OAUTH_STATE = "state"; public static final String OAUTH_GRANT_TYPE = "grant_type"; public static final String OAUTH_REFRESH_TOKEN = "refresh_token"; public static final String OAUTH_GRANT_TYPE_AUTHORIZE_CODE = "authorization_code"; public static final String OAUTH_GRANT_TYPE_REFRESH_TOKEN = "refresh_token"; - public static final String CLIENT_SECRET = "client_secret"; public static final String CLIENT_ID = "client_id"; + public static final String EMBEDDED_TEMPLATE_SKIP_SIGNER_ROLES = "skip_signer_roles"; + public static final String EMBEDDED_TEMPLATE_SKIP_SUBJECT_MESSAGE = "skip_subject_message"; + + private Authentication auth; + private HttpClient httpClient; + + // The base URL for all standard API endpoints, which can be + // overridden by setting the "hellosign.base.url" system property. + private String BASE_URI; + + // The base URL for retrieving an OAuth tokens, which can be + // overridden by setting the "hellosign.oauth.base.url" system property. + private String OAUTH_TOKEN_URL; - private Authentication auth = new Authentication(); + /** + * Default constructor that allows the injection of an HttpClient. + * + * In most cases, you should use the constructor that accepts your API key: + * @see #HelloSignClient(String) + */ + public HelloSignClient() { + setHttpClient(new HttpClient()); - private HelloSignClient() { - URL_HELLOSIGN = URL_API_BASE; + // Set overrides if present + BASE_URI = DEFAULT_BASE_API_URL; String baseUrl = System.getProperty("hellosign.base.url"); if (baseUrl != null && !baseUrl.isEmpty()) { - URL_HELLOSIGN = baseUrl; + BASE_URI = baseUrl; } - URL_OAUTH_TOKEN = URL_OAUTH_TOKEN_PRODUCTION; + OAUTH_TOKEN_URL = DEFAULT_OAUTH_TOKEN_URL; String customOauthToken = System.getProperty("hellosign.oauth.base.url"); if (customOauthToken != null && !customOauthToken.isEmpty()) { - URL_OAUTH_TOKEN = customOauthToken; + OAUTH_TOKEN_URL = customOauthToken; } - String disableSslCheck = System.getProperty("hellosign.disable.ssl"); - if (disableSslCheck != null && "true".equalsIgnoreCase(disableSslCheck)) { - disableStrictSSL(); - } - initApiEndpoints(); - } - - private void initApiEndpoints() { - URL_API = URL_HELLOSIGN + "/" + API_VERSION; - URL_ACCOUNT = URL_API + "/account"; - URL_VALIDATE_ACCOUNT = URL_ACCOUNT + "/verify"; - URL_ACCOUNT_CREATE = URL_ACCOUNT + "/create"; - URL_TEAM = URL_API + "/team"; - URL_TEAM_CREATE = URL_TEAM + "/create"; - URL_TEAM_DESTROY = URL_TEAM + "/destroy"; - URL_TEAM_ADD_MEMBER = URL_TEAM + "/add_member"; - URL_TEAM_REMOVE_MEMBER = URL_TEAM + "/remove_member"; - URL_SIGNATURE_REQUEST = URL_API + "/signature_request"; - URL_SIGNATURE_REQUEST_LIST = URL_SIGNATURE_REQUEST + "/list"; - URL_SIGNATURE_REQUEST_SEND = URL_SIGNATURE_REQUEST + "/send"; - URL_TEMPLATE = URL_API + "/template"; - URL_TEMPLATE_FILE = URL_TEMPLATE + "/files"; - URL_TEMPLATE_LIST = URL_TEMPLATE + "/list"; - URL_TEMPLATE_ADD_USER = URL_TEMPLATE + "/add_user"; - URL_TEMPLATE_REMOVE_USER = URL_TEMPLATE + "/remove_user"; - URL_TEMPLATE_DELETE = URL_TEMPLATE + "/delete"; - URL_TEMPLATE_CREATE_EMBEDDED_DRAFT = URL_TEMPLATE + "/create_embedded_draft"; - URL_TEMPLATE_SIGNATURE_REQUEST = URL_SIGNATURE_REQUEST + "/send_with_template"; - URL_SIGNATURE_REQUEST_CANCEL = URL_SIGNATURE_REQUEST + "/cancel"; - URL_SIGNATURE_REQUEST_REMIND = URL_SIGNATURE_REQUEST + "/remind"; - URL_SIGNATURE_REQUEST_FINAL_COPY = URL_SIGNATURE_REQUEST + "/final_copy"; - URL_SIGNATURE_REQUEST_FILES = URL_SIGNATURE_REQUEST + "/files"; - URL_SIGNATURE_REQUEST_UPDATE = URL_SIGNATURE_REQUEST + "/update"; - URL_SIGNATURE_REQUEST_EMBEDDED = URL_SIGNATURE_REQUEST + "/create_embedded"; - URL_SIGNATURE_REQUEST_EMBEDDED_TEMPLATE = URL_SIGNATURE_REQUEST + "/create_embedded_with_template"; - URL_EMBEDDED_SIGN_URL = URL_API + "/embedded/sign_url"; - URL_EMBEDDED_EDIT_URL = URL_API + "/embedded/edit_url"; - URL_UNCLAIMED_DRAFT_CREATE = URL_API + "/unclaimed_draft/create"; - URL_UNCLAIMED_DRAFT_CREATE_EMBEDDED = URL_API + "/unclaimed_draft/create_embedded"; - URL_UNCLAIMED_DRAFT_CREATE_EMBEDDED_WITH_TEMPLATE = URL_API + "/unclaimed_draft/create_embedded_with_template"; - URL_API_APP = URL_API + "/api_app"; - URL_API_APP_LIST = URL_API_APP + "/list"; } /** * Creates a new HelloSign client using your API key. * - * Your HelloSign API key can be found on the Settings page: - * https://www.hellosign.com/home/myAccount/current_tab/integrations - * * @param apiKey String API key + * @throws HelloSignException thrown if there's a problem setting + * the credentials + * @see Account Settings */ - public HelloSignClient(String apiKey) { + public HelloSignClient(String apiKey) throws HelloSignException { this(); - auth.setApiKey(apiKey); + Authentication a = new Authentication(); + a.setApiKey(apiKey); + setAuth(a); } /** * Creates a new HelloSign client using your website account's * email address and password. - * - * Note: This method is not suggested. You're using the API, so - * sign up for an API key already! - * - * https://www.hellosign.com/home/myAccount/current_tab/integrations * * @param email String email * @param password String password * @throws HelloSignException thrown if there is a problem setting * the credentials + * @deprecated Use {@link #HelloSignClient(String)} instead. */ - public HelloSignClient(String email, String password) - throws HelloSignException { + public HelloSignClient(String email, String password) throws HelloSignException { this(); - auth.setWebsiteCredentials(email, password); + Authentication a = new Authentication(); + a.setWebsiteCredentials(email, password); + setAuth(a); } /** @@ -254,12 +194,38 @@ public HelloSignClient(String email, String password) * @throws HelloSignException thrown if the HelloSignAuthentication * parameters are invalid or null */ - public HelloSignClient(Authentication auth) - throws HelloSignException { + public HelloSignClient(Authentication auth) throws HelloSignException { this(); + setAuth(auth); + } + + /** + * Stores the Authentication that should be used for + * HTTP requests against the HelloSign API. + * @param auth Authentication + * @throws HelloSignException thrown if there's a problem + * initializing the authentication credentials + */ + public void setAuth(Authentication auth) throws HelloSignException { this.auth = new Authentication(auth); } + /** + * Retrieves the authentication details being used by this client. + * @return Authentication + */ + public Authentication getAuth() { + return auth; + } + + /** + * Set the HttpClient that should be used for HTTP requests. + * @param client HttpClient + */ + public void setHttpClient(HttpClient client) { + httpClient = client; + } + /** * Returns the current user's account information. * @return Account @@ -267,9 +233,10 @@ public HelloSignClient(Authentication auth) * the HTTP request or the JSON response. */ public Account getAccount() throws HelloSignException { - HttpGetRequest request = new HttpGetRequest(URL_ACCOUNT, auth); - JSONObject json = request.getJsonResponse(); - return new Account(json); + return new Account(httpClient + .withAuth(auth) + .get(BASE_URI + ACCOUNT_URI) + .asJson()); } /** @@ -277,31 +244,22 @@ public Account getAccount() throws HelloSignException { * limited to the visibility of the currently authenticated user. * @param email String email address * @return true if the account exists, false otherwise - * @throws HelloSignException thrown if there's a problem processing - * the HTTP request or the JSON response. */ - public boolean isAccountValid(String email) throws HelloSignException { - if (email == null) { - return false; - } - Map params = - new HashMap(); - params.put("email_address", email); - HttpPostRequest request = new HttpPostRequest( - URL_VALIDATE_ACCOUNT, params, auth); - JSONObject response = request.getJsonResponse(); - if (response.has(Account.ACCOUNT_KEY)) { + public boolean isAccountValid(String email) { + boolean isValid = false; + if (email != null && !email.isEmpty()) { try { - JSONObject account = response.getJSONObject(Account.ACCOUNT_KEY); - if (account.has(Account.ACCOUNT_EMAIL_ADDRESS)) { - return email.equalsIgnoreCase( - account.getString(Account.ACCOUNT_EMAIL_ADDRESS)); - } - } catch (JSONException ex) { - throw new HelloSignException(ex); + Account account = new Account(httpClient + .withAuth(auth) + .withPostField(Account.ACCOUNT_EMAIL_ADDRESS, email) + .post(BASE_URI + VALIDATE_ACCOUNT_URI) + .asJson()); + isValid = (account.hasEmail() && email.equalsIgnoreCase(account.getEmail())); + } catch (HelloSignException ex) { + // Ignore } } - return false; + return isValid; } /** @@ -312,11 +270,10 @@ public boolean isAccountValid(String email) throws HelloSignException { * the HTTP request or the JSON response. */ public Account setCallback(String callback) throws HelloSignException { - Map properties = new HashMap(); - properties.put(Account.ACCOUNT_CALLBACK_URL, callback); - HttpPostRequest request = new HttpPostRequest(URL_ACCOUNT, properties, auth); - JSONObject json = request.getJsonResponse(); - return new Account(json); + return new Account(httpClient.withAuth(auth) + .withPostField(Account.ACCOUNT_CALLBACK_URL, callback) + .post(BASE_URI + ACCOUNT_URI) + .asJson()); } /** @@ -360,16 +317,27 @@ public Account createAccount(String email, String password) throws HelloSignExce * the HTTP request or the JSON response. */ public Account createAccount(String email, String clientId, String clientSecret) throws HelloSignException { - Map fields = new HashMap(); - fields.put(Account.ACCOUNT_EMAIL_ADDRESS, email); + HttpClient client = httpClient + .withAuth(auth) + .withPostField(Account.ACCOUNT_EMAIL_ADDRESS, email); if (clientId != null && clientSecret != null) { - fields.put(CLIENT_ID, clientId); - fields.put(CLIENT_SECRET, clientSecret); + client = client + .withPostField(CLIENT_ID, clientId) + .withPostField(CLIENT_SECRET, clientSecret); } - HttpPostRequest request = new HttpPostRequest(URL_ACCOUNT_CREATE, - fields, auth); - JSONObject json = request.getJsonResponse(); - return new Account(json); + JSONObject response = client + .post(BASE_URI + ACCOUNT_CREATE_URI) + .asJson(); + JSONObject copy; + try { + copy = new JSONObject(response.toString()); + } catch (JSONException e) { + throw new HelloSignException(e); + } + OauthData data = new OauthData(copy); + Account account = new Account(response); + account.setOauthData(data); + return account; } /** @@ -385,19 +353,7 @@ public Account createAccount(String email, String clientId, String clientSecret) * @deprecated as of 3.1.1, replaced by {@link #createAccount(String, String, String)} */ public Account createAccount(String email, String password, String clientId, String clientSecret) throws HelloSignException { - Map fields = new HashMap(); - fields.put(Account.ACCOUNT_EMAIL_ADDRESS, email); - - // Deprecated - we no longer allow setting a password when creating an account - fields.put(Account.ACCOUNT_PASSWORD, password); - - if (clientId != null && clientSecret != null) { - fields.put(CLIENT_ID, clientId); - fields.put(CLIENT_SECRET, clientSecret); - } - HttpPostRequest request = new HttpPostRequest(URL_ACCOUNT_CREATE, fields, auth); - JSONObject json = request.getJsonResponse(); - return new Account(json); + return createAccount(email, clientId, clientSecret); } /** @@ -409,16 +365,22 @@ public Account createAccount(String email, String password, String clientId, Str * @return OauthData object containing OAuth token details * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. + * @deprecated Use {@link #getOauthData(String, String, String, String, boolean)} */ public OauthData getOauthData(String code, String clientId, String secret) throws HelloSignException { - return getOauthData(code, clientId, secret, true); + return getOauthData(code, clientId, secret, "demo", false); } /** * Performs an OAuth request and returns the necessary data for authorizing an API * application, and will automatically set the access token and code for making * authenticated requests with this client. + * + * NOTE: + * This method does not provide a state parameter and is deprecated. Please update + * your references to this method as it will be removed in a future release. + * * @param code String OAuth code * @param clientId String OAuth client ID * @param secret String OAuth secret @@ -427,20 +389,36 @@ public OauthData getOauthData(String code, String clientId, String secret) * @return OauthData object containing OAuth token details * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. + * @deprecated Use {@link #getOauthData(String, String, String, String, boolean)} */ - public OauthData getOauthData( - String code, String clientId, String secret, boolean autoSetRequestToken) - throws HelloSignException { - Map fields = new HashMap(); - // TODO: What should this be? - fields.put(OAUTH_STATE, "demo"); - fields.put(OAUTH_CODE, code); - fields.put(CLIENT_ID, clientId); - fields.put(OAUTH_GRANT_TYPE, OAUTH_GRANT_TYPE_AUTHORIZE_CODE); - fields.put(CLIENT_SECRET, secret); - HttpPostRequest request = new HttpPostRequest(URL_OAUTH_TOKEN, fields, auth); - JSONObject json = request.getJsonResponse(); - OauthData data = new OauthData(json); + public OauthData getOauthData(String code, String clientId, String secret, boolean autoSetRequestToken) throws HelloSignException { + return getOauthData(code, clientId, secret, "demo", autoSetRequestToken); + } + + /** + * Performs an OAuth request and returns the necessary data for authorizing an API + * application, and will automatically set the access token and code for making + * authenticated requests with this client. + * @param code String OAuth code + * @param clientId String OAuth client ID + * @param secret String OAuth secret + * @param state String OAuth client state + * @param autoSetRequestToken true if the token should be applied to this client + * for future requests + * @return OauthData object containing OAuth token details + * @throws HelloSignException thrown if there's a problem processing + * the HTTP request or the JSON response. + */ + public OauthData getOauthData(String code, String clientId, String secret, String state, boolean autoSetRequestToken) throws HelloSignException { + OauthData data = new OauthData(httpClient + .withAuth(auth) + .withPostField(OAUTH_STATE, state) + .withPostField(OAUTH_CODE, code) + .withPostField(CLIENT_ID, clientId) + .withPostField(OAUTH_GRANT_TYPE, OAUTH_GRANT_TYPE_AUTHORIZE_CODE) + .withPostField(CLIENT_SECRET, secret) + .post(OAUTH_TOKEN_URL) + .asJson()); if (data != null && autoSetRequestToken) { setAccessToken(data.getAccessToken(), data.getTokenType()); } @@ -455,14 +433,13 @@ public OauthData getOauthData( * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public OauthData refreshOauthData(String refreshToken) - throws HelloSignException { - Map fields = new HashMap(); - fields.put(OAUTH_GRANT_TYPE, OAUTH_GRANT_TYPE_REFRESH_TOKEN); - fields.put(OAUTH_REFRESH_TOKEN, refreshToken); - HttpPostRequest request = new HttpPostRequest(URL_OAUTH_TOKEN, fields, auth); - JSONObject json = request.getJsonResponse(); - OauthData data = new OauthData(json); + public OauthData refreshOauthData(String refreshToken) throws HelloSignException { + OauthData data = new OauthData(httpClient + .withAuth(auth) + .withPostField(OAUTH_GRANT_TYPE, OAUTH_GRANT_TYPE_REFRESH_TOKEN) + .withPostField(OAUTH_REFRESH_TOKEN, refreshToken) + .post(OAUTH_TOKEN_URL) + .asJson()); if (data != null) { setAccessToken(data.getAccessToken(), data.getTokenType()); } @@ -476,8 +453,10 @@ public OauthData refreshOauthData(String refreshToken) * the HTTP request or the JSON response. */ public Team getTeam() throws HelloSignException { - HttpGetRequest request = new HttpGetRequest(URL_TEAM, auth); - return new Team(request.getJsonResponse()); + return new Team(httpClient + .withAuth(auth) + .get(BASE_URI + TEAM_URI) + .asJson()); } /** @@ -488,22 +467,24 @@ public Team getTeam() throws HelloSignException { * the HTTP request or the JSON response. */ public Team createTeam(String teamName) throws HelloSignException { - Map fields = new HashMap(); - fields.put(Team.TEAM_NAME, teamName); - HttpPostRequest request = new HttpPostRequest(URL_TEAM_CREATE, fields, auth); - JSONObject json = request.getJsonResponse(); - return new Team(json); + return new Team(httpClient + .withAuth(auth) + .withPostField(Team.TEAM_NAME, teamName) + .post(BASE_URI + TEAM_URI) + .asJson()); } /** * Destroys the current user's team. - * @return int HTTP Status + * @return boolean if destroy was successful * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public int destroyTeam() throws HelloSignException { - HttpPostRequest request = new HttpPostRequest(URL_TEAM_DESTROY, auth); - return request.getHttpResponseCode(); + public boolean destroyTeam() throws HelloSignException { + return HttpURLConnection.HTTP_OK == httpClient + .withAuth(auth) + .post(BASE_URI + TEAM_DESTROY_URI) + .asHttpCode(); } /** @@ -514,13 +495,13 @@ public int destroyTeam() throws HelloSignException { * the HTTP request or the JSON response. */ public Team updateTeamName(String teamName) throws HelloSignException { - Map fields = new HashMap(); - fields.put(Team.TEAM_NAME, teamName); - HttpPostRequest request = new HttpPostRequest(URL_TEAM, fields, auth); - JSONObject json = request.getJsonResponse(); - return new Team(json); + return new Team(httpClient + .withAuth(auth) + .withPostField(Team.TEAM_NAME, teamName) + .post(BASE_URI + TEAM_URI) + .asJson()); } - + /** * Adds the user to the current user's team. * @param idOrEmail String new team member's account ID or email address @@ -529,15 +510,12 @@ public Team updateTeamName(String teamName) throws HelloSignException { * the HTTP request or the JSON response. */ public Team inviteTeamMember(String idOrEmail) throws HelloSignException { - Map fields = new HashMap(); - if (idOrEmail.contains("@")) { - fields.put(Account.ACCOUNT_EMAIL_ADDRESS, idOrEmail); - } else { - fields.put(Account.ACCOUNT_ID, idOrEmail); - } - HttpPostRequest request = new HttpPostRequest(URL_TEAM_ADD_MEMBER, fields, auth); - JSONObject json = request.getJsonResponse(); - return new Team(json); + String key = (idOrEmail != null && idOrEmail.contains("@")) ? Account.ACCOUNT_EMAIL_ADDRESS : Account.ACCOUNT_ID; + return new Team(httpClient + .withAuth(auth) + .withPostField(key, idOrEmail) + .post(BASE_URI + TEAM_ADD_MEMBER_URI) + .asJson()); } /** @@ -548,15 +526,12 @@ public Team inviteTeamMember(String idOrEmail) throws HelloSignException { * the HTTP request or the JSON response. */ public Team removeTeamMember(String idOrEmail) throws HelloSignException { - Map fields = new HashMap(); - if (idOrEmail.contains("@")) { - fields.put(Account.ACCOUNT_EMAIL_ADDRESS, idOrEmail); - } else { - fields.put(Account.ACCOUNT_ID, idOrEmail); - } - HttpPostRequest request = new HttpPostRequest(URL_TEAM_REMOVE_MEMBER, fields, auth); - JSONObject json = request.getJsonResponse(); - return new Team(json); + String key = (idOrEmail != null && idOrEmail.contains("@")) ? Account.ACCOUNT_EMAIL_ADDRESS : Account.ACCOUNT_ID; + return new Team(httpClient + .withAuth(auth) + .withPostField(key, idOrEmail) + .post(BASE_URI + TEAM_REMOVE_MEMBER_URI) + .asJson()); } /** @@ -567,8 +542,11 @@ public Team removeTeamMember(String idOrEmail) throws HelloSignException { * the HTTP request or the JSON response. */ public SignatureRequest getSignatureRequest(String id) throws HelloSignException { - HttpGetRequest request = new HttpGetRequest(URL_SIGNATURE_REQUEST + "/" + id, auth); - return new SignatureRequest(request.getJsonResponse()); + String url = BASE_URI + SIGNATURE_REQUEST_URI + "/" + id; + return new SignatureRequest(httpClient + .withAuth(auth) + .get(url) + .asJson()); } /** @@ -579,10 +557,11 @@ public SignatureRequest getSignatureRequest(String id) throws HelloSignException * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public SignatureRequestList getSignatureRequests() - throws HelloSignException { - HttpGetRequest request = new HttpGetRequest(URL_SIGNATURE_REQUEST_LIST, auth); - return new SignatureRequestList(request.getJsonResponse()); + public SignatureRequestList getSignatureRequests() throws HelloSignException { + return new SignatureRequestList(httpClient + .withAuth(auth) + .get(BASE_URI + SIGNATURE_REQUEST_LIST_URI) + .asJson()); } /** @@ -592,13 +571,12 @@ public SignatureRequestList getSignatureRequests() * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public SignatureRequestList getSignatureRequests(int page) - throws HelloSignException { - Map params = new HashMap(); - params.put(AbstractResourceList.PAGE, Integer.toString(page)); - HttpGetRequest request = new HttpGetRequest( - URL_SIGNATURE_REQUEST_LIST, params, auth); - return new SignatureRequestList(request.getJsonResponse()); + public SignatureRequestList getSignatureRequests(int page) throws HelloSignException { + return new SignatureRequestList(httpClient + .withAuth(auth) + .withGetParam(AbstractResourceList.PAGE, Integer.toString(page)) + .get(BASE_URI + SIGNATURE_REQUEST_LIST_URI) + .asJson()); } /** @@ -611,13 +589,13 @@ public SignatureRequestList getSignatureRequests(int page) public SignatureRequest sendSignatureRequest(SignatureRequest req) throws HelloSignException { if (req.hasId()) { - throw new HelloSignException( - "Sending an existing signature request is not supported"); + throw new HelloSignException("Sending an existing signature request is not supported"); } - HttpPostRequest request = new HttpPostRequest( - URL_SIGNATURE_REQUEST_SEND, req.getPostFields(), auth); - JSONObject json = request.getJsonResponse(); - return new SignatureRequest(json); + return new SignatureRequest(httpClient + .withAuth(auth) + .withPostFields(req.getPostFields()) + .post(BASE_URI + SIGNATURE_REQUEST_SEND_URI) + .asJson()); } /** @@ -636,16 +614,16 @@ public SignatureRequest sendSignatureRequest(SignatureRequest req) * HTTP request or the JSON response. */ public SignatureRequest updateSignatureRequest( - String signature_request_id, - String signature_id, - String new_email_address) throws HelloSignException { - String url = this.URL_SIGNATURE_REQUEST_UPDATE + "/" + signature_request_id; - Map fields = new HashMap(); - fields.put(Signature.SIGNATURE_ID, signature_id); - fields.put(SignatureRequest.SIGREQ_SIGNER_EMAIL, new_email_address); - HttpPostRequest request = new HttpPostRequest(url, fields, auth); - JSONObject json = request.getJsonResponse(); - return new SignatureRequest(json); + String signatureRequestId, + String signatureId, + String newEmailAddress) throws HelloSignException { + String url = BASE_URI + SIGNATURE_REQUEST_UPDATE_URI + "/" + signatureRequestId; + return new SignatureRequest(httpClient + .withAuth(auth) + .withPostField(Signature.SIGNATURE_ID, signatureId) + .withPostField(SignatureRequest.SIGREQ_SIGNER_EMAIL, newEmailAddress) + .post(url) + .asJson()); } /** @@ -655,8 +633,10 @@ public SignatureRequest updateSignatureRequest( * the HTTP request or the JSON response. */ public TemplateList getTemplates() throws HelloSignException { - HttpGetRequest request = new HttpGetRequest(URL_TEMPLATE_LIST, auth); - return new TemplateList(request.getJsonResponse()); + return new TemplateList(httpClient + .withAuth(auth) + .get(BASE_URI + TEMPLATE_LIST_URI) + .asJson()); } /** @@ -667,10 +647,11 @@ public TemplateList getTemplates() throws HelloSignException { * the HTTP request or the JSON response. */ public TemplateList getTemplates(int page) throws HelloSignException { - Map params = new HashMap(); - params.put(AbstractResourceList.PAGE, Integer.toString(page)); - HttpGetRequest request = new HttpGetRequest(URL_TEMPLATE_LIST, params, auth); - return new TemplateList(request.getJsonResponse()); + return new TemplateList(httpClient + .withAuth(auth) + .withGetParam(AbstractResourceList.PAGE, Integer.toString(page)) + .get(BASE_URI + TEMPLATE_LIST_URI) + .asJson()); } @@ -683,9 +664,34 @@ public TemplateList getTemplates(int page) throws HelloSignException { * the HTTP request or the JSON response. */ public File getTemplateFile(String templateId) throws HelloSignException { - String url = URL_TEMPLATE_FILE + "/" + templateId; - HttpGetRequest request = new HttpGetRequest(url, auth); - return request.getFileResponse(TEMPLATE_FILE_NAME + "." + TEMPLATE_FILE_EXT); + String url = BASE_URI + TEMPLATE_FILE_URI + "/" + templateId; + String fileName = TEMPLATE_FILE_NAME + "." + TEMPLATE_FILE_EXT; + return httpClient.withAuth(auth).get(url).asFile(fileName); + } + + /** + * Returns a signed URL that can be used to retrieve the file backing a template. + * @param templateId String Template ID + * @return String URL or null if no file URL can be retrieved + * @throws HelloSignException thrown if there's a problem processing + * the HTTP request or the JSON response. + */ + public String getTemplateFileUrl(String templateId) throws HelloSignException { + String fileUrl = null; + String url = BASE_URI + TEMPLATE_FILE_URI + "/" + templateId; + JSONObject response = httpClient + .withAuth(auth) + .withGetParam(PARAM_TEMPLATE_GET_URL, "1") + .get(url) + .asJson(); + if (response.has("file_url")) { + try { + fileUrl = response.getString("file_url"); + } catch (JSONException ex) { + throw new HelloSignException(ex); + } + } + return fileUrl; } /** @@ -696,9 +702,8 @@ public File getTemplateFile(String templateId) throws HelloSignException { * the HTTP request or the JSON response. */ public Template getTemplate(String templateId) throws HelloSignException { - String url = URL_TEMPLATE + "/" + templateId; - HttpGetRequest request = new HttpGetRequest(url, auth); - return new Template(request.getJsonResponse()); + String url = BASE_URI + TEMPLATE_URI + "/" + templateId; + return new Template(httpClient.withAuth(auth).get(url).asJson()); } /** @@ -712,27 +717,25 @@ public Template getTemplate(String templateId) throws HelloSignException { */ public Template addTemplateUser(String templateId, String idOrEmail) throws HelloSignException { - String url = URL_TEMPLATE_ADD_USER + "/" + templateId; - Map fields = new HashMap(); - if (idOrEmail.contains("@")) { - fields.put(Account.ACCOUNT_EMAIL_ADDRESS, idOrEmail); - } else { - fields.put(Account.ACCOUNT_ID, idOrEmail); - } - HttpPostRequest request = new HttpPostRequest(url, fields, auth); - JSONObject json = request.getJsonResponse(); - return new Template(json); + String url = BASE_URI + TEMPLATE_ADD_USER_URI + "/" + templateId; + String key = (idOrEmail != null && idOrEmail.contains("@")) ? Account.ACCOUNT_EMAIL_ADDRESS : Account.ACCOUNT_ID; + return new Template(httpClient + .withAuth(auth) + .withPostField(key, idOrEmail) + .post(url) + .asJson()); } - public boolean deleteTemplate(String templateId) - throws HelloSignException { - String url = this.URL_TEMPLATE_DELETE + "/" + templateId; - HttpPostRequest request = new HttpPostRequest(url, auth); - int response = request.getHttpResponseCode(); - if (response == 200) { - return true; - } - throw new HelloSignException("Unable to delete template with ID " + templateId + ". Server returned: " + response); + /** + * Delete the template designated by the template id + * @param templateId String template ID + * @return true if the delete was successful, false otherwise + * @throws HelloSignException thrown if there is a problem processing + * the HTTP request + */ + public boolean deleteTemplate(String templateId) throws HelloSignException { + String url = BASE_URI + TEMPLATE_DELETE_URI + "/" + templateId; + return HttpURLConnection.HTTP_OK == httpClient.withAuth(auth).post(url).asHttpCode(); } /** @@ -744,18 +747,14 @@ public boolean deleteTemplate(String templateId) * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public Template removeTemplateUser(String templateId, String idOrEmail) - throws HelloSignException { - String url = URL_TEMPLATE_REMOVE_USER + "/" + templateId; - Map fields = new HashMap(); - if (idOrEmail.contains("@")) { - fields.put(Account.ACCOUNT_EMAIL_ADDRESS, idOrEmail); - } else { - fields.put(Account.ACCOUNT_ID, idOrEmail); - } - HttpPostRequest request = new HttpPostRequest(url, fields, auth); - JSONObject json = request.getJsonResponse(); - return new Template(json); + public Template removeTemplateUser(String templateId, String idOrEmail) throws HelloSignException { + String url = BASE_URI + TEMPLATE_REMOVE_USER_URI + "/" + templateId; + String key = (idOrEmail != null && idOrEmail.contains("@")) ? Account.ACCOUNT_EMAIL_ADDRESS : Account.ACCOUNT_ID; + return new Template(httpClient + .withAuth(auth) + .withPostField(key, idOrEmail) + .post(url) + .asJson()); } /** @@ -765,26 +764,25 @@ public Template removeTemplateUser(String templateId, String idOrEmail) * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public SignatureRequest sendTemplateSignatureRequest(TemplateSignatureRequest req) - throws HelloSignException { - HttpPostRequest request = new HttpPostRequest(URL_TEMPLATE_SIGNATURE_REQUEST, - req.getPostFields(), auth); - JSONObject json = request.getJsonResponse(); - return new SignatureRequest(json); + public SignatureRequest sendTemplateSignatureRequest(TemplateSignatureRequest req) throws HelloSignException { + return new SignatureRequest(httpClient + .withAuth(auth) + .withPostFields(req.getPostFields()) + .post(BASE_URI + TEMPLATE_SIGNATURE_REQUEST_URI) + .asJson()); } /** * Cancels an existing signature request. If it has been completed, it will delete * the signature request from your account. * @param id SignatureRequest id - * @return HttpStatus code + * @return boolean true if successful * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public int cancelSignatureRequest(String id) throws HelloSignException { - String cancelUrl = URL_SIGNATURE_REQUEST_CANCEL + "/" + id; - HttpPostRequest request = new HttpPostRequest(cancelUrl, auth); - return request.getHttpResponseCode(); + public boolean cancelSignatureRequest(String id) throws HelloSignException { + String url = BASE_URI + SIGNATURE_REQUEST_CANCEL_URI + "/" + id; + return HttpURLConnection.HTTP_OK == httpClient.withAuth(auth).post(url).asHttpCode(); } /** @@ -800,14 +798,13 @@ public int cancelSignatureRequest(String id) throws HelloSignException { * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public SignatureRequest requestEmailReminder(String requestId, String email) - throws HelloSignException { - Map fields = new HashMap(); - fields.put(Account.ACCOUNT_EMAIL_ADDRESS, email); - String remindUrl = URL_SIGNATURE_REQUEST_REMIND + "/" + requestId; - HttpPostRequest request = new HttpPostRequest(remindUrl, fields, auth); - JSONObject json = request.getJsonResponse(); - return new SignatureRequest(json); + public SignatureRequest requestEmailReminder(String requestId, String email) throws HelloSignException { + String url = BASE_URI + SIGNATURE_REQUEST_REMIND_URI + "/" + requestId; + return new SignatureRequest(httpClient + .withAuth(auth) + .withPostField(Account.ACCOUNT_EMAIL_ADDRESS, email) + .post(url) + .asJson()); } /** @@ -816,13 +813,12 @@ public SignatureRequest requestEmailReminder(String requestId, String email) * @return File final copy file, or null if it does not yet exist * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. - * @deprecated Use getFiles(requestId) + * @deprecated Use {{@link #getFiles(String)} */ public File getFinalCopy(String requestId) throws HelloSignException { - String finalCopyUrl = URL_SIGNATURE_REQUEST_FINAL_COPY + "/" + requestId; - String filename = FINAL_COPY_FILE_NAME + "." + FINAL_COPY_FILE_EXT; - HttpGetRequest request = new HttpGetRequest(finalCopyUrl, auth); - return request.getFileResponse(filename); + String url = BASE_URI + SIGNATURE_REQUEST_FINAL_COPY_URI + "/" + requestId; + String filename = FINAL_COPY_FILE_NAME + "." + FINAL_COPY_FILE_EXT; + return httpClient.withAuth(auth).get(url).asFile(filename); } /** @@ -848,11 +844,13 @@ public File getFiles(String requestId, String format) throws HelloSignException if (format == null || format.isEmpty()) { format = FILES_FILE_EXT; } - String filesUrl = URL_SIGNATURE_REQUEST_FILES + "/" + requestId + - "?" + URL_PARAM_FILE_TYPE + "=" + format; - HttpGetRequest request = new HttpGetRequest(filesUrl, null, auth); - String filename = FILES_FILE_NAME + "." + format; - return request.getFileResponse(filename); + String url = BASE_URI + SIGNATURE_REQUEST_FILES_URI + "/" + requestId; + String fileName = FILES_FILE_NAME + "." + format; + return httpClient + .withAuth(auth) + .withGetParam(PARAM_FILE_TYPE_URI, format) + .get(url) + .asFile(fileName); } /** @@ -862,26 +860,29 @@ public File getFiles(String requestId, String format) throws HelloSignException * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public AbstractRequest createEmbeddedRequest(EmbeddedRequest embeddedReq) - throws HelloSignException { - String url = URL_SIGNATURE_REQUEST_EMBEDDED; + public AbstractRequest createEmbeddedRequest(EmbeddedRequest embeddedReq) throws HelloSignException { + String url = BASE_URI; Class returnType = SignatureRequest.class; AbstractRequest req = embeddedReq.getRequest(); if (req instanceof TemplateSignatureRequest) { - url = URL_SIGNATURE_REQUEST_EMBEDDED_TEMPLATE; + url += SIGNATURE_REQUEST_EMBEDDED_TEMPLATE_URI; } else if (req instanceof UnclaimedDraft) { if (((UnclaimedDraft) req).getRequest() instanceof TemplateSignatureRequest) { - url = URL_UNCLAIMED_DRAFT_CREATE_EMBEDDED_WITH_TEMPLATE; + url += UNCLAIMED_DRAFT_CREATE_EMBEDDED_WITH_TEMPLATE_URI; } else { - url = URL_UNCLAIMED_DRAFT_CREATE_EMBEDDED; + url += UNCLAIMED_DRAFT_CREATE_EMBEDDED_URI; } returnType = UnclaimedDraft.class; + } else { + url += SIGNATURE_REQUEST_EMBEDDED_URI; } - HttpPostRequest request = new HttpPostRequest(url, embeddedReq.getPostFields(), auth); - JSONObject json = request.getJsonResponse(); try { Constructor constructor = returnType.getConstructor(JSONObject.class); - return (AbstractRequest) constructor.newInstance(json); + return (AbstractRequest) constructor.newInstance(httpClient + .withAuth(auth) + .withPostFields(embeddedReq.getPostFields()) + .post(url) + .asJson()); } catch (Exception ex) { throw new HelloSignException(ex); } @@ -895,12 +896,12 @@ public AbstractRequest createEmbeddedRequest(EmbeddedRequest embeddedReq) * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public EmbeddedResponse getEmbeddedSignUrl(String signatureId) - throws HelloSignException { - String url = URL_EMBEDDED_SIGN_URL + "/" + signatureId; - HttpGetRequest request = new HttpGetRequest(url, auth); - JSONObject json = request.getJsonResponse(); - return new EmbeddedResponse(json); + public EmbeddedResponse getEmbeddedSignUrl(String signatureId) throws HelloSignException { + String url = BASE_URI + EMBEDDED_SIGN_URL_URI + "/" + signatureId; + return new EmbeddedResponse(httpClient + .withAuth(auth) + .post(url) + .asJson()); } /** @@ -910,9 +911,8 @@ public EmbeddedResponse getEmbeddedSignUrl(String signatureId) * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public EmbeddedResponse getEmbeddedTemplateEditUrl(String templateId) - throws HelloSignException { - return getEmbeddedTemplateEditUrl(templateId, false, false); + public EmbeddedResponse getEmbeddedTemplateEditUrl(String templateId) throws HelloSignException { + return getEmbeddedTemplateEditUrl(templateId, false, false, false); } /** @@ -929,19 +929,33 @@ public EmbeddedResponse getEmbeddedTemplateEditUrl(String templateId) */ public EmbeddedResponse getEmbeddedTemplateEditUrl(String templateId, boolean skipSignerRoles, boolean skipSubjectMessage) throws HelloSignException { - String url = this.URL_EMBEDDED_EDIT_URL + "/" + templateId; - if (skipSignerRoles || skipSubjectMessage) { - url += '?'; - if (skipSignerRoles) { - url += "skip_signer_roles=1"; - } - if (skipSubjectMessage) { - url += "skip_subject_message=1"; - } - } - HttpPostRequest request = new HttpPostRequest(url, auth); - JSONObject json = request.getJsonResponse(); - return new EmbeddedResponse(json); + return getEmbeddedTemplateEditUrl(templateId, skipSignerRoles, skipSubjectMessage, false); + } + + /** + * Retrieves the necessary information to edit an embedded template. + * @param templateId String ID of the signature request to embed + * @param skipSignerRoles true if the edited template should not allow + * the user to modify the template's signer roles. Defaults to false. + * @param skipSubjectMessage true if the edited template should + * not allow the user to modify the template's subject and message. + * Defaults to false. + * @param testMode true if this request is a test request. Useful for + * editing locked templates. + * @return EmbeddedResponse + * @throws HelloSignException thrown if there's a problem processing + * the HTTP request or the JSON response. + */ + public EmbeddedResponse getEmbeddedTemplateEditUrl(String templateId, boolean skipSignerRoles, boolean skipSubjectMessage, boolean testMode) + throws HelloSignException { + String url = BASE_URI + EMBEDDED_EDIT_URL_URI + "/" + templateId; + return new EmbeddedResponse(httpClient + .withAuth(auth) + .withPostField(EMBEDDED_TEMPLATE_SKIP_SIGNER_ROLES, skipSignerRoles) + .withPostField(EMBEDDED_TEMPLATE_SKIP_SUBJECT_MESSAGE, skipSubjectMessage) + .withPostField(AbstractRequest.REQUEST_TEST_MODE, testMode) + .post(url) + .asJson()); } /** @@ -951,15 +965,18 @@ public EmbeddedResponse getEmbeddedTemplateEditUrl(String templateId, boolean sk * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public UnclaimedDraft createUnclaimedDraft(UnclaimedDraft draft) - throws HelloSignException { - String url = URL_UNCLAIMED_DRAFT_CREATE; + public UnclaimedDraft createUnclaimedDraft(UnclaimedDraft draft) throws HelloSignException { + String url = BASE_URI; if (draft.isForEmbeddedSigning()) { - url = URL_UNCLAIMED_DRAFT_CREATE_EMBEDDED; + url += UNCLAIMED_DRAFT_CREATE_EMBEDDED_URI; + } else { + url += UNCLAIMED_DRAFT_CREATE_URI; } - HttpPostRequest request = new HttpPostRequest(url, draft.getPostFields(), auth); - JSONObject json = request.getJsonResponse(); - return new UnclaimedDraft(json); + return new UnclaimedDraft(httpClient + .withAuth(auth) + .withPostFields(draft.getPostFields()) + .post(url) + .asJson()); } /** @@ -969,18 +986,12 @@ public UnclaimedDraft createUnclaimedDraft(UnclaimedDraft draft) * @throws HelloSignException thrown if there's a problem processing * the HTTP request or the JSON response. */ - public TemplateDraft createEmbeddedTemplateDraft(EmbeddedRequest req) - throws HelloSignException { - String url = URL_TEMPLATE_CREATE_EMBEDDED_DRAFT; - Class returnType = TemplateDraft.class; - HttpPostRequest request = new HttpPostRequest(url, req.getPostFields(), auth); - JSONObject json = request.getJsonResponse(); - try { - Constructor constructor = returnType.getConstructor(JSONObject.class); - return (TemplateDraft) constructor.newInstance(json); - } catch (Exception ex) { - throw new HelloSignException(ex); - } + public TemplateDraft createEmbeddedTemplateDraft(EmbeddedRequest req) throws HelloSignException { + return new TemplateDraft(httpClient + .withAuth(auth) + .withPostFields(req.getPostFields()) + .post(BASE_URI + TEMPLATE_CREATE_EMBEDDED_DRAFT_URI) + .asJson()); } /** @@ -991,8 +1002,11 @@ public TemplateDraft createEmbeddedTemplateDraft(EmbeddedRequest req) * the HTTP request or the JSON response. */ public ApiApp getApiApp(String clientId) throws HelloSignException { - HttpGetRequest request = new HttpGetRequest(URL_API_APP + "/" + clientId, auth); - return new ApiApp(request.getJsonResponse()); + String url = BASE_URI + API_APP_URI + "/" + clientId; + return new ApiApp(httpClient + .withAuth(auth) + .get(url) + .asJson()); } /** @@ -1002,8 +1016,10 @@ public ApiApp getApiApp(String clientId) throws HelloSignException { * the HTTP request or the JSON response. */ public ApiAppList getApiApps() throws HelloSignException { - HttpGetRequest request = new HttpGetRequest(URL_API_APP_LIST, auth); - return new ApiAppList(request.getJsonResponse()); + return new ApiAppList(httpClient + .withAuth(auth) + .get(BASE_URI + API_APP_LIST_URI) + .asJson()); } /** @@ -1014,8 +1030,11 @@ public ApiAppList getApiApps() throws HelloSignException { * the HTTP request or the JSON response. */ public ApiApp createApiApp(ApiApp app) throws HelloSignException { - HttpPostRequest request = new HttpPostRequest(URL_API_APP, app.getPostFields(), auth); - return new ApiApp(request.getJsonResponse()); + return new ApiApp(httpClient + .withAuth(auth) + .withPostFields(app.getPostFields()) + .post(BASE_URI + API_APP_URI) + .asJson()); } /** @@ -1026,8 +1045,8 @@ public ApiApp createApiApp(ApiApp app) throws HelloSignException { * the HTTP request or the JSON response. */ public boolean deleteApiApp(String clientId) throws HelloSignException { - HttpDeleteRequest request = new HttpDeleteRequest(URL_API_APP + "/" + clientId, auth); - return HttpURLConnection.HTTP_NO_CONTENT == request.getHttpResponseCode(); + String url = API_APP_URI + "/" + clientId; + return HttpURLConnection.HTTP_NO_CONTENT == httpClient.withAuth(auth).delete(url).asHttpCode(); } /** @@ -1041,26 +1060,27 @@ public ApiApp updateApiApp(ApiApp app) throws HelloSignException { if (!app.hasClientId()) { throw new HelloSignException("Cannot update an ApiApp without a client ID. Create one first!"); } - HttpPutRequest request = new HttpPutRequest(URL_API_APP + "/" + app.getClientId(), app.getPostFields(), auth); - return new ApiApp(request.getJsonResponse()); + String url = API_APP_URI + "/" + app.getClientId(); + return new ApiApp(httpClient.withAuth(auth).withPostFields(app.getPostFields()).put(url).asJson()); } /** - * Performs a simple call to the HelloSign API to see if it's available - * with the given credentials. + * Performs an OPTIONS call to the HelloSign API to see if it's online. * @return true if HelloSign is available and the client is online, * false otherwise. + * @throws HelloSignException thrown if there's a problem processing + * the HTTP request or response. */ - public boolean isOnline() { - HttpURLConnection connection = null; - try { - connection = AbstractHttpRequest.getConnection(URL_API); - connection.setRequestMethod("OPTIONS"); - return HttpURLConnection.HTTP_OK == connection.getResponseCode(); - } catch (Exception ex) { - // Ignore - } - return false; + public boolean isOnline() throws HelloSignException { + boolean isOnline = false; + try { + isOnline = (httpClient.options(BASE_URI).asHttpCode() == HttpURLConnection.HTTP_OK); + } catch (HelloSignException ex) { + throw ex; + } catch (Exception ex) { + throw new HelloSignException(ex); + } + return isOnline; } /** @@ -1074,60 +1094,4 @@ public void setAccessToken(String accessToken, String tokenType) throws HelloSignException { auth.setAccessToken(accessToken, tokenType); } - - // Utility methods to assist in testing, since we are dynamically configuring these URLs - // based on a system property ("hellosign.env"). - public String getApiUrl() { - return URL_API; - } - public String getSignatureRequestUrl() { - return URL_SIGNATURE_REQUEST; - } - public String getSignatureRequestSendUrl() { - return URL_SIGNATURE_REQUEST_SEND; - } - public String getSignatureRequestCancelUrl() { - return URL_SIGNATURE_REQUEST_CANCEL; - } - public String getTemplateSignatureRequestUrl() { - return URL_TEMPLATE_SIGNATURE_REQUEST; - } - - // ======================================================================= - // Static helpers - // ======================================================================= - private static void disableStrictSSL() { - // Create a trust manager that does not validate certificate chains - TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - public void checkClientTrusted(X509Certificate[] certs, - String authType) { - } - - public void checkServerTrusted(X509Certificate[] certs, - String authType) { - } - } }; - - // Ignore differences between given hostname and certificate hostname - HostnameVerifier hv = new HostnameVerifier() { - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - - // Install the all-trusting trust manager - try { - SSLContext sc = SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, new SecureRandom()); - HttpsURLConnection - .setDefaultSSLSocketFactory(sc.getSocketFactory()); - HttpsURLConnection.setDefaultHostnameVerifier(hv); - } catch (Exception e) { - } - } - } diff --git a/src/main/java/com/hellosign/sdk/http/AbstractHttpRequest.java b/src/main/java/com/hellosign/sdk/http/AbstractHttpRequest.java index 1bdd1446..d232073d 100644 --- a/src/main/java/com/hellosign/sdk/http/AbstractHttpRequest.java +++ b/src/main/java/com/hellosign/sdk/http/AbstractHttpRequest.java @@ -1,5 +1,7 @@ package com.hellosign.sdk.http; +import java.io.File; + /** * The MIT License (MIT) * @@ -32,19 +34,31 @@ import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; import java.util.Properties; import java.util.Scanner; -import org.json.JSONException; -import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.hellosign.sdk.HelloSignException; public abstract class AbstractHttpRequest { + + private static final Logger logger = LoggerFactory.getLogger(AbstractHttpRequest.class); public final static String DEFAULT_ENCODING = "UTF-8"; public final static String USER_AGENT = createUserAgent(); + // Request variables + protected String url; + protected Authentication auth; + + // Response variables + protected Integer lastHttpStatusCode; + protected InputStream lastResponseStream; + private static String createUserAgent() { String filename = "config.properties"; Properties props = new Properties(); @@ -65,28 +79,55 @@ private static String createUserAgent() { return "hellosign-java-sdk/" + version; } - protected String url; - protected Authentication auth; + /** + * Executes this HTTP request and preserves the response stream and + * HTTP response code for processing. + * + * @throws HelloSignException Thrown if there is an error while making + * the HTTP request to the HelloSign API. + */ + public void execute() throws HelloSignException { + HttpURLConnection connection = getConnection(); + try { + // Execute the request and save the HTTP status code + lastHttpStatusCode = connection.getResponseCode(); + + // Save the stream object for processing + if (lastHttpStatusCode >= 200 && lastHttpStatusCode < 300) { + logger.debug("OK!"); + lastResponseStream = connection.getInputStream(); + } else { + logger.error("Error! HTTP Code = " + lastHttpStatusCode); + lastResponseStream = connection.getErrorStream(); + } + } catch (Exception ex) { + throw new HelloSignException(ex); + } + } - public static String convertStreamToString(InputStream in) { - Scanner s = new Scanner(in); - s.useDelimiter("\\A"); - String result = (s.hasNext()) ? s.next() : ""; - s.close(); - return result; + /** + * Returns the last HTTP response code. + * @return Integer response code + */ + public Integer getResponseCode() { + return lastHttpStatusCode; } - protected static void validate(JSONObject json, int code) throws HelloSignException { - if (json.has("error")) { - try { - JSONObject error = json.getJSONObject("error"); - String message = error.getString("error_msg"); - String type = error.getString("error_name"); - throw new HelloSignException(message, code, type); - } catch (JSONException ex) { - throw new HelloSignException(ex); - } + /** + * Returns the last response stream as a string. + * @return String + */ + public String getResponseBody() { + String responseStr = ""; + if (lastResponseStream == null) { + logger.error("Unable to parse JSON from empty response!"); + } else { + Scanner s = new Scanner(lastResponseStream); + s.useDelimiter("\\A"); + responseStr = (s.hasNext()) ? s.next() : ""; + s.close(); } + return responseStr; } /** @@ -102,7 +143,7 @@ protected static void validate(JSONObject json, int code) throws HelloSignExcept * @throws MalformedURLException thrown if the URL is invalid * @throws IOException thrown if IO cannot be established with the URL */ - public static HttpURLConnection getConnection(String url) throws MalformedURLException, IOException { + protected static HttpURLConnection getProxiedConnection(String url) throws MalformedURLException, IOException { HttpURLConnection conn = null; Proxy proxy = null; String proxyUrlStr = System.getProperty("hellosign.proxy.url"); @@ -121,4 +162,29 @@ public static HttpURLConnection getConnection(String url) throws MalformedURLExc } return conn; } + + /** + * The method class will create the appropriate connection with + * an endpoint, parameters, etc. + * @return HttpURLConnection + * @throws HelloSignException + */ + abstract protected HttpURLConnection getConnection() throws HelloSignException; + + /** + * Write the last response to a file. + * @param f File + * @return long bytes written + * @throws HelloSignException Thrown if an exception occurs during + * the copy of the response stream to the given file. + */ + public long getResponseAsFile(File f) throws HelloSignException { + long bytesWritten = 0; + try { + bytesWritten = Files.copy(lastResponseStream, f.toPath(), StandardCopyOption.REPLACE_EXISTING); + } catch (Exception e) { + throw new HelloSignException(e); + } + return bytesWritten; + } } diff --git a/src/main/java/com/hellosign/sdk/http/Authentication.java b/src/main/java/com/hellosign/sdk/http/Authentication.java index 261fe2a4..5c3f8b93 100644 --- a/src/main/java/com/hellosign/sdk/http/Authentication.java +++ b/src/main/java/com/hellosign/sdk/http/Authentication.java @@ -57,7 +57,7 @@ public class Authentication { public Authentication() {} - public Authentication (Authentication clone) + public Authentication(Authentication clone) throws HelloSignException { if (clone.hasWebsiteCredentials()) { setWebsiteCredentials(clone.getEmail(), clone.getPassword()); diff --git a/src/main/java/com/hellosign/sdk/http/HttpClient.java b/src/main/java/com/hellosign/sdk/http/HttpClient.java new file mode 100644 index 00000000..8e30bfb4 --- /dev/null +++ b/src/main/java/com/hellosign/sdk/http/HttpClient.java @@ -0,0 +1,347 @@ +package com.hellosign.sdk.http; + +import java.io.File; +import java.io.Serializable; +import java.net.HttpURLConnection; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.HashMap; + +/** + * The MIT License (MIT) + * + * Copyright (C) 2016 hellosign.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import java.util.Map; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.hellosign.sdk.HelloSignException; + +/** + * Abstracts HTTP requests. + * @author cpaul + */ +public class HttpClient { + + private static final Logger logger = LoggerFactory.getLogger(HttpClient.class); + + private Authentication auth; + private Map getParams; + private Map postFields; + private AbstractHttpRequest request; + + // TODO: Could this contain a request factory that doles out an AbstractHttpRequest? + + public HttpClient() { + String disableSslCheck = System.getProperty("hellosign.disable.ssl"); + if (disableSslCheck != null && "true".equalsIgnoreCase(disableSslCheck)) { + disableStrictSSL(); + } + } + + public HttpClient withAuth(Authentication auth) { + this.auth = auth; + return this; + } + + public HttpClient withGetParam(String key, String value) { + if (getParams == null) { + getParams = new HashMap(); + } + getParams.put(key, value); + return this; + } + + public HttpClient withGetParams(Map params) { + getParams = params; + return this; + } + + public HttpClient withPostField(String key, Serializable value) { + if (postFields == null) { + postFields = new HashMap(); + } + postFields.put(key, value); + return this; + } + + public HttpClient withPostFields(Map fields) { + this.postFields = fields; + return this; + } + + /** + * Returns the response to the last HTTP request as a string. + * @return String or null if the request has not been created + */ + public String getLastResponse() { + if (request == null) { + return null; + } + return request.getResponseBody(); + } + + /** + * Returns the HTTP status code for the last request. + * @return Integer or null if the request has not been created + */ + public Integer getLastResponseCode() { + if (request == null) { + return null; + } + return request.getResponseCode(); + } + + /** + * Returns the last HTTP request body as a file. + * @param f File that should contain the response + * @return long bytes written + * @throws HelloSignException thrown if there is a problem + * writing to the file or reading the response stream + */ + public long getLastResponseAsFile(File f) throws HelloSignException { + return request.getResponseAsFile(f); + } + + /** + * Inspects the JSONObject response for errors and throws an exception if found. + * @param json JSONObject response + * @param code HTTP response code + * @throws HelloSignException thrown if an error is reported from the API call + */ + private void validate(JSONObject json) throws HelloSignException { + if (json.has("error")) { + try { + JSONObject error = json.getJSONObject("error"); + String message = error.getString("error_msg"); + String type = error.getString("error_name"); + throw new HelloSignException(message, getLastResponseCode(), type); + } catch (JSONException ex) { + throw new HelloSignException(ex); + } + } + } + + /** + * Clears the client after a request has successfully completed. + */ + private void reset() { + this.auth = null; + this.getParams = null; + this.postFields = null; + this.request = null; + } + + /** + * Executes the request and returns the response as a JSONObject. + * @return JSONObject response + * @throws HelloSignException thrown if there is a problem + * executing the request + */ + public JSONObject asJson() throws HelloSignException + { + JSONObject json = null; + try { + json = new JSONObject(getLastResponse()); + } catch (JSONException e) { + throw new HelloSignException(e); + } + validate(json); + reset(); + return json; + } + + /** + * Executes the request and returns the response as a File. + * @param fileName String name of destination file + * @return File response + * @throws HelloSignException thrown if there is a problem + * executing the request + */ + public File asFile(String fileName) throws HelloSignException + { + Integer lastResponseCode = getLastResponseCode(); + if (lastResponseCode != null && lastResponseCode != HttpURLConnection.HTTP_OK) { + this.asJson(); // Will validate response + } + File f = createTemporaryFile(fileName); + if (getLastResponseAsFile(f) == 0) { + logger.warn("No bytes written to file: " + fileName); + } + reset(); + return f; + } + + /** + * Helper method to create a temporary file. + * @param filename String + * @return File temporary file handle + * @throws HelloSignException thrown if the file cannot be created + */ + private File createTemporaryFile(String filename) throws HelloSignException { + String prefix = filename.substring(0, filename.indexOf(".")); + String postfix = filename.substring(filename.indexOf(".") + 1, filename.length()); + if (prefix == null || postfix == null) { + throw new HelloSignException("Invalid file name: " + prefix + "." + postfix); + } + File f = null; + try { + f = File.createTempFile(prefix, "." + postfix); + } catch (Exception ex) { + throw new HelloSignException(ex); + } + return f; + } + + /** + * Executes the request and returns the HTTP response code. + * @return int HTTP response code + * @throws HelloSignException thrown if no request has been performed + */ + public int asHttpCode() throws HelloSignException + { + Integer code = getLastResponseCode(); + if (code == null) { + throw new HelloSignException("No request performed"); + } + if (code >= 200 && code < 300) { + reset(); + return code; + } + throw new HelloSignException("HTTP Code " + code); + } + + /** + * Initializes a GET request to the given URL. + * @param url String url + * @return HttpClient + * @throws HelloSignException thrown if the url is invalid + */ + public HttpClient get(String url) throws HelloSignException { + if (postFields != null) { + logger.warn("POST fields set for a GET request, they will be ignored"); + } + request = new HttpGetRequest(url, getParams, auth); + request.execute(); + return this; + } + + /** + * Initializes a POST request to the given URL. + * @param url String url + * @return HttpClient + * @throws HelloSignException thrown if the url is invalid + */ + public HttpClient post(String url) throws HelloSignException { + if (getParams != null) { + logger.warn("GET parameters set for a POST request, they will be ignored"); + } + request = new HttpPostRequest(url, postFields, auth); + request.execute(); + return this; + } + + /** + * Initializes a DELETE request to the given URL. + * @param url String url + * @return HttpClient + * @throws HelloSignException thrown if the url is invalid + */ + public HttpClient delete(String url) throws HelloSignException { + request = new HttpDeleteRequest(url, auth); + request.execute(); + return this; + } + + /** + * Makes a PUT request to the given URL + * @param url String url + * @return HttpClient + * @throws HelloSignException thrown if the url is invalid + */ + public HttpClient put(String url) throws HelloSignException { + request = new HttpPutRequest(url, postFields, auth); + request.execute(); + return this; + } + + /** + * Makes an OPTIONS request to the given URL + * @param url String URL + * @return HttpClient + * @throws HelloSignException thrown if the URL is invalid + */ + public HttpClient options(String url) throws HelloSignException { + request = new HttpOptionsRequest(url); + request.execute(); + return this; + } + + /** + * Helper method that allows this client to ignore SSL certificates + * when making API requests. + */ + private void disableStrictSSL() { + // Create a trust manager that does not validate certificate chains + TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public void checkClientTrusted(X509Certificate[] certs, + String authType) { + } + + public void checkServerTrusted(X509Certificate[] certs, + String authType) { + } + } }; + + // Ignore differences between given hostname and certificate hostname + HostnameVerifier hv = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + // Install the all-trusting trust manager + try { + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new SecureRandom()); + HttpsURLConnection + .setDefaultSSLSocketFactory(sc.getSocketFactory()); + HttpsURLConnection.setDefaultHostnameVerifier(hv); + } catch (Exception e) { + } + } +} diff --git a/src/main/java/com/hellosign/sdk/http/HttpDeleteRequest.java b/src/main/java/com/hellosign/sdk/http/HttpDeleteRequest.java index 222ae7ee..a6362fa2 100644 --- a/src/main/java/com/hellosign/sdk/http/HttpDeleteRequest.java +++ b/src/main/java/com/hellosign/sdk/http/HttpDeleteRequest.java @@ -2,21 +2,16 @@ import java.net.HttpURLConnection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.hellosign.sdk.HelloSignException; public class HttpDeleteRequest extends AbstractHttpRequest { - private static final Logger logger = LoggerFactory.getLogger(HttpDeleteRequest.class); - public HttpDeleteRequest(String url) throws HelloSignException { this(url, null); } public HttpDeleteRequest(String url, Authentication auth) throws HelloSignException { - if (url == null || "".equals(url)) { + if (url == null || url.isEmpty()) { throw new HelloSignException("URL cannot be null or empty"); } this.url = url; @@ -25,23 +20,22 @@ public HttpDeleteRequest(String url, Authentication auth) throws HelloSignExcept } } - public int getHttpResponseCode() throws HelloSignException { - try { - logger.debug("DELETE: " + url); - HttpURLConnection connection = getConnection(url); - connection.setRequestProperty("Accept-Charset", DEFAULT_ENCODING); - connection.setRequestProperty("user-agent", USER_AGENT); - if (auth != null) { - logger.debug("Authenticating..."); - auth.authenticate(connection, url); - } - connection.setDoOutput(true); - connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); - connection.setRequestMethod("DELETE"); - connection.connect(); - return connection.getResponseCode(); - } catch (Exception e) { - throw new HelloSignException(e); - } - } + @Override + protected HttpURLConnection getConnection() throws HelloSignException { + HttpURLConnection connection; + try { + connection = getProxiedConnection(url); + connection.setRequestProperty("Accept-Charset", DEFAULT_ENCODING); + connection.setRequestProperty("user-agent", USER_AGENT); + if (auth != null) { + auth.authenticate(connection, url); + } + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + connection.setRequestMethod("DELETE"); + } catch (Exception ex) { + throw new HelloSignException(ex); + } + return connection; + } } diff --git a/src/main/java/com/hellosign/sdk/http/HttpGetRequest.java b/src/main/java/com/hellosign/sdk/http/HttpGetRequest.java index 10e48669..ede10381 100644 --- a/src/main/java/com/hellosign/sdk/http/HttpGetRequest.java +++ b/src/main/java/com/hellosign/sdk/http/HttpGetRequest.java @@ -24,21 +24,12 @@ * SOFTWARE. */ -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; -import java.net.MalformedURLException; import java.net.URLEncoder; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; import java.util.Iterator; import java.util.Map; -import org.json.JSONException; -import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -90,8 +81,7 @@ public HttpGetRequest(String url, Map parameters) * @param url String * @param parameters Map * @param auth Authentication - * @throws HelloSignException thrown if there is a problem making - * the HTTP request or processing the response + * @throws HelloSignException thrown the URL is empty */ public HttpGetRequest(String url, Map parameters, Authentication auth) throws HelloSignException { @@ -108,100 +98,33 @@ public HttpGetRequest(String url, Map parameters, Authentication } /** - * Executes the GET request and converts the response to a JSON - * object. - * @return JSONObject - * @throws HelloSignException thrown if there is a problem making - * the HTTP request. - */ - public JSONObject getJsonResponse() throws HelloSignException { - JSONObject json = null; - try { - HttpURLConnection connection = get(url, parameters, auth); - int httpCode = connection.getResponseCode(); - InputStream is = null; - if (HttpURLConnection.HTTP_OK == httpCode) { - is = connection.getInputStream(); - } else { - is = connection.getErrorStream(); - } - String response = convertStreamToString(is); - json = new JSONObject(response); - validate(json, httpCode); - } catch (HelloSignException e) { - throw e; - } catch (Exception e) { - throw new HelloSignException(e); - } - return json; - } - - /** - * Execute the GET request and process the response as a file. The file - * will be stored as a temporary file with the given filename, but using - * the File.createTemporaryFile() method. This file will append a - * timestamp to the filename. - * @param filename String - * @return File - * @throws HelloSignException thrown if there is a problem creating the file - */ - public File getFileResponse(String filename) throws HelloSignException { - File f = createTemporaryFile(filename); - return getFile(url, auth, f); - } - - /** - * Helper method to create a temporary file. - * @param filename String - * @return File - * @throws HelloSignException thrown if the file cannot be created + * @return HttpURLConnection used to make the HTTP request + * @see AbstractHttpRequest#getConnection() */ - private static File createTemporaryFile(String filename) - throws HelloSignException { - String prefix = filename.substring(0, filename.indexOf(".")); - String postfix = filename.substring(filename.indexOf(".") + 1, filename.length()); - if (prefix == null || postfix == null) { - throw new HelloSignException("Invalid file name: " + prefix + "." + postfix); - } - File f = null; - try { - f = File.createTempFile(prefix, "." + postfix); - } catch (IOException ex) { - ex.printStackTrace(); - throw new HelloSignException(ex.getMessage()); - } - return f; - } - - /** - * Helper method to execute an HTTP GET request. - * @param url String - * @param parameters Map - * @param auth Authentication - * @return HttpURLConnection - * @throws UnsupportedEncodingException thrown if the encoding is not supported - * @throws IOException thrown if there is a problem handling the request - * @throws MalformedURLException thrown if the URL is unrecognizable - */ - private static HttpURLConnection get(String url, - Map parameters, Authentication auth) - throws UnsupportedEncodingException, IOException, - MalformedURLException { + @Override + protected HttpURLConnection getConnection() throws HelloSignException { if (parameters != null) { url += "?"; Iterator keys = parameters.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); - url += URLEncoder.encode(key, DEFAULT_ENCODING) - + "=" + - URLEncoder.encode(parameters.get(key), DEFAULT_ENCODING); + try { + url += URLEncoder.encode(key, DEFAULT_ENCODING) + "=" + URLEncoder.encode(parameters.get(key), DEFAULT_ENCODING); + } catch (UnsupportedEncodingException ex) { + throw new HelloSignException(ex); + } if (keys.hasNext()) { url += "&"; } } } logger.debug("GET: " + url); - HttpURLConnection connection = getConnection(url); + HttpURLConnection connection; + try { + connection = getProxiedConnection(url); + } catch (Exception e) { + throw new HelloSignException(e); + } connection.setRequestProperty("Accept-Charset", DEFAULT_ENCODING); connection.setRequestProperty("user-agent", USER_AGENT); if (auth != null) { @@ -210,61 +133,4 @@ private static HttpURLConnection get(String url, } return connection; } - - /** - * Helper method to make an HTTP request and return a File object. - * @param url String - * @param auth Authentication - * @param f File that will be written to - * @return File - * @throws HelloSignException thrown if there is a problem with the - * HTTP request or writing to the file - */ - private static File getFile(String url, Authentication auth, File f) - throws HelloSignException { - InputStream in = null; - OutputStream out = null; - try { - HttpURLConnection connection = get(url, null, auth); - int httpCode = connection.getResponseCode(); - if (httpCode == HttpURLConnection.HTTP_OK) { - Files.copy(connection.getInputStream(), f.toPath(), StandardCopyOption.REPLACE_EXISTING); - return f; - } - - // We know we encountered an error here, so let's parse - // the response as an API error message - in = connection.getErrorStream(); - String responseStr = convertStreamToString(in); - try { - JSONObject json = new JSONObject(responseStr); - validate(json, httpCode); - } catch (JSONException e) { - throw new HelloSignException( - "Error encountered attempting to parse API error response: " - + e.getMessage()); - } - - // If we were not able to throw an exception by now, - // throw one, because the user should not be here. - throw new HelloSignException( - "Unable to process response from HelloSign. Please contact support."); - - } catch (HelloSignException ex) { - // Rethrow any exceptions we're throwing ourselves - throw ex; - } catch (Exception e) { - // Wrap any exceptions we receive - throw new HelloSignException(e); - } finally { - // Cleanup - if (in != null) { - try { in.close(); } catch (Exception e) {} - } - if (out != null) { - try { out.close(); } catch (Exception e) {} - } - } - } - } diff --git a/src/main/java/com/hellosign/sdk/http/HttpOptionsRequest.java b/src/main/java/com/hellosign/sdk/http/HttpOptionsRequest.java new file mode 100644 index 00000000..c829828f --- /dev/null +++ b/src/main/java/com/hellosign/sdk/http/HttpOptionsRequest.java @@ -0,0 +1,24 @@ +package com.hellosign.sdk.http; + +import java.net.HttpURLConnection; + +import com.hellosign.sdk.HelloSignException; + +public class HttpOptionsRequest extends AbstractHttpRequest { + + public HttpOptionsRequest(String url) { + this.url = url; + } + + @Override + protected HttpURLConnection getConnection() throws HelloSignException { + HttpURLConnection connection = null; + try { + connection = getProxiedConnection(url); + connection.setRequestMethod("OPTIONS"); + } catch (Exception ex) { + throw new HelloSignException(ex); + } + return connection; + } +} diff --git a/src/main/java/com/hellosign/sdk/http/HttpPostRequest.java b/src/main/java/com/hellosign/sdk/http/HttpPostRequest.java index 59689678..b5ad4974 100644 --- a/src/main/java/com/hellosign/sdk/http/HttpPostRequest.java +++ b/src/main/java/com/hellosign/sdk/http/HttpPostRequest.java @@ -27,7 +27,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; @@ -39,7 +38,6 @@ import java.util.Iterator; import java.util.Map; -import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -123,60 +121,6 @@ public HttpPostRequest(String url, Map fields, Authenticat boundary = "===" + Long.toHexString(System.currentTimeMillis()) + "==="; } - /** - * Performs a POST request to the given URL, using the authentication - * details and POST fields provided. - * @return JSONObject - * @throws HelloSignException thrown if there is a problem making the HTTP - * request or processing the result - */ - public JSONObject getJsonResponse() throws HelloSignException { - HttpURLConnection connection = post(); - JSONObject json = null; - try { - int httpCode = connection.getResponseCode(); - InputStream response = null; - if (httpCode >= 200 && httpCode < 300) { - logger.debug("OK!"); - response = connection.getInputStream(); - } else { - logger.error("Error! HTTP Code = " + httpCode); - response = connection.getErrorStream(); - } - String responseStr = ""; - if (response == null) { - logger.error("Unable to parse JSON from empty response!"); - } else { - responseStr = convertStreamToString(response); - logger.debug("String Response: " + responseStr); - json = new JSONObject(responseStr); - validate(json, httpCode); - logger.debug("JSON Response: " + json.toString(2)); - } - } catch (HelloSignException e) { - throw e; - } catch (Exception e) { - throw new HelloSignException(e); - } - return json; - } - - /** - * Performs a field-less POST request to the provided URL using basic auth and - * returns the HTTP code. - * @return int HTTP status code - * @throws HelloSignException thrown if there is a problem making the HTTP - * request or processing the result - */ - public int getHttpResponseCode() throws HelloSignException { - HttpURLConnection connection = post(); - try { - return connection.getResponseCode(); - } catch (Exception ex) { - throw new HelloSignException(ex.getMessage()); - } - } - /** * Helper method to make an HTTP POST request. Intelligently detects * whether Files have been attached and sends as an multipart form request. @@ -184,7 +128,8 @@ public int getHttpResponseCode() throws HelloSignException { * @throws HelloSignException thrown if there is a problem making the HTTP * request or processing the result */ - private HttpURLConnection post() throws HelloSignException { + @Override + protected HttpURLConnection getConnection() throws HelloSignException { if (fields != null) { for (String key : fields.keySet()) { if (fields.get(key) instanceof File) { @@ -205,7 +150,7 @@ private HttpURLConnection postQuery() throws HelloSignException { logger.debug(this.method + ": " + url); HttpURLConnection connection; try { - connection = getConnection(url); + connection = getProxiedConnection(url); if (!this.method.equals("POST")) { connection.setRequestMethod(method); } @@ -283,7 +228,7 @@ private HttpURLConnection postWithFile() throws HelloSignException { private void openMultipartPostConnection() throws IOException { - httpConn = getConnection(this.url); + httpConn = getProxiedConnection(this.url); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); diff --git a/src/main/java/com/hellosign/sdk/resource/Account.java b/src/main/java/com/hellosign/sdk/resource/Account.java index 49cea779..42795fa6 100644 --- a/src/main/java/com/hellosign/sdk/resource/Account.java +++ b/src/main/java/com/hellosign/sdk/resource/Account.java @@ -49,6 +49,7 @@ public class Account extends AbstractResource { public static final String ACCOUNT_PASSWORD = "password"; private Quotas quotas; + private OauthData oauthData; public Account() { super(); @@ -120,12 +121,16 @@ public RoleType getRoleCode() throws HelloSignException { public boolean hasRoleCode() { return has(ACCOUNT_ROLE_CODE); } + + public Quotas getQuotas() { + return quotas; + } public OauthData getOauthData() throws HelloSignException { - return new OauthData((JSONObject) get(OAUTH_DATA)); + return oauthData; } - public Quotas getQuotas() { - return quotas; - } + public void setOauthData(OauthData data) { + oauthData = data; + } } diff --git a/src/main/java/com/hellosign/sdk/resource/SignatureRequest.java b/src/main/java/com/hellosign/sdk/resource/SignatureRequest.java index 4d5f0d78..40521a15 100644 --- a/src/main/java/com/hellosign/sdk/resource/SignatureRequest.java +++ b/src/main/java/com/hellosign/sdk/resource/SignatureRequest.java @@ -33,6 +33,7 @@ import org.json.JSONObject; import com.hellosign.sdk.HelloSignException; +import com.hellosign.sdk.resource.support.CustomField; import com.hellosign.sdk.resource.support.Document; import com.hellosign.sdk.resource.support.FormField; import com.hellosign.sdk.resource.support.ResponseData; @@ -65,6 +66,7 @@ public class SignatureRequest extends AbstractRequest { public static final String SIGREQ_SIGNING_URL = "signing_url"; public static final String SIGREQ_DETAILS_URL = "details_url"; public static final String SIGREQ_IS_DECLINED = "is_declined"; + public static final String SIGREQ_CUSTOM_FIELDS = "custom_fields"; public static final String SIGREQ_FORMAT_ZIP = "zip"; public static final String SIGREQ_FORMAT_PDF = "pdf"; @@ -372,4 +374,13 @@ public boolean isDeclined() { } return false; } + + /** + * Gets the custom fields associated with this request, + * set when sending the request from a template. + * @return List + */ + public List getCustomFields() { + return getList(CustomField.class, SIGREQ_CUSTOM_FIELDS); + } } \ No newline at end of file diff --git a/src/main/java/com/hellosign/sdk/resource/UnclaimedDraft.java b/src/main/java/com/hellosign/sdk/resource/UnclaimedDraft.java index 4e27e287..de9dab24 100644 --- a/src/main/java/com/hellosign/sdk/resource/UnclaimedDraft.java +++ b/src/main/java/com/hellosign/sdk/resource/UnclaimedDraft.java @@ -26,6 +26,7 @@ import java.io.File; import java.io.Serializable; +import java.util.Date; import java.util.Map; import org.json.JSONObject; @@ -56,6 +57,8 @@ public class UnclaimedDraft extends AbstractRequest { public static final String UNCLAIMED_DRAFT_REQUESTER_EMAIL = "requester_email_address"; public static final String UNCLAIMED_DRAFT_IS_FOR_EMBEDDED_SIGNING = "is_for_embedded_signing"; public static final String UNCLAIMED_DRAFT_SIGNATURE_REQUEST_ID = "signature_request_id"; + public static final String UNCLAIMED_DRAFT_EXPIRES_AT = "expires_at"; + public static final String UNCLAIMED_DRAFT_TEST_MODE = "test_mode"; private UnclaimedDraftType type; @@ -309,6 +312,9 @@ public void setTestMode(boolean testMode) { @Override public boolean isTestMode() { + if (request == null) { + return getBoolean(UNCLAIMED_DRAFT_TEST_MODE); + } return request.isTestMode(); } @@ -331,4 +337,8 @@ public boolean hasRedirectUrl() { public String getId() { return request.getId(); } + + public Date getExpiresAt() { + return getDate(UNCLAIMED_DRAFT_EXPIRES_AT); + } } diff --git a/src/main/java/com/hellosign/sdk/resource/support/CustomField.java b/src/main/java/com/hellosign/sdk/resource/support/CustomField.java index a66ef48b..8c5318b2 100644 --- a/src/main/java/com/hellosign/sdk/resource/support/CustomField.java +++ b/src/main/java/com/hellosign/sdk/resource/support/CustomField.java @@ -49,6 +49,15 @@ public class CustomField extends AbstractResource { public static final String CUSTOM_FIELD_VALUE = "value"; public static final String CUSTOM_FIELD_EDITOR = "editor"; public static final String CUSTOM_FIELD_REQUIRED = "required"; + public static final String CUSTOM_FIELD_X = "x"; + public static final String CUSTOM_FIELD_Y = "y"; + public static final String CUSTOM_FIELD_WIDTH = "width"; + public static final String CUSTOM_FIELD_HEIGHT = "height"; + + // Estimates for character length + public static final String CUSTOM_FIELD_AVG_TEXT_LENGTH = "avg_text_length"; + public static final String CUSTOM_FIELD_NUM_LINES = "num_lines"; + public static final String CUSTOM_FIELD_NUM_CHARS_PER_LINE = "num_chars_per_line"; public CustomField() { super(); @@ -124,4 +133,76 @@ public Boolean isRequired() { public void setIsRequired(Boolean isRequired) { set(CUSTOM_FIELD_REQUIRED, isRequired); } + + /** + * Returns the x coordinate for this field. + * @return Integer or null if not set + */ + public Integer getX() { + return getInteger(CUSTOM_FIELD_X); + } + + /** + * Returns the y coordinate for this field. + * @return Integer or null if not set + */ + public Integer getY() { + return getInteger(CUSTOM_FIELD_Y); + } + + /** + * Returns the pixel width of this field. + * @return Integer or null if not set + */ + public Integer getWidth() { + return getInteger(CUSTOM_FIELD_WIDTH); + } + + /** + * Returns the pixel height of this field. + * @return Integer or null if not set + */ + public Integer getHeight() { + return getInteger(CUSTOM_FIELD_HEIGHT); + } + + /** + * Once processed with a position, height, and width, HelloSign will + * estimate the number of lines a custom field can contain, along with + * the number of characters per line. This method will return the + * estimated average number of lines of text this field can hold. + * @return Integer or null if not set + */ + public Integer getEstimatedTextLines() { + if (!dataObj.has(CUSTOM_FIELD_AVG_TEXT_LENGTH)) { + return null; + } + Integer numLines = null; + try { + JSONObject obj = dataObj.getJSONObject(CUSTOM_FIELD_AVG_TEXT_LENGTH); + numLines = obj.getInt(CUSTOM_FIELD_NUM_LINES); + } catch (JSONException e) { + } + return numLines; + } + + /** + * Once processed with a position, height, and width, HelloSign will + * estimate the number of lines a custom field can contain, along with + * the number of characters per line. This method will return the + * estimated average number of characters per line this field can hold. + * @return Integer or null if not set + */ + public Integer getEstimatedCharsPerLine() { + if (!dataObj.has(CUSTOM_FIELD_AVG_TEXT_LENGTH)) { + return null; + } + Integer numLines = null; + try { + JSONObject obj = dataObj.getJSONObject(CUSTOM_FIELD_AVG_TEXT_LENGTH); + numLines = obj.getInt(CUSTOM_FIELD_NUM_CHARS_PER_LINE); + } catch (JSONException e) { + } + return numLines; + } } \ No newline at end of file diff --git a/src/main/java/com/hellosign/sdk/resource/support/FormField.java b/src/main/java/com/hellosign/sdk/resource/support/FormField.java index a5510fc4..238bc496 100644 --- a/src/main/java/com/hellosign/sdk/resource/support/FormField.java +++ b/src/main/java/com/hellosign/sdk/resource/support/FormField.java @@ -27,8 +27,6 @@ import org.json.JSONObject; import com.hellosign.sdk.HelloSignException; -import com.hellosign.sdk.resource.AbstractResource; -import com.hellosign.sdk.resource.support.types.FieldType; import com.hellosign.sdk.resource.support.types.ValidationType; /** @@ -36,17 +34,9 @@ * * @author "Chris Paul (chris@hellosign.com)" */ -public class FormField extends AbstractResource { +public class FormField extends CustomField { - private static final String FORM_FIELD_API_ID = "api_id"; - private static final String FORM_FIELD_NAME = "name"; - private static final String FORM_FIELD_TYPE = "type"; - private static final String FORM_FIELD_X = "x"; - private static final String FORM_FIELD_Y = "y"; - private static final String FORM_FIELD_WIDTH = "width"; - private static final String FORM_FIELD_HEIGHT = "height"; private static final String FORM_FIELD_SIGNER = "signer"; - private static final String FORM_FIELD_REQUIRED = "required"; private static final String FORM_FIELD_PAGE = "page"; private static final String FORM_FIELD_VALIDATION_TYPE = "validation_type"; @@ -55,60 +45,7 @@ public FormField() { } public FormField(JSONObject json) throws HelloSignException { - super(json, null); - } - - public String getApiId() { - return getString(FORM_FIELD_API_ID); - } - public void setApiId(String apiId) { - set(FORM_FIELD_API_ID, apiId); - } - - public String getName() { - return getString(FORM_FIELD_NAME); - } - public void setName(String name) { - set(FORM_FIELD_NAME, name); - } - public boolean hasName() { - return has(FORM_FIELD_NAME); - } - public FieldType getType() { - return FieldType.valueOf(getString(FORM_FIELD_TYPE)); - } - public void setType(FieldType type) { - set(FORM_FIELD_TYPE, type.toString()); - } - public String getTypeString() { - if (has(FORM_FIELD_TYPE)) { - return getType().toString(); - } - return null; - } - public Integer getX() { - return getInteger(FORM_FIELD_X); - } - public void setX(Integer x) { - set(FORM_FIELD_X, x); - } - public Integer getY() { - return getInteger(FORM_FIELD_Y); - } - public void setY(Integer y) { - set(FORM_FIELD_Y, y); - } - public Integer getWidth() { - return getInteger(FORM_FIELD_WIDTH); - } - public void setWidth(Integer width) { - set(FORM_FIELD_WIDTH, width); - } - public Integer getHeight() { - return getInteger(FORM_FIELD_HEIGHT); - } - public void setHeight(Integer height) { - set(FORM_FIELD_HEIGHT, height); + super(json); } public Integer getSigner() { return getInteger(FORM_FIELD_SIGNER); @@ -116,12 +53,6 @@ public Integer getSigner() { public void setSigner(Integer signer) { set(FORM_FIELD_SIGNER, signer); } - public Boolean getRequired() { - return getBoolean(FORM_FIELD_REQUIRED); - } - public void setRequired(Boolean required) { - set(FORM_FIELD_REQUIRED, required); - } public void setPage(Integer page) { set(FORM_FIELD_PAGE, page); } diff --git a/src/main/java/com/hellosign/sdk/resource/support/types/ApiAppOauthScopeType.java b/src/main/java/com/hellosign/sdk/resource/support/types/ApiAppOauthScopeType.java index f8e2c238..3fede54f 100644 --- a/src/main/java/com/hellosign/sdk/resource/support/types/ApiAppOauthScopeType.java +++ b/src/main/java/com/hellosign/sdk/resource/support/types/ApiAppOauthScopeType.java @@ -31,5 +31,10 @@ */ public enum ApiAppOauthScopeType { basic_account_info, - request_signature + request_signature, + access_reusable_forms, + manage_docs, + access_docs, + send_docs, + signatures } diff --git a/src/test/java/com/hellosign/sdk/AbstractHelloSignTest.java b/src/test/java/com/hellosign/sdk/AbstractHelloSignTest.java deleted file mode 100644 index b4a3ae22..00000000 --- a/src/test/java/com/hellosign/sdk/AbstractHelloSignTest.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.hellosign.sdk; - -/** - * The MIT License (MIT) - * - * Copyright (C) 2015 hellosign.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.Serializable; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.Scanner; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.hellosign.sdk.http.Authentication; - -/** - * Contains common code used by all tests. - * - * @author "Chris Paul (chris@hellosign.com)" - */ -public abstract class AbstractHelloSignTest { - - private static final Logger logger = LoggerFactory.getLogger(AbstractHelloSignTest.class); - - protected static String validApiKey; - protected static String validUserEmail; - protected static String validUserPass; - protected static String validUserEmail2; - protected static String teamName; - protected static String invalidUserEmail; - protected static String invalidUserPass; - protected static String templateId; - protected static String templateTitle; - protected static String clientId; - protected static String callbackUrl; - - protected static boolean online = false; - - protected static Authentication auth = new Authentication(); - - // Static block to populate test properties and set up the HTTPS client, if necessary. - // These can be used by all implementing test classes. - static { - Properties properties = new Properties(); - try { - properties.load(AbstractHelloSignTest.class.getResourceAsStream("/test.properties")); - } catch (IOException e) { - e.printStackTrace(); - } - - if (properties != null) { - validApiKey = properties.getProperty("valid.apiKey"); - validUserEmail = properties.getProperty("valid.email"); - validUserPass = properties.getProperty("valid.pass"); - validUserEmail2 = properties.getProperty("valid.email.2"); - teamName = properties.getProperty("team.name"); - invalidUserEmail = properties.getProperty("invalid.email"); - invalidUserPass = properties.getProperty("invalid.pass"); - templateTitle = properties.getProperty("template.title"); - templateId = properties.getProperty("template.id"); - clientId = properties.getProperty("client.id"); - callbackUrl = properties.getProperty("callback.url"); - - auth.setApiKey(validApiKey); - try { - auth.setWebsiteCredentials(validUserEmail, validUserPass); - } catch (HelloSignException e) { - e.printStackTrace(); - } - } - - // Force this to be run against the local test environment - System.setProperty("hellosign.base.url", "https://www.dev-hellosign.com/apiapp_dev.php"); - System.setProperty("hellosign.oauth.base.url", "https://www.dev-hellosign.com/webapp_dev.php/oauth/token"); - System.setProperty("hellosign.disable.ssl", "true"); - System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug"); - - online = false; - if (!validApiKey.isEmpty()) { - try { - HelloSignClient client = new HelloSignClient(validApiKey); - online = client.isOnline(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - public static boolean isHelloSignAvailable() { - return online; - } - - public static void printFields(Map fields) { - for (String key : fields.keySet()) { - logger.debug("\t" + key + "=" + fields.get(key)); - } - } - - /** - * Utility method to compare POST fields from a text file (loaded from getExpectedFields()) and - * the fields map generated by the HelloSign resource class. This ensures that we're getting the - * correct fields to submit to the server. If the actual value of a field is arbitrary (e.g., - * an ID field), then the expected field should have an asterisk (*) as its expected value. - * @param expectedFields Map - * @param actualFields Map - * @return true if all fields are equal, false otherwise - */ - public static boolean areFieldsEqual(Map expectedFields, Map actualFields) { - for (String key : expectedFields.keySet()) { - if (!actualFields.containsKey(key)) { - logger.error("Key '" + key + "' not found in actual fields."); - return false; - } - String expectedValue = (String) expectedFields.get(key); - Serializable actualValue = actualFields.get(key); - if ("*".equals(expectedValue)) { - continue; - } - if (actualValue instanceof File) { - continue; // Not sure we can test this unless we compare file names? - } - if (!actualValue.toString().equals(expectedValue.toString())) { - logger.error("Actual value '" + actualValue.toString() + "' does not equal expected value '" + expectedValue.toString() + "'"); - return false; - } - } - return true; - } - - /** - * Searches for the provided file in the directory: - * /src/test/resources/[TEST_CLASS_NAME] - * - * @param name String file name - * @return File - */ - protected File getTestFile(String name) { - String url = System.getProperty("file.separator") + this.getClass().getSimpleName() + - System.getProperty("file.separator") + name; - return new File(this.getClass().getResource(url).getFile()); - } - - /** - * Searches for the provided file in the directory and returns its contents as a String. - * /src/test/resources/[TEST_CLASS_NAME] - * - * @param name String file name - * @return String - */ - protected String getTestFileAsString(String name) throws FileNotFoundException { - Scanner s = new Scanner(getTestFile(name)); - s.useDelimiter("\\Z"); - String result = (s.hasNext() ? s.next() : ""); - s.close(); - return result; - } - - /** - * Searches for a test case file located at: - * /src/test/resources/[TEST_CLASS_NAME]/expectedFields.txt - * - * It then parses this into a Map of KVPs to use in analyzing the fields being - * returned by the HelloSign resource. - * - * @return Map (technically always Map, - * but let's be consistent) - */ - public Map getExpectedFields() { - Map fields = new HashMap(); - BufferedReader br = null; - try { - File expectedFields = getTestFile("expectedFields.txt"); - br = new BufferedReader(new FileReader(expectedFields)); - String line = null; - while ((line = br.readLine()) != null) { - String[] field = line.split("="); - if (field.length == 2) { - fields.put(field[0], field[1]); - } - } - } catch (Exception ex) { - try { - if (br != null) br.close(); - } catch (Exception e) {} - } - return fields; - } - - /** - * Searches for a test case file located at: - * /src/test/resources/[TEST_CLASS_NAME]/expectedResponse.txt - * - * It then parses this into a JSONObject for use in analyzing the response - * returned by an API call. - * - * @return JSONObject - */ - public JSONObject getExpectedJSONResponse() { - JSONObject json = null; - try { - String jsonStr = getTestFileAsString("expectedResponse.txt"); - json = new JSONObject(jsonStr); - } catch (Exception ex) { - ex.printStackTrace(); - } - return json; - } - - /** - * Utility method to compare 2 JSON objects for similar structure and content. - * @param json1 JSONObject - * @param json2 JSONObject - * @return true if the structure and content of the JSON objects is equal, false otherwise - */ - public static boolean areJSONObjectsEqual(JSONObject json1, JSONObject json2) { - return areJSONObjectsEqual(json1, json2, false) && areJSONObjectsEqual(json1, json2, false); - } - - /** - * Utility method to compare 2 JSON objects for similar structure and content. - * Ignores the content and focuses solely on the structure. - * @param json1 JSONObject - * @param json2 JSONObject - * @param ignoreData boolean - * @return true if the structure of the JSONObjects is equal, false otherwise - */ - public static boolean areJSONObjectsEqualIgnoreData(JSONObject json1, JSONObject json2) { - return areJSONObjectsEqual(json1, json2, true) && areJSONObjectsEqual(json1, json2, true); - } - - private static boolean areJSONObjectsEqual(JSONObject json1, JSONObject json2, boolean ignoreData) { - boolean equal = true; - try { - Iterator keys = json1.keys(); - while (keys.hasNext()) { - String key = (String) keys.next(); - if (json2.has(key)) { - if (ignoreData) { - equal &= true; - } else { - equal &= compareObjects(json1.get(key), json2.get(key)); - } - } - if (!equal) { - return false; - } - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - return true; - } - - private static boolean compareObjects(Object value1, Object value2) throws Exception { - if (!value1.getClass().equals(value2.getClass())) { - return false; - } - if (value1 instanceof JSONObject) { - return areJSONObjectsEqual((JSONObject) value1, (JSONObject) value2, false); - } else if (value1 instanceof JSONArray) { - if (((JSONArray) value1).length() != ((JSONArray) value2).length()) { - return false; - } - // Assumes array order matters - boolean arraysEqual = true; - for (int i = 0; i < ((JSONArray) value1).length(); i++) { - Object v1 = ((JSONArray) value1).get(i); - Object v2 = ((JSONArray) value2).get(i); - arraysEqual &= compareObjects(v1, v2); - } - return arraysEqual; - } else if (value1 instanceof String) { - return value1.equals(value2); - } - // else assume they are primitives - return value1 == value2; - } -} diff --git a/src/test/java/com/hellosign/sdk/HelloSignClientTest.java b/src/test/java/com/hellosign/sdk/HelloSignClientTest.java index a86e18fc..ea3c2aed 100644 --- a/src/test/java/com/hellosign/sdk/HelloSignClientTest.java +++ b/src/test/java/com/hellosign/sdk/HelloSignClientTest.java @@ -1,5 +1,50 @@ package com.hellosign.sdk; +import static org.junit.Assert.*; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.ArgumentMatchers.*; + +import java.io.File; +import java.io.FileNotFoundException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; +import java.util.regex.Pattern; + +import org.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TestName; + +import com.hellosign.sdk.http.HttpClient; +import com.hellosign.sdk.resource.AbstractRequest; +import com.hellosign.sdk.resource.Account; +import com.hellosign.sdk.resource.ApiApp; +import com.hellosign.sdk.resource.EmbeddedRequest; +import com.hellosign.sdk.resource.EmbeddedResponse; +import com.hellosign.sdk.resource.SignatureRequest; +import com.hellosign.sdk.resource.Team; +import com.hellosign.sdk.resource.Template; +import com.hellosign.sdk.resource.TemplateDraft; +import com.hellosign.sdk.resource.TemplateSignatureRequest; +import com.hellosign.sdk.resource.UnclaimedDraft; +import com.hellosign.sdk.resource.support.ApiAppList; +import com.hellosign.sdk.resource.support.CustomField; +import com.hellosign.sdk.resource.support.Document; +import com.hellosign.sdk.resource.support.FormField; +import com.hellosign.sdk.resource.support.OauthData; +import com.hellosign.sdk.resource.support.Signature; +import com.hellosign.sdk.resource.support.SignatureRequestList; +import com.hellosign.sdk.resource.support.TemplateList; +import com.hellosign.sdk.resource.support.TemplateRole; +import com.hellosign.sdk.resource.support.WhiteLabelingOptions; +import com.hellosign.sdk.resource.support.types.FieldType; +import com.hellosign.sdk.resource.support.types.UnclaimedDraftType; + /** * The MIT License (MIT) * @@ -12,8 +57,8 @@ * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, @@ -24,38 +69,750 @@ * SOFTWARE. */ -import static org.junit.Assert.*; +public class HelloSignClientTest { -import org.junit.Test; + // TODO: Make convenience method to mock response code -import com.hellosign.sdk.HelloSignClient; -import com.hellosign.sdk.resource.Account; + @Rule + public TestName name = new TestName(); + + private HttpClient spy; + private HelloSignClient client; + + @Before + public void setup() throws Exception { + spy = spy(new HttpClient()); + client = new HelloSignClient("testapikey"); + client.setHttpClient(spy); + + // Don't actually make HTTP requests + doReturn(spy).when(spy).post(any(String.class)); + doReturn(spy).when(spy).get(any(String.class)); + doReturn(spy).when(spy).put(any(String.class)); + doReturn(spy).when(spy).delete(any(String.class)); + doReturn(spy).when(spy).options(any(String.class)); + + // Return the test case's JSON response instead + // TODO: Add instructions for autogeneration + doReturn(getTestFileAsString(name.getMethodName() + ".json")).when(spy).getLastResponse(); + } + + protected String getTestFileAsString(String name) throws FileNotFoundException { + String result = null; + String url = System.getProperty("file.separator") + this.getClass().getSimpleName() + + System.getProperty("file.separator") + name; + URL resource = this.getClass().getResource(url); + if (resource != null) { + Scanner s = new Scanner(new File(resource.getFile())); + s.useDelimiter("\\Z"); + result = (s.hasNext() ? s.next() : ""); + s.close(); + } + return result; + } + + @After + public void tearDown() { + spy = null; + client = null; + } + + @Test + public void testCreateAccount() throws Exception { + String email = "newuser@hellosign.com"; + Account account = client.createAccount(email); + assertNotNull(account); + assertTrue(email.equals(account.getEmail())); + } + + @Test(expected = HelloSignException.class) + public void testCreateAccountExisting() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + client.createAccount("chris@hellosign.com"); + } + + @Test + public void testCreateAccountWithOAuthData() throws Exception { + String email = "newuser1@hellosign.com"; + Account account = client.createAccount(email); + assertNotNull(account); + assertTrue(email.equals(account.getEmail())); + OauthData data = account.getOauthData(); + assertNotNull(data); + assertNotNull(data.getAccessToken()); + assertTrue(!data.getAccessToken().isEmpty()); + assertNotNull(data.getTokenType()); + assertTrue(!data.getTokenType().isEmpty()); + assertNotNull(data.getRefreshToken()); + assertTrue(!data.getRefreshToken().isEmpty()); + assertTrue(data.getExpiresIn() > 0); + } + + @Test + public void testGetOauthData() throws Exception { + String code = "testcode"; + String clientId = "testclientid"; + String secret = "testsecret"; + String state = "teststate"; + OauthData data = client.getOauthData(code, clientId, secret, state, false); + assertNotNull(data); + assertNotNull(data.getAccessToken()); + assertTrue(!data.getAccessToken().isEmpty()); + assertNotNull(data.getExpiresIn()); + assertTrue(data.getExpiresIn() > 0); + assertNotNull(data.getRefreshToken()); + assertTrue(!data.getRefreshToken().isEmpty()); + assertNotNull(data.getTokenType()); + assertTrue(!data.getTokenType().isEmpty()); + + // Confirm that NOT auto-saving the access token works + assertTrue(client.getAuth().getAccessToken().isEmpty()); + assertTrue(client.getAuth().getAccessTokenType().isEmpty()); + + // Confirm that auto-saving the access token works + client.getOauthData(code, clientId, secret, state, true); + assertTrue(!client.getAuth().getAccessToken().isEmpty()); + assertTrue(!client.getAuth().getAccessTokenType().isEmpty()); + } + + @Test + public void testGetAccount() throws Exception { + Account account = client.getAccount(); + assertNotNull(account); + assertNotNull(account.getId()); + assertTrue(Pattern.matches("\\A.*@hellosign.com\\z", account.getEmail())); + assertNull(account.getCallbackUrl()); // not set + assertNull(account.getOauthData()); // not set + assertNotNull(account.getQuotas()); + assertNotNull(account.getApiSignatureRequestsLeft()); + assertNull(account.getDocumentsLeft()); // null = unlimited + assertNotNull(account.getTemplatesLeft()); + assertNotNull(account.getRoleCode()); + } + + @Test + public void testIsAccountValid() throws Exception { + assertTrue(client.isAccountValid("chris@hellosign.com")); + } + + @Test + public void testIsAccountInvalid() throws Exception { + assertFalse(client.isAccountValid("zztop@hellosign.com")); + } + + @Test + public void testSetAccountCallback() throws Exception { + String callbackUrl = "https://www.example.com"; + Account account = client.setCallback(callbackUrl); + assertNotNull(account); + assertTrue(callbackUrl.equals(account.getCallbackUrl())); + } + + @Test(expected = HelloSignException.class) + public void testSetAccountCallbackInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + String callbackUrl = "foo"; + client.setCallback(callbackUrl); + } + + @Test + public void testGetTeam() throws Exception { + Team team = client.getTeam(); + assertNotNull(team); + } + + @Test(expected = HelloSignException.class) + public void testGetTeamInvalid() throws Exception { + doReturn(404).when(spy).getLastResponseCode(); + client.getTeam(); + } + + @Test + public void testCreateTeam() throws Exception { + String teamName = "Team Echevaria"; + Team newTeam = client.createTeam(teamName); + assertNotNull(newTeam); + assertTrue(teamName.equals(newTeam.getName())); + } + + @Test(expected = HelloSignException.class) + public void testCreateTeamInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + client.createTeam("foo"); + } + + @Test + public void testInviteTeamMember() throws Exception { + String email = "chris+2@hellosign.com"; + Team team = client.inviteTeamMember(email); + boolean emailFound = false; + for (Account a : team.getInvitedAccounts()) { + if (email.equals(a.getEmail())) { + emailFound = true; + break; + } + } + assertTrue(emailFound); + } + + @Test(expected = HelloSignException.class) + public void testInviteTeamMemberInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + client.inviteTeamMember("foo"); + } + + @Test + public void testRemoveTeamMember() throws Exception { + String email = "chris+1@hellosign.com"; + Team team = client.removeTeamMember(email); + for (Account a : team.getAccounts()) { + assertFalse(email.equals(a.getEmail())); + } + } + + @Test(expected = HelloSignException.class) + public void testRemoveTeamMemberInvalid() throws Exception { + doReturn(404).when(spy).getLastResponseCode(); + client.removeTeamMember("foo"); + } + + @Test + public void testUpdateTeamName() throws Exception { + String name = "Team America"; + Team team = client.updateTeamName(name); + assertNotNull(team); + assertTrue(name.equals(team.getName())); + } + + @Test(expected = HelloSignException.class) + public void testUpdateTeamNameInvalid() throws Exception { + doReturn(404).when(spy).getLastResponseCode(); + client.updateTeamName("foo"); + } + + @Test + public void testDestroyTeam() throws Exception { + doReturn(200).when(spy).getLastResponseCode(); + client.destroyTeam(); + } + + @Test(expected = HelloSignException.class) + public void testDestroyTeamInvalid() throws Exception { + doReturn(404).when(spy).getLastResponseCode(); + client.destroyTeam(); + } + + @Test + public void testGetSignatureRequest() throws Exception { + String id = "5fd97d3b6a2ac509b7837891d8c804e29cc35636"; + SignatureRequest request = client.getSignatureRequest(id); + assertNotNull(request); + assertTrue(id.equals(request.getId())); + } + + @Test(expected = HelloSignException.class) + public void testGetSignatureRequestInvalid() throws Exception { + doReturn(404).when(spy).getLastResponseCode(); + client.getSignatureRequest("foo"); + } + + @Test + public void testGetSignatureRequests() throws Exception { + SignatureRequestList list = client.getSignatureRequests(); + for (SignatureRequest s : list) { + assertNotNull(s); + assertNotNull(s.getId()); + } + } + + @Test(expected = HelloSignException.class) + public void testGetSignatureRequestsInvalid() throws Exception { + doReturn(401).when(spy).getLastResponseCode(); + client.getSignatureRequests(); + } + + @Test + public void testGetSignatureRequestsPage() throws Exception { + SignatureRequestList list = client.getSignatureRequests(1); + for (SignatureRequest s : list) { + assertNotNull(s); + assertNotNull(s.getId()); + } + } + + @Test + public void testGetSignatureRequestsPageInvalid() throws Exception { + SignatureRequestList list = client.getSignatureRequests(19); + assertFalse(list.iterator().hasNext()); + } + + @Test + public void testSendSignatureRequest() throws Exception { + String subject = "From the Mare"; + String message = "Pls sign"; + SignatureRequest req = new SignatureRequest(); + req.setTestMode(true); + req.addSigner("charlie@hotmail.com", "Charlie Day"); + req.addFileUrl("http://www.orimi.com/pdf-test.pdf"); + req.setSubject(subject); + req.setMessage(message); + SignatureRequest sentReq = client.sendSignatureRequest(req); + assertNotNull(sentReq); + assertTrue(sentReq.hasId()); + assertNotNull(sentReq.getSignature("charlie@hotmail.com", "Charlie Day")); + assertTrue(subject.equals(sentReq.getSubject())); + assertTrue(message.equals(sentReq.getMessage())); + assertTrue(req.isTestMode()); + } + + @Test(expected = HelloSignException.class) + public void testSendSignatureRequestInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + SignatureRequest req = new SignatureRequest(); + req.setTestMode(true); + client.sendSignatureRequest(req); + } + + @Test + public void testUpdateSignatureRequest() throws Exception { + String id = "5fd97d3b6a2ac509b7837891d8c804e29cc35636"; + String signatureId = "c390fac7bb23c2b48e6314272ec9db17"; + String newEmailAddress = "barack@obama.com"; + SignatureRequest updatedReq = client.updateSignatureRequest(id, signatureId, newEmailAddress); + assertNotNull(updatedReq); + assertTrue(id.equals(updatedReq.getId())); + Signature sig = updatedReq.getSignature(newEmailAddress, "Barack"); + assertNotNull(sig); + assertTrue(signatureId.equals(sig.getId())); + } + + @Test(expected = HelloSignException.class) + public void testUpdateSignatureRequestInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + String id = "84f8767b525611511ed24e5eaacee537589a30be"; + String signatureId = "e477e554af09555eea762d1c204d9f3d"; + String newEmailAddress = "nightman@hotmail.com"; + client.updateSignatureRequest(id, signatureId, newEmailAddress); + } + + @Test + public void testGetTemplates() throws Exception { + TemplateList templates = client.getTemplates(); + assertNotNull(templates); + for (Template t : templates) { + assertNotNull(t); + assertTrue(t.hasId()); + } + } + + @Test(expected = HelloSignException.class) + public void testGetTemplatesInvalid() throws Exception { + doReturn(401).when(spy).getLastResponseCode(); + client.getTemplates(); + } + + @Test + public void testGetTemplatesPage() throws Exception { + TemplateList templates = client.getTemplates(1); + assertNotNull(templates); + for (Template t : templates) { + assertNotNull(t); + assertTrue(t.hasId()); + } + } + + @Test + public void testGetTemplatesPageInvalid() throws Exception { + TemplateList templates = client.getTemplates(10); + assertNotNull(templates); + assertFalse(templates.iterator().hasNext()); + } + + @Test + public void testGetTemplateFile() throws Exception { + // Mock a random byte size written + doReturn((long) 100000).when(spy).getLastResponseAsFile(any(File.class)); + File f = client.getTemplateFile("templateid"); + assertNotNull(f); + assertTrue(f.exists()); + assertTrue(f.delete()); + } + + @Test(expected = HelloSignException.class) + public void testGetTemplateFileInvalid() throws Exception { + doReturn(404).when(spy).getLastResponseCode(); + client.getTemplateFile("foo"); + } + + @Test + public void testGetTemplate() throws Exception { + String templateId = "475c0a43282985bb0fc02c995bfce6df2840a6f5"; + Template template = client.getTemplate(templateId); + assertNotNull(template); + assertTrue(templateId.equals(template.getId())); + for (TemplateRole s : template.getSignerRoles()) { + assertNotNull(s.getRole()); + } + for (Document d : template.getDocuments()) { + assertNotNull(d.getName()); + for (CustomField cf : d.getCustomFields()) { + assertNotNull(cf.getApiId()); + assertNotNull(cf.getName()); + assertNotNull(cf.getType()); + assertNotNull(cf.getX()); + assertNotNull(cf.getY()); + assertNotNull(cf.getWidth()); + assertNotNull(cf.getHeight()); + assertNotNull(cf.isRequired()); + if (cf.getType().equals(FieldType.text)) { + assertNotNull(cf.getEstimatedTextLines()); + assertNotNull(cf.getEstimatedCharsPerLine()); + } + } + for (FormField ff : d.getFormFields()) { + assertNotNull(ff.getApiId()); + assertNotNull(ff.getName()); + assertNotNull(ff.getType()); + assertNotNull(ff.getX()); + assertNotNull(ff.getY()); + assertNotNull(ff.getWidth()); + assertNotNull(ff.getHeight()); + assertNotNull(ff.isRequired()); + assertNotNull(ff.getSigner()); + if (ff.getType().equals(FieldType.text)) { + assertNotNull(ff.getEstimatedTextLines()); + assertNotNull(ff.getEstimatedCharsPerLine()); + } + } + for (Account a : template.getAccounts()) { + assertNotNull(a); + } + } + + } + + @Test(expected = HelloSignException.class) + public void testGetTemplateInvalid() throws Exception { + doReturn(404).when(spy).getLastResponseCode(); + client.getTemplateFile("foo"); + } + + @Test + public void testAddTemplateUser() throws Exception { + String templateId = "475c0a43282985bb0fc02c995bfce6df2840a6f5"; + String email = "chris+1@hellosign.com"; + Template template = client.addTemplateUser(templateId, email); + boolean found = false; + for (Account a : template.getAccounts()) { + if (email.equals(a.getEmail())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test(expected = HelloSignException.class) + public void testAddTemplateUserInvalid() throws Exception { + doReturn(403).when(spy).getLastResponseCode(); + client.addTemplateUser("foo", "bar"); + } + + @Test + public void testDeleteTemplate() throws Exception { + doReturn(200).when(spy).getLastResponseCode(); + client.deleteTemplate("foo"); + } + + @Test(expected = HelloSignException.class) + public void testDeleteTemplateInvalid() throws Exception { + doReturn(401).when(spy).getLastResponseCode(); + client.deleteTemplate("foo"); + } + + @Test + public void testRemoveTemplateUser() throws Exception { + String templateId = "475c0a43282985bb0fc02c995bfce6df2840a6f5"; + String email = "chris+1@hellosign.com"; + Template template = client.removeTemplateUser(templateId, email); + assertNotNull(template); + boolean found = false; + for (Account a : template.getAccounts()) { + if (email.equals(a.getEmail())) { + found = true; + } + } + assertFalse(found); + } + + @Test(expected = HelloSignException.class) + public void testRemoveTemplateUserInvalid() throws Exception { + doReturn(403).when(spy).getLastResponseCode(); + String templateId = "475c0a43282985bb0fc02c995bfce6df2840a6f5"; + String email = "chris@hellosign.com"; + client.removeTemplateUser(templateId, email); + } + + @Test + public void testSendTemplateSignatureRequest() throws Exception { + String templateId = "9cc3d5819959419abee4dbff2073d497e7c0a962"; + String title = "Java SDK request"; + String message = "Pls to be signing kthx"; + TemplateSignatureRequest req = new TemplateSignatureRequest(); + req.setTemplateId(templateId); + req.setTitle(title); + req.setMessage(message); + req.setSigner("Tester A", "chris+a@hellosign.com", "Chris A"); + req.setSigner("Tester B", "chris+b@hellosign.com", "Chris B"); + Map fields = new HashMap(); + fields.put("Field A", "Hello"); + fields.put("Field B", "World!"); + fields.put("Checkbox A", "true"); + fields.put("Checkbox B", "false"); + req.setCustomFields(fields); + SignatureRequest sentReq = client.sendTemplateSignatureRequest(req); + assertNotNull(sentReq); + assertTrue(title.equals(sentReq.getTitle())); + assertTrue(message.equals(sentReq.getMessage())); + for (CustomField cf : sentReq.getCustomFields()) { + assertTrue(fields.get(cf.getName()).equals(cf.getValue())); + } + } + + @Test(expected = HelloSignException.class) + public void testSendTemplateSignatureRequestInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + SignatureRequest req = new SignatureRequest(); + req.addFileUrl("http://www.example.com"); + client.sendSignatureRequest(req); + } + + @Test + public void testCancelSignatureRequest() throws Exception { + doReturn(200).when(spy).getLastResponseCode(); + assertTrue(client.cancelSignatureRequest("9cc3d5819959419abee4dbff2073d497e7c0a962")); + } + + @Test(expected = HelloSignException.class) + public void testCancelSignatureRequestInvalid() throws Exception { + doReturn(410).when(spy).getLastResponseCode(); + client.cancelSignatureRequest("foo"); + } + + @Test + public void testRequestEmailReminder() throws Exception { + String id = "89d1f4f831ff1bbaf707c398881d98bff447c64e"; + SignatureRequest req = client.requestEmailReminder(id, "chris+a@hellosign.com"); + assertNotNull(req); + assertTrue(id.equals(req.getId())); + } + + @Test(expected = HelloSignException.class) + public void testRequestEmailReminderInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + String id = "89d1f4f831ff1bbaf707c398881d98bff447c64e"; + client.requestEmailReminder(id, "chris+a@hellosign.comd"); + } + + @Test + public void testGetFiles() throws Exception { + // Mock a random byte size written + doReturn((long) 100000).when(spy).getLastResponseAsFile(any(File.class)); + File f = client.getFiles("id"); + // This really just makes sure a temp file is created + // the content isn't actually written, since we'd have to + // mock the response stream + assertNotNull(f); + assertTrue(f.exists()); + assertTrue(f.delete()); + } + + @Test(expected = HelloSignException.class) + public void testGetFilesInvalid() throws Exception { + doReturn(404).when(spy).getLastResponseCode(); + client.getFiles("foo"); + } + + @Test + public void testCreateApiApp() throws Exception { + ApiApp app = new ApiApp(); + app.setName("Java API App"); + app.setDomain("example.com"); + app.setCallbackUrl("http://www.example.com"); + ApiApp createdApp = client.createApiApp(app); + assertNotNull(createdApp); + assertNotNull(createdApp.getClientId()); + assertTrue(app.getName().equals(createdApp.getName())); + assertTrue(app.getDomain().equals(createdApp.getDomain())); + assertTrue(app.getCallbackUrl().equals(createdApp.getCallbackUrl())); + } + + @Test(expected = HelloSignException.class) + public void testCreateApiAppInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + ApiApp app = new ApiApp(); + app.setName("Java API App"); + client.createApiApp(app); + } + + @Test + public void testGetApiApp() throws Exception { + ApiApp app = client.getApiApp("034fb51064187cf28e4aad1c2533ad8f"); + assertNotNull(app); + } + + @Test(expected = HelloSignException.class) + public void testGetApiAppInvalid() throws Exception { + doReturn(401).when(spy).getLastResponseCode(); + client.getApiApp("034fb51064187cf28e4aad1c2533ad8f"); + } + + @Test + public void testGetApiApps() throws Exception { + ApiAppList appList = client.getApiApps(); + assertNotNull(appList); + assertNotNull(appList.getNumPages()); + assertTrue(appList.getNumPages() > 0); + assertNotNull(appList.getNumResults()); + assertTrue(appList.getNumResults() > 0); + assertNotNull(appList.getPageSize()); + assertTrue(appList.getPageSize() > 0); + for (ApiApp app : appList) { + assertNotNull(app); + assertNotNull(app.getClientId()); + } + } + + @Test(expected = HelloSignException.class) + public void testGetApiAppsInvalid() throws Exception { + doReturn(401).when(spy).getLastResponseCode(); + client.getApiApps(); + } + + @Test + public void testCreateEmbeddedRequest() throws Exception { + SignatureRequest req = new SignatureRequest(); + req.addFileUrl("http://www.orimi.com/pdf-test.pdf"); + req.addSigner("chris@hellosign.com", "Chris"); + req.setTestMode(true); + req.addMetadata("test_key", "test_value"); + EmbeddedRequest embeddedReq = new EmbeddedRequest("034fb51064187cf28e4aad1c2533ad8f", req); + AbstractRequest newReq = client.createEmbeddedRequest(embeddedReq); + assertNotNull(newReq); + assertNotNull(newReq.getId()); + assertTrue(req.getMetadata("test_key").equals(newReq.getMetadata("test_key"))); + } + + @Test(expected = HelloSignException.class) + public void testCreateEmbeddedRequestInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + EmbeddedRequest embeddedReq = new EmbeddedRequest("clientId", new SignatureRequest()); + client.createEmbeddedRequest(embeddedReq); + } + + @Test + public void testGetEmbeddedSignUrl() throws Exception { + EmbeddedResponse s = client.getEmbeddedSignUrl("37b35bb8b53e3ed26658c1b64c2ffa08"); + assertNotNull(s); + assertNotNull(s.getSignUrl()); + assertNotNull(s.getExpiresAt()); + } + + @Test(expected = HelloSignException.class) + public void testGetEmbeddedSignUrlInvalid() throws Exception { + doReturn(404).when(spy).getLastResponseCode(); + client.getEmbeddedSignUrl("foo"); + } + + @Test + public void testCreateUnclaimedDraft() throws Exception { + UnclaimedDraft draft = new UnclaimedDraft(); + draft.addFileUrl("http://www.orimi.com/pdf-test.pdf"); + draft.setType(UnclaimedDraftType.request_signature); + draft.setSubject("Java is hot hot hot"); + draft.setMessage("Best served at 180 degrees"); + UnclaimedDraft response = client.createUnclaimedDraft(draft); + assertNotNull(response); + assertNotNull(response.getClaimUrl()); + assertFalse(response.isTestMode()); + assertNotNull(response.getExpiresAt()); + assertNotNull(response.getSignatureRequestId()); + } + + @Test(expected = HelloSignException.class) + public void testCreateUnclaimedDraftInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + client.createUnclaimedDraft(new UnclaimedDraft()); + } + + @Test + public void testCreateEmbeddedTemplateDraft() throws Exception { + TemplateDraft draft = new TemplateDraft(); + draft.setClientId("034fb51064187cf28e4aad1c2533ad8f"); + draft.addFileUrl("http://www.orimi.com/pdf-test.pdf"); + draft.addSignerRole("Role A", 1); + draft.addSignerRole("Role B", 2); + draft.addCCRole("Lawyer"); + draft.addCCRole("Manager"); + draft.addMergeField("Full Name", FieldType.text); + draft.addMergeField("Is registered?", FieldType.checkbox); + draft.addMetadata("test_key", "test_value"); + EmbeddedRequest embeddedReq = new EmbeddedRequest("034fb51064187cf28e4aad1c2533ad8f", draft); + TemplateDraft response = client.createEmbeddedTemplateDraft(embeddedReq); + assertNotNull(response); + assertNotNull(response.getId()); + assertNotNull(response.getEditUrl()); + assertNotNull(response.getExpiresAt()); + } + + @Test(expected = HelloSignException.class) + public void testCreateEmbeddedTemplateDraftInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + client.createEmbeddedTemplateDraft(new EmbeddedRequest("foo", new TemplateDraft())); + } + + @Test + public void testGetEmbeddedTemplateEditUrl() throws Exception { + EmbeddedResponse response = client.getEmbeddedTemplateEditUrl("foo"); + assertNotNull(response); + assertNotNull(response.getEditUrl()); + assertNotNull(response.getExpiresAt()); + } + + @Test(expected = HelloSignException.class) + public void testGetEmbeddedTemplateEditUrlInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + client.getEmbeddedTemplateEditUrl("foo"); + } + + @Test + public void testUpdateApiApp() throws Exception { + // Usually, you'd retrieve this from the client first, update, and then send + JSONObject obj = new JSONObject(getTestFileAsString("testGetApiApp.json")); + ApiApp app = new ApiApp(obj); + WhiteLabelingOptions options = new WhiteLabelingOptions(); + options.setPrimaryButtonColor("#FF0000"); + app.setWhiteLabelingOptions(options); + ApiApp updatedApp = client.updateApiApp(app); + assertNotNull(updatedApp); + assertTrue(app.getWhiteLabelingOptions().getPrimaryButtonColor().equalsIgnoreCase(updatedApp.getWhiteLabelingOptions().getPrimaryButtonColor())); + } + + @Test(expected = HelloSignException.class) + public void testUpdateApiAppInvalid() throws Exception { + doReturn(400).when(spy).getLastResponseCode(); + client.updateApiApp(new ApiApp()); + } + + @Test + public void testDeleteApiApp() throws Exception { + doReturn(204).when(spy).getLastResponseCode(); + assertTrue(client.deleteApiApp("034fb51064187cf28e4aad1c2533ad8f")); + } -public class HelloSignClientTest extends AbstractHelloSignTest { - - @Test - public void testAuthWithValidCredentials() { - Account account = null; - try { - HelloSignClient client = new HelloSignClient(validApiKey); - account = client.getAccount(); - } catch (HelloSignException ex) { - ex.printStackTrace(); - fail("Unexpected exception encountered!"); - } - assertNotNull(account); - } - - @Test - public void testAuthWithInvalidCredentials() { - Account account = null; - try { - HelloSignClient client = new HelloSignClient(invalidUserEmail, invalidUserPass); - account = client.getAccount(); - } catch (HelloSignException ex) { - assertNotNull("Expected exception encountered.", ex); - } - assertNull("No account was returned", account); - } - -} + @Test(expected = HelloSignException.class) + public void testDeleteApiAppInvalid() throws Exception { + doReturn(404).when(spy).getLastResponseCode(); + assertFalse(client.deleteApiApp("foo")); + } +} \ No newline at end of file diff --git a/src/test/java/com/hellosign/sdk/resource/AccountTest.java b/src/test/java/com/hellosign/sdk/resource/AccountTest.java deleted file mode 100644 index 457bac0c..00000000 --- a/src/test/java/com/hellosign/sdk/resource/AccountTest.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.hellosign.sdk.resource; - -/** - * The MIT License (MIT) - * - * Copyright (C) 2015 hellosign.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -import static org.junit.Assert.*; - -import org.json.JSONObject; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.hellosign.sdk.AbstractHelloSignTest; -import com.hellosign.sdk.HelloSignClient; -import com.hellosign.sdk.HelloSignException; -import com.hellosign.sdk.resource.Account; - -/** - * Simple test for the Account resource class. - * - * @author "Chris Paul (chris@hellosign.com)" - */ -public class AccountTest extends AbstractHelloSignTest { - - private static final Logger logger = LoggerFactory.getLogger(AccountTest.class); - - @Test - public void testAccountWithValidJSON() throws Exception { - JSONObject account = new JSONObject(getTestFileAsString("validAccount.txt")); - Account u = new Account(account); - assertNotNull(u); - } - - @Test - public void testCreateAccount() throws HelloSignException { - // We only want to test account creation against a local test environment - if (isHelloSignAvailable()) { - String testEmail = "test-" + System.currentTimeMillis() + "@test.com"; - HelloSignClient client = new HelloSignClient(validApiKey); - try { - Account account = client.createAccount(testEmail); - assertNotNull(account); - assertTrue(account.hasId()); - } catch (HelloSignException ex) { - fail(ex.getMessage()); - } - } - } - - @Test - public void testUpdateAccount() throws HelloSignException { - if (!isHelloSignAvailable()) { - logger.debug("No API access, skipping tests..."); - return; - } - HelloSignClient client = new HelloSignClient(validApiKey); -// Account currentAccount = client.getAccount(); -// String origCallback = (currentAccount.hasCallbackUrl() ? currentAccount.getCallbackUrl() : ""); - - Account account = client.setCallback(callbackUrl); - assertNotNull(account); - assertTrue(account.hasId()); - assertEquals(callbackUrl, account.getCallbackUrl()); - -// account = client.setCallback(origCallback); -// assertNotNull(account); -// assertTrue(account.hasId()); -// assertEquals("Callback URL was reset", origCallback, account.getCallbackUrl()); - } -} diff --git a/src/test/java/com/hellosign/sdk/resource/ApiAppTest.java b/src/test/java/com/hellosign/sdk/resource/ApiAppTest.java deleted file mode 100644 index b90b395a..00000000 --- a/src/test/java/com/hellosign/sdk/resource/ApiAppTest.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.hellosign.sdk.resource; - -/** - * The MIT License (MIT) - * - * Copyright (C) 2015 hellosign.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -import static org.junit.Assert.*; - -import java.text.DateFormat; -import java.util.Set; - -import org.json.JSONObject; -import org.junit.Test; - -import com.hellosign.sdk.AbstractHelloSignTest; -import com.hellosign.sdk.resource.support.ApiAppOauth; -import com.hellosign.sdk.resource.support.WhiteLabelingOptions; -import com.hellosign.sdk.resource.support.types.ApiAppOauthScopeType; - -/** - * Simple test for the ApiApp resource class. - * - * @author "Chris Paul (chris@hellosign.com)" - */ -public class ApiAppTest extends AbstractHelloSignTest { - - @Test - public void testDefaultApiApp() throws Exception { - ApiApp app = new ApiApp(); - assertNull(app.getCallbackUrl()); - } - - @Test - public void testApiAppWithValidJSON() throws Exception { - JSONObject apiapp = new JSONObject(getTestFileAsString("validApiApp.txt")); - ApiApp app = new ApiApp(apiapp); - assertNotNull(app); - assertEquals(app.getCallbackUrl(), "http://example.com/hello"); - assertEquals(app.getClientId(), "0dd3b823a682527788c4e40cb7b6f7e9"); - DateFormat format = DateFormat.getDateInstance(); - assertEquals(format.format(app.getCreatedAt()), "06-Jul-2015"); - assertEquals(app.getDomain(), "example.com"); - assertEquals(app.isApproved(), true); - assertEquals(app.getName(), "My Production App"); - ApiAppOauth oauth = app.getOauthInfo(); - assertEquals(oauth.getCallbackUrl(), "http://example.com/oauth"); - Set scopes = oauth.getScopes(); - assertTrue(scopes.contains(ApiAppOauthScopeType.basic_account_info)); - assertTrue(scopes.contains(ApiAppOauthScopeType.request_signature)); - assertEquals(oauth.getSecret(), "98891a1b59f312d04cd88e4e0c498d75"); - Account owner = app.getOwnerAccount(); - assertEquals(owner.getId(), "dc5deeb9e10b044c591ef2475aafad1d1d3bd888"); - assertEquals(owner.getEmail(), "john@example.com"); - } - - private String getShiftedColor(String color) { - int c = Integer.parseInt(color.substring(1), 16); - if (c - 20 >= 0) { - c -= 20; - } else { - c += 20; - } - String str = String.format("%06x", c); - return "#" + str; - } - - @Test - public void testApiAppWithWhiteLabelingOptions() throws Exception { - JSONObject apiapp = new JSONObject(getTestFileAsString("apiAppWithWhiteLabeling.txt")); - ApiApp app = new ApiApp(apiapp); - assertNotNull(app); - WhiteLabelingOptions oldOptions = app.getWhiteLabelingOptions(); - - String shiftedColor = getShiftedColor(oldOptions.getHeaderBackgroundColor()); - app.setHeaderBackgroundColor(shiftedColor); - assertEquals(app.getHeaderBackgroundColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getPageBackgroundColor()); - app.setPageBackgroundColor(shiftedColor); - assertEquals(app.getPageBackgroundColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getLinkColor()); - app.setLinkColor(shiftedColor); - assertEquals(app.getLinkColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getPrimaryButtonColor()); - app.setPrimaryButtonColor(shiftedColor); - assertEquals(app.getPrimaryButtonColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getPrimaryButtonHoverColor()); - app.setPrimaryButtonHoverColor(shiftedColor); - assertEquals(app.getPrimaryButtonHoverColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getPrimaryButtonTextColor()); - app.setPrimaryButtonTextColor(shiftedColor); - assertEquals(app.getPrimaryButtonTextColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getPrimaryButtonTextHoverColor()); - app.setPrimaryButtonTextHoverColor(shiftedColor); - assertEquals(app.getPrimaryButtonTextHoverColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getSecondaryButtonColor()); - app.setSecondaryButtonColor(shiftedColor); - assertEquals(app.getSecondaryButtonColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getSecondaryButtonHoverColor()); - app.setSecondaryButtonHoverColor(shiftedColor); - assertEquals(app.getSecondaryButtonHoverColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getSecondaryButtonTextColor()); - app.setSecondaryButtonTextColor(shiftedColor); - assertEquals(app.getSecondaryButtonTextColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getSecondaryButtonTextHoverColor()); - app.setSecondaryButtonTextHoverColor(shiftedColor); - assertEquals(app.getSecondaryButtonTextHoverColor(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getTextColor1()); - app.setTextColor1(shiftedColor); - assertEquals(app.getTextColor1(), shiftedColor); - - shiftedColor = getShiftedColor(oldOptions.getTextColor2()); - app.setTextColor2(shiftedColor); - assertEquals(app.getTextColor2(), shiftedColor); - } - - @Test - public void testApiAppPostFields() throws Exception { - ApiApp app = new ApiApp(); - app.setName("My Production App"); - app.setDomain("example.com"); - app.setCallbackUrl("https://example.com/hello"); - app.setOAuthCallbackUrl("https://example.com/oauth"); - app.addScope(ApiAppOauthScopeType.basic_account_info); - app.addScope(ApiAppOauthScopeType.request_signature); - app.setHeaderBackgroundColor("#FFFFFF"); - app.setPageBackgroundColor("#FFFFFF"); - app.setLinkColor("#FFFFFF"); - app.setPrimaryButtonColor("#FFFFFF"); - app.setPrimaryButtonHoverColor("#FFFFFF"); - app.setPrimaryButtonTextColor("#FFFFFF"); - app.setPrimaryButtonTextHoverColor("#FFFFFF"); - app.setSecondaryButtonColor("#FFFFFF"); - app.setSecondaryButtonHoverColor("#FFFFFF"); - app.setSecondaryButtonTextColor("#FFFFFF"); - app.setSecondaryButtonTextHoverColor("#FFFFFF"); - app.setTextColor1("#FFFFFF"); - app.setTextColor2("#FFFFFF"); - assertTrue(areFieldsEqual(getExpectedFields(), app.getPostFields())); - } -} diff --git a/src/test/java/com/hellosign/sdk/resource/EventTest.java b/src/test/java/com/hellosign/sdk/resource/EventTest.java deleted file mode 100644 index 0b05c897..00000000 --- a/src/test/java/com/hellosign/sdk/resource/EventTest.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.hellosign.sdk.resource; - -/** - * The MIT License (MIT) - * - * Copyright (C) 2015 hellosign.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -import static org.junit.Assert.*; - -import org.junit.Test; - -import com.hellosign.sdk.AbstractHelloSignTest; -import com.hellosign.sdk.HelloSignException; - -/** - * Exercises the Event object. - * - * @author "Chris Paul (chris@hellosign.com)" - */ -public class EventTest extends AbstractHelloSignTest { - - @Test - public void testEventHashing() throws HelloSignException { - Event event = new Event(getExpectedJSONResponse()); - assertNotNull(event); - assertFalse(event.isValid(null)); - assertFalse(event.isValid("")); - - // This works for the JSON response in EventTest/expectedResponse.txt - // Ensures that if the hash checking changes, we are notified in the API - assertTrue(event.isValid("4e94adf59d17c417ce0d1d2cb34b953ba7a1eebe1ecbe31bb1c586af92af1e1d")); - } - -} diff --git a/src/test/java/com/hellosign/sdk/resource/MultiTemplateSignatureRequestTest.java b/src/test/java/com/hellosign/sdk/resource/MultiTemplateSignatureRequestTest.java deleted file mode 100644 index 078c9f4a..00000000 --- a/src/test/java/com/hellosign/sdk/resource/MultiTemplateSignatureRequestTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.hellosign.sdk.resource; - -/** - * The MIT License (MIT) - * - * Copyright (C) 2015 hellosign.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -import static org.junit.Assert.*; - -import java.io.Serializable; -import java.net.HttpURLConnection; -import java.util.List; -import java.util.Map; - -import org.json.JSONObject; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.hellosign.sdk.AbstractHelloSignTest; -import com.hellosign.sdk.HelloSignClient; -import com.hellosign.sdk.HelloSignException; -import com.hellosign.sdk.http.HttpPostRequest; -import com.hellosign.sdk.resource.Template; -import com.hellosign.sdk.resource.TemplateSignatureRequest; -import com.hellosign.sdk.resource.support.TemplateList; - -/** - * This test is meant to be run internally. Will be skipped by automated tests. - * - * @author "Chris Paul (chris@hellosign.com)" - */ -public class MultiTemplateSignatureRequestTest extends AbstractHelloSignTest { - - private static final Logger logger = LoggerFactory.getLogger(TemplateSignatureRequestTest.class); - - /* - @Test - public void testMultiTemplateSignatureRequestCreateAndSend() throws HelloSignException { - if (!isHelloSignAvailable()) { - logger.debug("No API access, skipping tests..."); - return; - } - // Retrieve user's templates - logger.debug("Testing Template list... "); - HelloSignClient client = new HelloSignClient(auth); - - // Create the signature request based on template - TemplateSignatureRequest request = new TemplateSignatureRequest(); - request.addTemplateId("c1a5d2dfb74e732c146cb038f9a3ac7d21b1ae0d"); - request.addTemplateId("9bcc3e903b2c24b1068ca32c051ab3d6b73707ca", 0); - request.addTemplateId("fa6d13bc5cddb80f2973c0b12a3a066e75471f06"); - request.setTestMode(true); - request.setSubject("MultiTemplateTest"); - request.setMessage("Glad we could come to an agreement."); - request.setSigner("Tester", "chris+1@hellosign.com", "Chris 1"); - request.setCustomFieldValue("Text", "Hello world!"); - - logger.debug("Building POST fields... "); - Map fields = request.getPostFields(); - assertTrue(areFieldsEqual(getExpectedFields(), fields)); - logger.debug("\tFields match!"); - - // HelloSignClient client = new HelloSignClient(validUserEmail, validUserPass); - // response = client.sendTemplateSignatureRequest(request); - - // The following is for testing purposes only. Don't do this in your code, - // you'll want to use the line above to send your request, much easier! - - logger.debug("Creating new request..."); - logger.debug("POST " + client.getTemplateSignatureRequestUrl()); - HttpPostRequest postRequest = new HttpPostRequest( - client.getTemplateSignatureRequestUrl(), - fields, auth); - JSONObject jsonResponse = postRequest.getJsonResponse(); - assertTrue(areJSONObjectsEqualIgnoreData(getExpectedJSONResponse(), jsonResponse)); - - // Convert the JSON response to a SignatureRequest - SignatureRequest response = new SignatureRequest(jsonResponse); - assertNotNull(response); - logger.debug("\tSuccess!"); - logger.debug("Created signature request with ID: " + response.getId()); - - // Cancel newly created request - logger.debug("Cancelling new request..."); - String cancelUrl = client.getSignatureRequestCancelUrl() + "/" + response.getId(); - logger.debug("POST " + cancelUrl); - postRequest = new HttpPostRequest(cancelUrl, auth); - assertTrue(HttpURLConnection.HTTP_OK == postRequest.getHttpResponseCode()); - logger.debug("\tSuccess!"); - } -*/ - -} diff --git a/src/test/java/com/hellosign/sdk/resource/SignatureRequestMetadataTest.java b/src/test/java/com/hellosign/sdk/resource/SignatureRequestMetadataTest.java deleted file mode 100644 index 9368ba40..00000000 --- a/src/test/java/com/hellosign/sdk/resource/SignatureRequestMetadataTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.hellosign.sdk.resource; - -import static org.junit.Assert.*; - -import java.io.Serializable; -import java.util.Map; - -import org.json.JSONObject; -import org.junit.Test; - -import com.hellosign.sdk.AbstractHelloSignTest; -import com.hellosign.sdk.HelloSignException; - -public class SignatureRequestMetadataTest extends AbstractHelloSignTest { - - @Test - public void test() throws HelloSignException { - JSONObject json = getExpectedJSONResponse(); - SignatureRequest sr = new SignatureRequest(json); - assertEquals(sr.getMetadata("client_id"), "1234"); - sr.addMetadata("new!", "Hello, world!"); - Map fields = sr.getPostFields(); - assertTrue(areFieldsEqual(getExpectedFields(), fields)); - } - -} diff --git a/src/test/java/com/hellosign/sdk/resource/SignatureRequestTest.java b/src/test/java/com/hellosign/sdk/resource/SignatureRequestTest.java deleted file mode 100644 index 44c0d178..00000000 --- a/src/test/java/com/hellosign/sdk/resource/SignatureRequestTest.java +++ /dev/null @@ -1,318 +0,0 @@ -package com.hellosign.sdk.resource; - -/** - * The MIT License (MIT) - * - * Copyright (C) 2015 hellosign.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -import static org.junit.Assert.*; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import org.json.JSONObject; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.hellosign.sdk.AbstractHelloSignTest; -import com.hellosign.sdk.HelloSignClient; -import com.hellosign.sdk.HelloSignException; -import com.hellosign.sdk.http.HttpPostRequest; -import com.hellosign.sdk.resource.SignatureRequest; -import com.hellosign.sdk.resource.support.Document; -import com.hellosign.sdk.resource.support.FormField; -import com.hellosign.sdk.resource.support.Signature; -import com.hellosign.sdk.resource.support.SignatureRequestList; -import com.hellosign.sdk.resource.support.types.FieldType; - -/** - * Exercises the Signature Request capability. - * - * @author "Chris Paul (chris@hellosign.com)" - */ -public class SignatureRequestTest extends AbstractHelloSignTest { - - private static final Logger logger = LoggerFactory.getLogger(SignatureRequestTest.class); - - @Test - public void testSignatureRequestCreate() throws HelloSignException { - // Create the signature request - SignatureRequest request = new SignatureRequest(); - request.setTestMode(true); - request.setTitle("NDA with Acme Co."); - request.setSubject("The NDA we talked about"); - request.setMessage("Please sign this NDA and then we can discuss more. Let me know if you have any questions."); - request.addSigner("jill@example.com", "Jill"); - request.addSigner("jack@example.com", "Jack", 1); - request.setOrderMatters(true); - request.addCC("lawyer@hellosign.com"); - request.addCC("lawyer@example.com"); - request.addFile(getTestFile("nda.pdf")); - request.addFile(getTestFile("AppendixA.pdf")); - - // Test the POST fields - logger.debug("Building POST fields... "); - Map fields = request.getPostFields(); - assertTrue(areFieldsEqual(getExpectedFields(), fields)); - logger.debug("\tSuccess!"); - - // HelloSignClient client = new HelloSignClient(validUserEmail, validUserPass); - // SignatureRequest response = client.sendSignatureRequest(request); - - // The following is for testing purposes only. Don't do this in your code, - // you'll want to use the lines above to send your request, much easier! - - if (isHelloSignAvailable()) { - HelloSignClient client = new HelloSignClient(auth); - logger.debug("Creating new request..."); - logger.debug("POST " + client.getSignatureRequestUrl()); - HttpPostRequest postRequest = new HttpPostRequest( - client.getSignatureRequestSendUrl(), - fields, auth); - JSONObject createResponse = postRequest.getJsonResponse(); - assertTrue( - areJSONObjectsEqualIgnoreData( - getExpectedJSONResponse(), - createResponse)); - logger.debug("\tSuccess!"); - - // Convert the JSON response to a SignatureRequest - SignatureRequest response = new SignatureRequest(createResponse); - assertNotNull(request); - logger.debug("SignatureRequest created with ID: " + response.getId()); - - // Test retrieval by user list - logger.debug("Testing SignatureRequest list..."); - SignatureRequestList list = client.getSignatureRequests(); - List foundRequests = - list.filterCurrentPageBy(SignatureRequest.REQUEST_TITLE, request.getTitle()); - - // If the request isn't found, let's page through the results from the server until we find it - while (foundRequests.size() == 0) { - Integer nextPage = list.getPage() + 1; - if (nextPage > list.getNumPages()) { - break; - } - list = client.getSignatureRequests(nextPage); - foundRequests = - list.filterCurrentPageBy(SignatureRequest.REQUEST_TITLE, request.getTitle()); - } - - // Make sure we have at least one request - assertTrue(foundRequests.size() >= 1); - logger.debug("\tSuccess!"); - - // Test retrieval by ID - logger.debug("Testing direct SignatureRequest retrieval..."); - SignatureRequest retrievedReq = client.getSignatureRequest(response.getId()); - assertNotNull(retrievedReq); - assertEquals(retrievedReq.getId(), response.getId()); - logger.debug("\tSuccess!"); - - // Test signature request reminder - logger.debug("Testing SignatureRequest reminder..."); - SignatureRequest remindedReq = client.requestEmailReminder(response.getId(), "jack@example.com"); - assertNotNull(remindedReq); - assertEquals(remindedReq.getId(), response.getId()); - logger.debug("\tSuccess!"); - - // Test final copy retrieval (should fail) -// logger.debug("Testing retrieval of final copy..."); -// try { -// client.getFinalCopy(response.getId()); -// } catch (HelloSignException ex) { -// assertEquals(ex.getMessage(), "Not ready"); -// } - -// logger.debug("Testing retrieval of files..."); -// File f = null; -// int tries = 0; -// int sleep = 5000; // 5 seconds -// while (f == null && tries < 10) { -// try { -// f = client.getFiles(response.getId()); -// } catch (HelloSignException ex) { -// assertEquals(ex.getMessage(), "Not ready"); -// try { -// logger.debug("Sleeping " + sleep + " milliseconds..."); -// Thread.sleep(sleep); -// tries++; -// } catch (Exception e) {}; -// } -// } -// -// assertNotNull(f); -// assertTrue(f.exists()); - - logger.debug("\tSuccess!"); - - // Cancel the signature request - // client.cancelSignatureRequest(response.getId()); - logger.debug("Cancelling new request..."); - String cancelUrl = client.getSignatureRequestCancelUrl() + "/" + response.getId(); - logger.debug("POST " + cancelUrl); - postRequest = new HttpPostRequest(cancelUrl, auth); - logger.debug("HTTP response code: " + postRequest.getHttpResponseCode()); -// assertTrue(HttpURLConnection.HTTP_OK == postRequest.getHttpResponseCode()); - logger.debug("\tSuccess!"); - } - } - -// @Test -// public void testFinalCopyRetrieval() throws HelloSignException { -// HelloSignClient client = new HelloSignClient(validApiKey); -// File f = client.getFinalCopy("6a310a025cac668778f1e2b5624e8934e0975ed2"); -// logger.debug(f.getAbsolutePath()); -// assertNotNull(f); -// } - -// @Test(expected=HelloSignException.class) -// public void testRetrieveDeletedSig() throws HelloSignException { -// HelloSignClient client = new HelloSignClient(validApiKey); -// client.getSignatureRequest("711d4f19607e4c49928057b2a326d30c1b65418f"); -// } - - @Test - public void testTextTags() throws HelloSignException { - SignatureRequest req = new SignatureRequest(); - req.setTestMode(true); - req.addSigner("abeecher@example.com", "Alice"); - req.addFile(getTestFile("text_tags_test.pdf")); - req.setUseTextTags(true); - assertNotNull(req); - assertTrue(req.isUsingTextTags()); - logger.debug("Sending: " + req.toString()); - if (isHelloSignAvailable()) { - HelloSignClient client = new HelloSignClient(auth); - logger.debug("Creating new request..."); - logger.debug("POST " + client.getSignatureRequestUrl()); - SignatureRequest resp = client.sendSignatureRequest(req); - assertNotNull(resp); - logger.debug("\tSuccess!"); - } - } - - @Test - public void testHiddenTextTags() throws HelloSignException { - SignatureRequest req = new SignatureRequest(); - req.setTestMode(true); - req.addSigner("abeecher@example.com", "Alice"); - req.addFile(getTestFile("test_white_text_tags.pdf")); - req.setUseTextTags(true); - req.setHideTextTags(true); - assertNotNull(req); - assertTrue(req.isUsingTextTags()); - logger.debug("Sending: " + req.toString()); - if (isHelloSignAvailable()) { - HelloSignClient client = new HelloSignClient(auth); - logger.debug("Creating new request..."); - logger.debug("POST " + client.getSignatureRequestUrl()); - SignatureRequest resp = client.sendSignatureRequest(req); - assertNotNull(resp); - logger.debug("\tSuccess!"); - } - } - - @Test - public void testGetSignature() throws HelloSignException { - SignatureRequest req = new SignatureRequest(); - req.setTestMode(true); - req.addSigner("abeecher@example.com", "Alice"); - req.addFile(getTestFile("test_white_text_tags.pdf")); - logger.debug("Sending: " + req.toString()); - if (isHelloSignAvailable()) { - HelloSignClient client = new HelloSignClient(auth); - logger.debug("Creating new request..."); - logger.debug("POST " + client.getSignatureRequestUrl()); - SignatureRequest resp = client.sendSignatureRequest(req); - assertNotNull(resp); - Signature sig = resp.getSignature("abeecher@example.com", "Alice"); - assertNotNull(sig); - logger.debug("\tSuccess!"); - } - } - - @Test - public void testUpdateSignature() throws HelloSignException { - if (isHelloSignAvailable()) { - String goodName = "Jill"; - String badEmail = "llij@hellosign.com"; - String goodEmail = "jill@hellosign.com"; - // Create the signature request - SignatureRequest request = new SignatureRequest(); - request.setTestMode(true); - request.addSigner(badEmail, goodName); - Document doc = new Document(); - doc.setFile(getTestFile("nda.pdf")); - FormField signature_field = new FormField(); - signature_field.setType(FieldType.signature); - signature_field.setSigner(1); - signature_field.setX(200); - signature_field.setY(200); - signature_field.setWidth(300); - signature_field.setHeight(80); - signature_field.setPage(1); - doc.addFormField(signature_field); - request.addDocument(doc); - HelloSignClient client = new HelloSignClient(auth); - SignatureRequest sentRequest = client.sendSignatureRequest(request); - assertNotNull(sentRequest); - assertTrue(sentRequest.getSignatures().get(0).getEmail().equals(badEmail)); - Signature badSigner = sentRequest.getSignature(badEmail, goodName); - SignatureRequest updatedRequest = client.updateSignatureRequest( - sentRequest.getId(), - badSigner.getId(), - goodEmail); - assertNotNull(updatedRequest); - assertTrue(updatedRequest.getSignatures().get(0).getEmail().equals(goodEmail)); - } - } - - @Test - public void testSignatureRequestClientId() throws HelloSignException { - String clientid = "TEST"; - SignatureRequest req = new SignatureRequest(); - req.setClientId(clientid); - Map fields = req.getPostFields(); - String reqclientid = (String) fields.get(AbstractRequest.REQUEST_CLIENT_ID); - assertTrue(clientid.equals(reqclientid)); - } - - @Test - public void testSignatureRequestDecline() throws HelloSignException { - SignatureRequest req = new SignatureRequest(); - req.setIsDeclinable(true); - assertTrue(req.getIsDeclinable()); - Map fields = req.getPostFields(); - String allow_decline = (String) fields.get(AbstractRequest.REQUEST_ALLOW_DECLINE); - assertTrue("1".equals(allow_decline)); - req.setIsDeclinable(false); - assertTrue(!req.getIsDeclinable()); - fields = req.getPostFields(); - allow_decline = (String) fields.get(AbstractRequest.REQUEST_ALLOW_DECLINE); - assertTrue("0".equals(allow_decline)); - req.setIsDeclinable(null); - assertNull(req.getIsDeclinable()); - } -} diff --git a/src/test/java/com/hellosign/sdk/resource/TeamTest.java b/src/test/java/com/hellosign/sdk/resource/TeamTest.java deleted file mode 100644 index 1dbbb518..00000000 --- a/src/test/java/com/hellosign/sdk/resource/TeamTest.java +++ /dev/null @@ -1,183 +0,0 @@ -package com.hellosign.sdk.resource; - -/** - * The MIT License (MIT) - * - * Copyright (C) 2015 hellosign.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -import static org.junit.Assert.*; - -import java.net.HttpURLConnection; - -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.hellosign.sdk.AbstractHelloSignTest; -import com.hellosign.sdk.HelloSignClient; -import com.hellosign.sdk.HelloSignException; -import com.hellosign.sdk.resource.support.types.RoleType; - -/** - * Exercise the Team class and HelloSignClient team operations. - * - * @author "Chris Paul (chris@hellosign.com)" - */ -public class TeamTest extends AbstractHelloSignTest { - - private static final Logger logger = LoggerFactory.getLogger(TeamTest.class); - - // These tests will not work with new users, since you cannot - // create teams with a free account any more. Will need to revisit - // these tests once we can upgrade a user via the API, or - // allow configuration of the test to use an upgraded user. - -// @Test -// public void testTeam() throws Exception { -// -// if (!isHelloSignAvailable()) { -// logger.debug("No API access, skipping tests..."); -// return; -// } -// -// logger.debug("Retrieving current user's team..."); -// HelloSignClient client = new HelloSignClient(auth); -// Team originalTeam = null; -// boolean teamCreated = false; -// -// try { -// originalTeam = client.getTeam(); -// assertNotNull(originalTeam); -// -// // Determine if we're the owner of the current team -// // If not, we can skip these tests because there is no way to -// // do any of them without owner status and you cannot currently -// // leave a team. -// for (Account account : originalTeam.getAccounts()) { -// if (validApiKey.equals(account.getEmail())) { -// if (RoleType.MEMBER.equals(account.getRoleCode())) { -// logger.debug("\tCannot test teams for user " + validApiKey + ". Must be owner of team."); -// return; -// } else { -// break; -// } -// } -// } -// } catch (HelloSignException ex) { -// // It's likely the team doesn't exist yet, so let's create one -// } -// -// String updatedName = ""; -// if (originalTeam == null) { -// logger.debug("\tNo team found, creating one..."); -// originalTeam = client.createTeam(teamName); -// assertNotNull(originalTeam); -// assertTrue(teamName.equals(originalTeam.getName())); -// teamCreated = true; -// updatedName = originalTeam.getName(); -// } -// logger.debug("\tSuccess!"); -// -// // Update the team name -// String newName = (updatedName != "" ? updatedName + " " : "") + "UPDATED"; -// logger.debug("Updating team name to: " + newName); -// Team updatedTeam = client.updateTeamName(newName); -// assertNotNull(updatedTeam); -// assertTrue(newName.equals(updatedTeam.getName())); -// logger.debug("\tSuccess!"); -// -// // Revert the team name -// logger.debug("Reverting team name to: " + originalTeam.getName()); -// updatedTeam = client.updateTeamName(originalTeam.getName()); -// assertNotNull(updatedTeam); -// assertTrue(originalTeam.getName().equals(updatedTeam.getName())); -// logger.debug("\tSuccess!"); -// -// if (validUserEmail2 == null || validUserEmail2.equals("")) { -// logger.debug("No valid user provided, skipping remainder of tests."); -// return; -// } - - // Invite new user to team -// logger.debug("Inviting new user to team: " + validUserEmail2); -// boolean found = false; -// try { -// updatedTeam = client.inviteTeamMember(validUserEmail2); -// assertNotNull(updatedTeam); -// for (Account account : updatedTeam.getInvitedAccounts()) { -// if (validUserEmail2.equals(account.getEmail())) { -// found = true; -// break; -// } -// } -// assertTrue(found); -// logger.debug("\tUser has been invited to join the team."); -// } catch (HelloSignException ex) { -// if ("This account is already on your team".equals(ex.getMessage())) { -// logger.debug("\tCannot perform test, user is already a member of the team."); -// } else { -// throw ex; -// } -// } -// -// // Remove user from team if we invited them -// if (found) { -// logger.debug("Removing user from team: " + validUserEmail2); -// updatedTeam = client.removeTeamMember(validUserEmail2); -// assertNotNull(updatedTeam); -// found = false; -// for (Account account : updatedTeam.getAccounts()) { -// if (validUserEmail2.equals(account.getEmail())) { -// found = true; -// break; -// } -// } -// if (!found) { -// for (Account account : updatedTeam.getInvitedAccounts()) { -// if (validUserEmail2.equals(account.getEmail())) { -// found = true; -// break; -// } -// } -// } -// assertFalse(found); -// logger.debug("\tSuccess!"); -// } -// - // We don't want to destroy the team if it has more than one member -// if (updatedTeam.getAccounts().size() != 1) { -// logger.debug("Skipping remainder of tests..."); -// return; -// } -// -// // We don't want to destroy the team if we didn't create it for the test -// if (!teamCreated) { -// logger.debug("Skipping remainder of tests..."); -// return; -// } -// -// // Test destroying team -// logger.debug("Testing destoy team..."); -// assertTrue(HttpURLConnection.HTTP_OK == client.destroyTeam()); -// logger.debug("\tSuccess!"); -// } -} diff --git a/src/test/java/com/hellosign/sdk/resource/TemplateDraftTest.java b/src/test/java/com/hellosign/sdk/resource/TemplateDraftTest.java deleted file mode 100644 index d5233227..00000000 --- a/src/test/java/com/hellosign/sdk/resource/TemplateDraftTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.hellosign.sdk.resource; - -/** - * The MIT License (MIT) - * - * Copyright (C) 2015 hellosign.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -import static org.junit.Assert.*; - -import org.json.JSONObject; -import org.junit.Test; - -import com.hellosign.sdk.AbstractHelloSignTest; -import com.hellosign.sdk.resource.support.types.FieldType; - -/** - * @author "Chris Paul (chris@hellosign.com)" - */ -public class TemplateDraftTest extends AbstractHelloSignTest { - - @Test - public void testTemplateDraftCreate() throws Exception { - TemplateDraft t = new TemplateDraft(); - assertNotNull(t); - - t = new TemplateDraft(new JSONObject("{}")); - assertNotNull(t); - assertNull(t.getId()); - assertNull(t.getEditUrl()); - assertNull(t.getExpiresAt()); - - t = new TemplateDraft(new JSONObject("{'template':{'template_id':'1234567890abcdef'}}")); - assertNotNull(t); - assertNotNull(t.getId()); - assertNull(t.getEditUrl()); - assertNull(t.getExpiresAt()); - - t = new TemplateDraft(new JSONObject("{'template':{'template_id':'1234567890abcdef','edit_url':'https://www.google.com/','expires_at':'1234567890'}}")); - assertNotNull(t); - assertNotNull(t.getId()); - assertNotNull(t.getEditUrl()); - assertNotNull(t.getExpiresAt()); - } - - @Test - public void testTemplateDraftPostFields() throws Exception { - TemplateDraft t = new TemplateDraft(); - t.setTestMode(true); - t.addFile(getTestFile("nda.pdf")); - t.addSignerRole("Signer 1"); - t.addSignerRole("Signer 2"); - t.addCCRole("CC Role 1"); - t.setTitle("Title"); - t.setSubject("Subject"); - t.setMessage("Message"); - t.addMergeField("Text", FieldType.text); - t.addMergeField("Checkbox", FieldType.checkbox); - assertTrue(areFieldsEqual(getExpectedFields(), t.getPostFields())); - } -} diff --git a/src/test/java/com/hellosign/sdk/resource/TemplateSignatureRequestTest.java b/src/test/java/com/hellosign/sdk/resource/TemplateSignatureRequestTest.java deleted file mode 100644 index 69972677..00000000 --- a/src/test/java/com/hellosign/sdk/resource/TemplateSignatureRequestTest.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.hellosign.sdk.resource; - -/** - * The MIT License (MIT) - * - * Copyright (C) 2015 hellosign.com - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -import static org.junit.Assert.*; - -import java.io.Serializable; -import java.net.HttpURLConnection; -import java.util.List; -import java.util.Map; - -import org.json.JSONObject; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.hellosign.sdk.AbstractHelloSignTest; -import com.hellosign.sdk.HelloSignClient; -import com.hellosign.sdk.HelloSignException; -import com.hellosign.sdk.http.HttpPostRequest; -import com.hellosign.sdk.resource.Template; -import com.hellosign.sdk.resource.TemplateSignatureRequest; -import com.hellosign.sdk.resource.support.TemplateList; - -/** - * IMPORTANT: - * - * Before this test case can be run, a template must be manually created on the - * HelloSign server. This template must have the following information: - * - * - Title: "testTemplateSignatureRequest" - * - Signing Role: "Client" - * - CC Role: "Accounting" - * - * The document must have 2 fields: - * - * 1. Textbox: - * - Label: "Cost" - * - Filled by: "Me (when sending)" - * 2. Signature: "Client" - * - * If the template doesn't exist, this test will simply be skipped. - * - * @author "Chris Paul (chris@hellosign.com)" - */ -public class TemplateSignatureRequestTest extends AbstractHelloSignTest { - - private static final Logger logger = LoggerFactory.getLogger(TemplateSignatureRequestTest.class); - - @Test - public void testTemplateSignatureRequestCreateAndSend() throws HelloSignException { - if (!isHelloSignAvailable()) { - logger.debug("No API access, skipping tests..."); - return; - } - // Retrieve user's templates - logger.debug("Testing Template list... "); - HelloSignClient client = new HelloSignClient(auth); - TemplateList templateList = client.getTemplates(); - List