From 4e6feecb9fab8d68bddc6c6e003b43f21fe251c3 Mon Sep 17 00:00:00 2001 From: Henry Hai Date: Wed, 8 Apr 2015 15:44:47 -0400 Subject: [PATCH] TaskRouter Classes Lookups Classes Forked List - Next Gen List Support Forked Client - New URL Endpoints TaskRouter, Lookups. Defect Fix - SetRequestAccountSid on all Legacy List Classes. Added new TwiML verbs for TaskRouter Added Test Classes Updated version to 3.3 --- src/classes/TwilioAPI.cls | 29 +- src/classes/TwilioAccount.cls | 159 +-- src/classes/TwilioAccountList.cls | 4 +- src/classes/TwilioApplicationList.cls | 9 +- .../TwilioAuthorizedConnectAppList.cls | 7 +- src/classes/TwilioAvailablePhoneNumber.cls | 2 +- .../TwilioAvailablePhoneNumberList.cls | 7 +- src/classes/TwilioCall.cls | 27 +- src/classes/TwilioCallList.cls | 12 +- src/classes/TwilioCapability.cls | 39 +- src/classes/TwilioCapabilityPolicy.cls | 37 + .../TwilioCapabilityPolicy.cls-meta.xml | 5 + src/classes/TwilioClient.cls | 716 +++++++++++++ src/classes/TwilioClient.cls-meta.xml | 5 + src/classes/TwilioConference.cls | 2 +- src/classes/TwilioConferenceList.cls | 7 +- src/classes/TwilioConnectAppList.cls | 6 +- src/classes/TwilioIncomingPhoneNumberList.cls | 7 +- src/classes/TwilioIterator.cls | 4 +- src/classes/TwilioMediaList.cls | 6 +- src/classes/TwilioMember.cls | 2 +- src/classes/TwilioMemberList.cls | 8 +- src/classes/TwilioMessage.cls | 41 +- src/classes/TwilioMessageList.cls | 8 +- src/classes/TwilioNotificationList.cls | 7 +- src/classes/TwilioOutgoingCallerIdList.cls | 7 +- src/classes/TwilioParser.cls | 421 +++++--- src/classes/TwilioParticipant.cls | 4 +- src/classes/TwilioParticipantList.cls | 7 +- src/classes/TwilioQueue.cls | 6 +- src/classes/TwilioQueueList.cls | 6 +- src/classes/TwilioRecording.cls | 2 +- src/classes/TwilioRecordingList.cls | 151 +-- src/classes/TwilioResource.cls | 417 ++++++-- src/classes/TwilioRestClient.cls | 674 +------------ src/classes/TwilioRestException.cls | 158 +-- src/classes/TwilioRestResponse.cls | 428 ++++---- src/classes/TwilioShortCode.cls | 310 +++--- src/classes/TwilioShortCodeList.cls | 103 +- src/classes/TwilioSmsList.cls | 6 +- src/classes/TwilioTRActivities.cls | 17 +- src/classes/TwilioTRActivitiesList.cls | 21 +- src/classes/TwilioTRReservation.cls | 22 +- src/classes/TwilioTRReservationList.cls | 21 +- src/classes/TwilioTRRestClient.cls | 92 ++ src/classes/TwilioTRRestClient.cls-meta.xml | 5 + src/classes/TwilioTRTask.cls | 34 +- src/classes/TwilioTRTaskList.cls | 21 +- src/classes/TwilioTRTaskQueue.cls | 15 +- src/classes/TwilioTRTaskQueueList.cls | 27 +- src/classes/TwilioTRTest.cls | 168 ++-- src/classes/TwilioTRWorker.cls | 20 +- src/classes/TwilioTRWorkerList.cls | 21 +- src/classes/TwilioTRWorkflow.cls | 18 +- src/classes/TwilioTRWorkflowList.cls | 21 +- src/classes/TwilioTRWorkspace.cls | 91 +- src/classes/TwilioTRWorkspaceList.cls | 16 +- src/classes/TwilioTranscriptionList.cls | 7 +- src/classes/Twilio_TestApplication.cls | 414 ++++---- src/classes/Twilio_TestCalls.cls | 938 +++++++++--------- src/classes/Twilio_TestCapability.cls | 106 +- src/classes/Twilio_TestPhoneNumbers.cls | 2 +- src/classes/Twilio_TestQueue.cls | 1 - src/classes/Twilio_TestShortCode.cls | 53 + src/classes/Twilio_TestShortCode.cls-meta.xml | 5 + .../Twilio_Lookups.remoteSite | 7 + .../Twilio_TaskRouter.remoteSite | 7 + 67 files changed, 3375 insertions(+), 2651 deletions(-) create mode 100644 src/classes/TwilioCapabilityPolicy.cls create mode 100644 src/classes/TwilioCapabilityPolicy.cls-meta.xml create mode 100644 src/classes/TwilioClient.cls create mode 100644 src/classes/TwilioClient.cls-meta.xml create mode 100644 src/classes/TwilioTRRestClient.cls create mode 100644 src/classes/TwilioTRRestClient.cls-meta.xml create mode 100644 src/classes/Twilio_TestShortCode.cls create mode 100644 src/classes/Twilio_TestShortCode.cls-meta.xml create mode 100755 src/remoteSiteSettings/Twilio_Lookups.remoteSite create mode 100755 src/remoteSiteSettings/Twilio_TaskRouter.remoteSite diff --git a/src/classes/TwilioAPI.cls b/src/classes/TwilioAPI.cls index db5617c..0e7bd73 100644 --- a/src/classes/TwilioAPI.cls +++ b/src/classes/TwilioAPI.cls @@ -47,7 +47,9 @@ global class TwilioAPI { private class MissingTwilioConfigCustomSettingsException extends Exception {} private static TwilioRestClient client; - + private static TwilioTRRestClient trClient; + private static TwilioLookupsRestClient lookupsClient; + private TwilioAPI() {} /** @@ -60,7 +62,29 @@ global class TwilioAPI { } return TwilioAPI.client; } - + + /** + * Get a TwilioTRRestClient pre-populated with your TwilioConfig credentials + */ + public static TwilioTRRestClient getDefaultTRClient() { + if (trClient==null) { + TwilioConfig__c twilioCfg = getTwilioConfig(); + TwilioAPI.trClient = new TwilioTRRestClient(twilioCfg.AccountSid__c, twilioCfg.AuthToken__c); + } + return TwilioAPI.trClient; + } + + /** + * Get a TwilioLookupsRestClient pre-populated with your TwilioConfig credentials + */ + public static TwilioLookupsRestClient getDefaultLookupsClient() { + if (lookupsClient==null) { + TwilioConfig__c twilioCfg = getTwilioConfig(); + TwilioAPI.lookupsClient = new TwilioLookupsRestClient(twilioCfg.AccountSid__c, twilioCfg.AuthToken__c); + } + return TwilioAPI.lookupsClient; + } + /** * Get your primary account using your TwilioConfig credentials */ @@ -86,6 +110,7 @@ global class TwilioAPI { return new TwilioTRCapability(twilioCfg.AccountSid__c, twilioCfg.AuthToken__c, workspaceSid, workerSid); } + /** * Get a new TwilioRestClient authorized with the credentials provided */ diff --git a/src/classes/TwilioAccount.cls b/src/classes/TwilioAccount.cls index 7ea1f2f..525decc 100644 --- a/src/classes/TwilioAccount.cls +++ b/src/classes/TwilioAccount.cls @@ -41,7 +41,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { /* Constructor */ public TwilioAccount(TwilioRestClient client) { - super(client); + super(client); } /* Constructor, using predefined set of property values */ @@ -126,9 +126,6 @@ global class TwilioAccount extends TwilioResource.InstanceResource { /** Constructs a Twilio API resource URI for this Account. Overrides method from TwilioResource. */ public override String getResourceLocation() { - system.debug('Account Resource Location:' + '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '.json'); - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' + this.getRequestAccountSid() + '.json'; } @@ -147,7 +144,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * See http://www.twilio.com/docs/api/rest/call */ public TwilioCallList getCalls(Map filters) { - TwilioCallList calls = new TwilioCallList(this.getClient(), filters); + TwilioCallList calls = new TwilioCallList((TwilioRestClient)this.getClient(), filters); calls.setRequestAccountSid(this.getRequestAccountSid()); return calls; @@ -155,7 +152,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { /** Returns a given call instance by sid */ public TwilioCall getCall(String sid) { - TwilioCall call = new TwilioCall(this.getClient(), sid); + TwilioCall call = new TwilioCall((TwilioRestClient)this.getClient(), sid); call.setRequestAccountSid(this.getRequestAccountSid()); return call; } @@ -174,7 +171,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * See http://www.twilio.com/docs/api/rest/sms */ public TwilioSmsList getSmsMessages(Map filters) { - TwilioSmsList sms = new TwilioSmsList(this.getClient(), filters); + TwilioSmsList sms = new TwilioSmsList((TwilioRestClient)this.getClient(), filters); sms.setRequestAccountSid(this.getRequestAccountSid()); return sms; @@ -182,7 +179,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { /** Returns a given SMS message by sid */ public TwilioSms getSms(String sid) { - TwilioSms sms = new TwilioSms(this.getClient(), sid); + TwilioSms sms = new TwilioSms((TwilioRestClient)this.getClient(), sid); sms.setRequestAccountSid(this.getRequestAccountSid()); return sms; } @@ -200,7 +197,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * See http://www.twilio.com/docs/api/rest/message */ public TwilioMessageList getMessages(Map filters) { - TwilioMessageList message = new TwilioMessageList(this.getClient(), filters); + TwilioMessageList message = new TwilioMessageList((TwilioRestClient)this.getClient(), filters); message.setRequestAccountSid(this.getRequestAccountSid()); return message; @@ -208,14 +205,14 @@ global class TwilioAccount extends TwilioResource.InstanceResource { /** Returns a given message by sid */ public TwilioMessage getMessage(String sid) { - TwilioMessage message = new TwilioMessage(this.getClient(), sid); + TwilioMessage message = new TwilioMessage((TwilioRestClient)this.getClient(), sid); message.setRequestAccountSid(this.getRequestAccountSid()); return message; } public TwilioQueueList getQueues() { - TwilioQueueList Queuelist = new TwilioQueueList(this.getClient(), filters); + TwilioQueueList Queuelist = new TwilioQueueList((TwilioRestClient)this.getClient(), filters); Queuelist.setRequestAccountSid(this.getRequestAccountSid()); return Queuelist; } @@ -228,7 +225,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { */ public TwilioQueue getQueue(String sid) { - TwilioQueue queue = new TwilioQueue(this.getClient(), sid); + TwilioQueue queue = new TwilioQueue((TwilioRestClient)this.getClient(), sid); queue.setRequestAccountSid(this.getRequestAccountSid()); return queue; } @@ -246,7 +243,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioAccount a = new TwilioAccount(this.getClient(), response.toMap()); + TwilioAccount a = new TwilioAccount((TwilioRestClient)this.getClient(), response.toMap()); a.setRequestAccountSid(this.getRequestAccountSid()); return a; } @@ -264,7 +261,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioAccount a = new TwilioAccount(this.getClient(), response.toMap()); + TwilioAccount a = new TwilioAccount((TwilioRestClient)this.getClient(), response.toMap()); a.setRequestAccountSid(this.getRequestAccountSid()); return a; } @@ -282,7 +279,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioAccount a = new TwilioAccount(this.getClient(), response.toMap()); + TwilioAccount a = new TwilioAccount((TwilioRestClient)this.getClient(), response.toMap()); a.setRequestAccountSid(this.getRequestAccountSid()); return a; } @@ -300,7 +297,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * See http://www.twilio.com/docs/api/rest/applications */ public TwilioApplicationList getApplications(Map filters) { - TwilioApplicationList twlist = new TwilioApplicationList(this.getClient(), filters); + TwilioApplicationList twlist = new TwilioApplicationList((TwilioRestClient)this.getClient(), filters); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } @@ -309,7 +306,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns a given Application instance by sid. */ public TwilioApplication getApplication(String sid) { - TwilioApplication app = new TwilioApplication(this.getClient(), sid); + TwilioApplication app = new TwilioApplication((TwilioRestClient)this.getClient(), sid); app.setRequestAccountSid(this.getRequestAccountSid()); return app; } @@ -329,7 +326,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { */ public TwilioAvailablePhoneNumberList getAvailablePhoneNumbers(Map filters) { TwilioAvailablePhoneNumberList twlist = new TwilioAvailablePhoneNumberList( - this.getClient(), filters); + (TwilioRestClient)this.getClient(), filters); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } @@ -352,7 +349,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { public TwilioAvailablePhoneNumberList getAvailablePhoneNumbers( Map filters, String isoCountry, String type) { TwilioAvailablePhoneNumberList twlist = new TwilioAvailablePhoneNumberList( - this.getClient(), filters, isoCountry, type); + (TwilioRestClient)this.getClient(), filters, isoCountry, type); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; @@ -371,7 +368,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * See http://www.twilio.com/docs/api/rest/conference */ public TwilioConferenceList getConferences(Map filters) { - TwilioConferenceList twlist = new TwilioConferenceList(this.getClient(), filters); + TwilioConferenceList twlist = new TwilioConferenceList((TwilioRestClient)this.getClient(), filters); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } @@ -380,7 +377,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns a given conference instance by sid. */ public TwilioConference getConference(String sid) { - TwilioConference conf = new TwilioConference(this.getClient(), sid); + TwilioConference conf = new TwilioConference((TwilioRestClient)this.getClient(), sid); conf.setRequestAccountSid(this.getRequestAccountSid()); return conf; } @@ -391,7 +388,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * @return */ public TwilioParticipantList getParticipants(String conferenceSid) { - TwilioParticipantList twlist = new TwilioParticipantList(this.getClient(), conferenceSid); + TwilioParticipantList twlist = new TwilioParticipantList((TwilioRestClient)this.getClient(), conferenceSid); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } @@ -411,7 +408,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { public TwilioIncomingPhoneNumberList getIncomingPhoneNumbers( Map filters) { TwilioIncomingPhoneNumberList twlist = new TwilioIncomingPhoneNumberList( - this.getClient(), filters); + (TwilioRestClient)this.getClient(), filters); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } @@ -420,7 +417,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns a given incoming phone number instance by sid. */ public TwilioIncomingPhoneNumber getIncomingPhoneNumber(String sid) { - TwilioIncomingPhoneNumber pn = new TwilioIncomingPhoneNumber(this.getClient(), sid); + TwilioIncomingPhoneNumber pn = new TwilioIncomingPhoneNumber((TwilioRestClient)this.getClient(), sid); pn.setRequestAccountSid(this.getRequestAccountSid()); return pn; } @@ -436,7 +433,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns the Short Code list with filters. */ public TwilioShortCodeList getShortCodes(Map filters) { - TwilioShortCodeList twlist = new TwilioShortCodeList(this.getClient(), filters); + TwilioShortCodeList twlist = new TwilioShortCodeList((TwilioRestClient)this.getClient(), filters); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } @@ -445,7 +442,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns a given Short Code instance by sid. */ public TwilioShortCode getShortCode(String sid) { - TwilioShortCode sc = new TwilioShortCode(this.getClient(), sid); + TwilioShortCode sc = new TwilioShortCode((TwilioRestClient)this.getClient(), sid); sc.setRequestAccountSid(this.getRequestAccountSid()); return sc; } @@ -463,7 +460,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns the notifications. */ public TwilioNotificationList getNotifications(Map filters) { - TwilioNotificationList twlist = new TwilioNotificationList(this.getClient(), filters); + TwilioNotificationList twlist = new TwilioNotificationList((TwilioRestClient)this.getClient(), filters); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } @@ -472,7 +469,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns a given notification instance by sid */ public TwilioNotification getNotification(String sid) { - TwilioNotification n = new TwilioNotification(this.getClient(), sid); + TwilioNotification n = new TwilioNotification((TwilioRestClient)this.getClient(), sid); n.setRequestAccountSid(this.getRequestAccountSid()); return n; } @@ -492,9 +489,9 @@ global class TwilioAccount extends TwilioResource.InstanceResource { public TwilioOutgoingCallerIdList getOutgoingCallerIds(Map filters) { TwilioOutgoingCallerIdList twlist; if (filters==null) { - twlist = new TwilioOutgoingCallerIdList(this.getClient()); + twlist = new TwilioOutgoingCallerIdList((TwilioRestClient)this.getClient()); } else { - twlist = new TwilioOutgoingCallerIdList(this.getClient(), filters); + twlist = new TwilioOutgoingCallerIdList((TwilioRestClient)this.getClient(), filters); } twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; @@ -504,7 +501,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns a given outgoing caller id instance by sid. */ public TwilioOutgoingCallerId getOutgoingCallerId(String sid) { - TwilioOutgoingCallerId cid = new TwilioOutgoingCallerId(this.getClient(), sid); + TwilioOutgoingCallerId cid = new TwilioOutgoingCallerId((TwilioRestClient)this.getClient(), sid); cid.setRequestAccountSid(this.getRequestAccountSid()); return cid; } @@ -523,7 +520,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * See http://www.twilio.com/docs/api/rest/recording */ public TwilioRecordingList getRecordings(Map filters) { - TwilioRecordingList twlist = new TwilioRecordingList(this.getClient(), filters); + TwilioRecordingList twlist = new TwilioRecordingList((TwilioRestClient)this.getClient(), filters); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } @@ -532,7 +529,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns a given recording instance by sid. */ public TwilioRecording getRecording(String sid) { - TwilioRecording r = new TwilioRecording(this.getClient(), sid); + TwilioRecording r = new TwilioRecording((TwilioRestClient)this.getClient(), sid); r.setRequestAccountSid(this.getRequestAccountSid()); return r; } @@ -550,7 +547,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * See http://www.twilio.com/docs/api/rest/transcription */ public TwilioTranscriptionList getTranscriptions(Map filters) { - TwilioTranscriptionList twlist = new TwilioTranscriptionList(this.getClient(), + TwilioTranscriptionList twlist = new TwilioTranscriptionList((TwilioRestClient)this.getClient(), filters); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; @@ -560,7 +557,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns a given transcription instance by sid */ public TwilioTranscription getTranscription(String sid) { - TwilioTranscription tr = new TwilioTranscription(this.getClient(), sid); + TwilioTranscription tr = new TwilioTranscription((TwilioRestClient)this.getClient(), sid); tr.setRequestAccountSid(this.getRequestAccountSid()); return tr; } @@ -571,7 +568,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * See http://www.twilio.com/docs/api/rest/connect-apps */ public TwilioConnectAppList getConnectApps(Map filters) { - TwilioConnectAppList twlist = new TwilioConnectAppList(this.getClient(), + TwilioConnectAppList twlist = new TwilioConnectAppList((TwilioRestClient)this.getClient(), filters); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; @@ -581,7 +578,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns a given connect app instance by sid */ public TwilioConnectApp getConnectApp(String sid) { - TwilioConnectApp cn = new TwilioConnectApp(this.getClient(), sid); + TwilioConnectApp cn = new TwilioConnectApp((TwilioRestClient)this.getClient(), sid); cn.setRequestAccountSid(this.getRequestAccountSid()); return cn; } @@ -591,7 +588,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * See http://www.twilio.com/docs/api/rest/connect-apps */ public TwilioAuthorizedConnectAppList getAuthorizedConnectApps(Map filters) { - TwilioAuthorizedConnectAppList twlist = new TwilioAuthorizedConnectAppList(this.getClient(), + TwilioAuthorizedConnectAppList twlist = new TwilioAuthorizedConnectAppList((TwilioRestClient)this.getClient(), filters); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; @@ -601,7 +598,7 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns a given connect app instance by sid. */ public TwilioAuthorizedConnectApp getAuthorizedConnectApp(String sid) { - TwilioAuthorizedConnectApp cn = new TwilioAuthorizedConnectApp(this.getClient(), sid); + TwilioAuthorizedConnectApp cn = new TwilioAuthorizedConnectApp((TwilioRestClient)this.getClient(), sid); cn.setRequestAccountSid(this.getRequestAccountSid()); return cn; } @@ -610,90 +607,8 @@ global class TwilioAccount extends TwilioResource.InstanceResource { * Returns the developer sandbox. */ public TwilioSandbox getSandbox() { - TwilioSandbox sb = new TwilioSandbox(this.getClient()); + TwilioSandbox sb = new TwilioSandbox((TwilioRestClient)this.getClient()); sb.setRequestAccountSid(this.getRequestAccountSid()); return sb; } - - /** - * Returns the Workspaces list. - * See http://www.twilio.com/docs/api/rest/recording - */ - public TwilioTRWorkspaceList getWorkspaces() { - return this.getWorkspaces(new Map()); - } - - /** - * Returns a list of Workspaces in this account, applying the supplied filters. - * See http://www.twilio.com/docs/api/rest/applications - */ - public TwilioTRWorkspaceList getWorkspaces(Map filters) { - TwilioTRWorkspaceList twlist = new TwilioTRWorkspaceList(this.getClient(), filters); - twlist.setRequestAccountSid(this.getRequestAccountSid()); - return twlist; - } - - /** - * Returns a given Workspace instance by sid. - */ - public TwilioTRWorkspace getWorkspace(String sid) { - TwilioTRWorkspace workspace = new TwilioTRWorkspace(this.getClient(), sid); - workspace.setRequestAccountSid(this.getRequestAccountSid()); - return workspace; - } - - /** - * Get the Tasks list - * - * @return - */ - public TwilioTRTaskList getTasks(String workspaceSid) { - TwilioTRTaskList twlist = new TwilioTRTaskList(this.getClient(), workspaceSid); - twlist.setRequestAccountSid(this.getRequestAccountSid()); - return twlist; - } - - /** - * Get the TaskQueues list - * - * @return - */ - public TwilioTRTaskQueueList getTaskQueues(String workspaceSid) { - TwilioTRTaskQueueList twlist = new TwilioTRTaskQueueList(this.getClient(), workspaceSid); - twlist.setRequestAccountSid(this.getRequestAccountSid()); - return twlist; - } - - /** - * Get the Workflows list - * - * @return - */ - public TwilioTRWorkflowList getWorkflows(String workspaceSid) { - TwilioTRWorkflowList twlist = new TwilioTRWorkflowList(this.getClient(), workspaceSid); - twlist.setRequestAccountSid(this.getRequestAccountSid()); - return twlist; - } - - /** - * Get the Workers list - * - * @return - */ - public TwilioTRWorkerList getWorkers(String workspaceSid) { - TwilioTRWorkerList twlist = new TwilioTRWorkerList(this.getClient(), workspaceSid); - twlist.setRequestAccountSid(this.getRequestAccountSid()); - return twlist; - } - - /** - * Get the Activities list - * - * @return - */ - public TwilioTRActivitiesList getActivities(String workspaceSid) { - TwilioTRActivitiesList twlist = new TwilioTRActivitiesList(this.getClient(), workspaceSid); - twlist.setRequestAccountSid(this.getRequestAccountSid()); - return twlist; - } } \ No newline at end of file diff --git a/src/classes/TwilioAccountList.cls b/src/classes/TwilioAccountList.cls index d9358e8..b81128e 100644 --- a/src/classes/TwilioAccountList.cls +++ b/src/classes/TwilioAccountList.cls @@ -50,9 +50,9 @@ global class TwilioAccountList extends TwilioResource.ListResource } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, + public override Object makeNew(TwilioClient client, Map params) { - return new TwilioAccount(client, params); + return new TwilioAccount((TwilioRestClient)client, params); } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioApplicationList.cls b/src/classes/TwilioApplicationList.cls index 4c78434..acdaaf2 100644 --- a/src/classes/TwilioApplicationList.cls +++ b/src/classes/TwilioApplicationList.cls @@ -58,9 +58,10 @@ global class TwilioApplicationList extends TwilioResource.ListResource /* * see TwilioResource.ListResource#makeNew() */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioApplication(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioApplication application = new TwilioApplication((TwilioRestClient)client, params); + application.setRequestAccountSid(this.getRequestAccountSid()); + return application; } /* @@ -96,7 +97,7 @@ global class TwilioApplicationList extends TwilioResource.ListResource * @throws TwilioRestException the twilio rest exception */ public boolean deleteResource(String sid) { - TwilioAccount requestAccount = getClient().getAccount(getRequestAccountSid()); + TwilioAccount requestAccount = ((TwilioRestClient)getClient()).getAccount(getRequestAccountSid()); TwilioApplication app = requestAccount.getApplication(sid); return app.deleteResource(); } diff --git a/src/classes/TwilioAuthorizedConnectAppList.cls b/src/classes/TwilioAuthorizedConnectAppList.cls index 356ef89..a171813 100644 --- a/src/classes/TwilioAuthorizedConnectAppList.cls +++ b/src/classes/TwilioAuthorizedConnectAppList.cls @@ -66,9 +66,10 @@ global class TwilioAuthorizedConnectAppList extends TwilioResource.ListResource /* * see TwilioResource.ListResource#makeNew(TwilioRestClient, Map) */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioAuthorizedConnectApp(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioAuthorizedConnectApp connectApp = new TwilioAuthorizedConnectApp((TwilioRestClient)client, params); + connectApp.setRequestAccountSid(this.getRequestAccountSid()); + return connectApp; } /** diff --git a/src/classes/TwilioAvailablePhoneNumber.cls b/src/classes/TwilioAvailablePhoneNumber.cls index e6d8621..e168570 100644 --- a/src/classes/TwilioAvailablePhoneNumber.cls +++ b/src/classes/TwilioAvailablePhoneNumber.cls @@ -148,7 +148,7 @@ global class TwilioAvailablePhoneNumber extends TwilioResource.InstanceResource Map props = new Map(); props.put('PhoneNumber', getPhoneNumber()); - TwilioAccount requestAccount = getClient().getAccount(getRequestAccountSid()); + TwilioAccount requestAccount = ((TwilioRestClient)getClient()).getAccount(getRequestAccountSid()); TwilioIncomingPhoneNumber incoming = requestAccount.getIncomingPhoneNumbers().create(props); this.purchased = true; return incoming; diff --git a/src/classes/TwilioAvailablePhoneNumberList.cls b/src/classes/TwilioAvailablePhoneNumberList.cls index ad841b3..6470f10 100644 --- a/src/classes/TwilioAvailablePhoneNumberList.cls +++ b/src/classes/TwilioAvailablePhoneNumberList.cls @@ -89,9 +89,10 @@ global class TwilioAvailablePhoneNumberList extends TwilioResource.ListResource } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioAvailablePhoneNumber(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioAvailablePhoneNumber available = new TwilioAvailablePhoneNumber((TwilioRestClient)client, params); + available.setRequestAccountSid(this.getRequestAccountSid()); + return available; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioCall.cls b/src/classes/TwilioCall.cls index e6c27b7..421a668 100644 --- a/src/classes/TwilioCall.cls +++ b/src/classes/TwilioCall.cls @@ -190,13 +190,13 @@ global class TwilioCall extends TwilioResource.InstanceResource { } public TwilioNotificationList getNotifications() { - TwilioNotificationList twlist = new TwilioNotificationList(this.getClient(), this.getSid()); + TwilioNotificationList twlist = new TwilioNotificationList((TwilioRestClient)this.getClient(), this.getSid()); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } public TwilioRecordingList getRecordings() { - TwilioRecordingList twlist = new TwilioRecordingList(this.getClient(), this.getSid()); + TwilioRecordingList twlist = new TwilioRecordingList((TwilioRestClient)this.getClient(), this.getSid()); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } @@ -223,7 +223,7 @@ global class TwilioCall extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioCall c = new TwilioCall(this.getClient(), response.toMap()); + TwilioCall c = new TwilioCall((TwilioRestClient)this.getClient(), response.toMap()); c.setRequestAccountSid(this.getRequestAccountSid()); return c; } @@ -240,7 +240,7 @@ global class TwilioCall extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioCall c = new TwilioCall(this.getClient(), response.toMap()); + TwilioCall c = new TwilioCall((TwilioRestClient)this.getClient(), response.toMap()); c.setRequestAccountSid(this.getRequestAccountSid()); return c; } @@ -257,8 +257,25 @@ global class TwilioCall extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioCall c = new TwilioCall(this.getClient(), response.toMap()); + TwilioCall c = new TwilioCall((TwilioRestClient)this.getClient(), response.toMap()); c.setRequestAccountSid(this.getRequestAccountSid()); return c; } + + /** + * Delete this Call. This will remove it from your + * account. + * + * @throws TwilioRestException + * if there is an error in the request + * @return true, if successful + * + */ + public boolean deleteCall() { + TwilioRestResponse response = this.getClient().safeRequest( + this.getResourceLocation(), 'DELETE', null); + + return !response.isError(); + } + } \ No newline at end of file diff --git a/src/classes/TwilioCallList.cls b/src/classes/TwilioCallList.cls index 24cffc2..5ce627c 100644 --- a/src/classes/TwilioCallList.cls +++ b/src/classes/TwilioCallList.cls @@ -35,7 +35,7 @@ global class TwilioCallList extends TwilioResource.ListResource * * @param client the client */ - public TwilioCallList(TwilioRestClient client) { + public TwilioCallList(TwilioClient client) { super(client); } @@ -45,7 +45,7 @@ global class TwilioCallList extends TwilioResource.ListResource * @param client the client * @param filters the filters */ - public TwilioCallList(TwilioRestClient client, Map filters) { + public TwilioCallList(TwilioClient client, Map filters) { super(client, filters); } @@ -56,9 +56,11 @@ global class TwilioCallList extends TwilioResource.ListResource } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioCall(client, params); + public override Object makeNew(TwilioClient client, + Map params) { + TwilioCall call = new TwilioCall((TwilioRestClient)client, params); + call.setRequestAccountSid(this.getRequestAccountSid()); + return call; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioCapability.cls b/src/classes/TwilioCapability.cls index b5dc7ae..089869a 100644 --- a/src/classes/TwilioCapability.cls +++ b/src/classes/TwilioCapability.cls @@ -105,7 +105,7 @@ global class TwilioCapability { */ global void allowEventStream(Map filters) { Map value = new Map(); - value.put('path', '/' + TwilioRestClient.DEFAULT_VERSION + '/Events'); + value.put('path', '/2010-04-01/Events'); if (filters != null) { value.put('params', generateParamString(filters)); } @@ -138,7 +138,7 @@ global class TwilioCapability { Map payload = new Map(); payload.put('iss', this.accountSid); payload.put('exp', String.valueOf(System.currentTimeMillis()/1000 + ttl)); - payload.put('scope', String.join(this.scopes, ' ')); + payload.put('scope', join(this.scopes, ' ')); return jwtEncode(payload, this.authToken); } @@ -197,7 +197,7 @@ global class TwilioCapability { /** * Construct URL-style query param string, e.g. key1=val1&key2=val2&...keyN=valN */ - @TestVisible private static String generateParamString(Map params) { + private static String generateParamString(Map params) { String queryString = ''; Set keySet = params.keySet(); @@ -225,17 +225,17 @@ global class TwilioCapability { segments.add(urlSafeEncodeBase64(JSON.serialize(header))); segments.add(urlSafeEncodeBase64(JSON.serialize(payload))); - String signature = sign(String.join(segments, '.'), key); + String signature = sign(join(segments, '.'), key); segments.add(signature); - return String.join(segments, '.'); + return join(segments, '.'); } - @TestVisible private static String urlSafeEncodeBase64(String data) { + private static String urlSafeEncodeBase64(String data) { return urlSafeEncodeBase64(Blob.valueOf(data)); } - @TestVisible private static String urlSafeEncodeBase64(Blob data) { + private static String urlSafeEncodeBase64(Blob data) { String encodedString = EncodingUtil.base64Encode(data); return encodedString.replace('+','-').replace('/','_').replace('=', ''); // make URL-safe } @@ -243,8 +243,6 @@ global class TwilioCapability { /** * Construct a String containing the contents of 'vals' separated by 'sep' */ - // Now part of built-in String methods in Apex - /* private static String join(List vals, String sep) { String sb = ''; for (Iterator it=vals.iterator(); it.hasNext(); ) { @@ -255,7 +253,6 @@ global class TwilioCapability { } return sb; } - */ /** * Generate a signature for the token @@ -269,6 +266,28 @@ global class TwilioCapability { return result; } + /* UNIT TESTS FOR PRIVATE METHODS */ + static testMethod void testGenerateParamString() { + System.assertEquals('', generateParamString(new Map())); + System.assertEquals('a=b', generateParamString(new Map {'a'=>'b'} )); + System.assertEquals('cat=dog&foo=bar', generateParamString(new Map {'cat' => 'dog', 'foo'=>'bar'} )); + System.assertEquals('a=b&c=d&e=f', generateParamString(new Map {'a'=>'b', 'c'=>'d', 'e'=>'f' } )); + System.assertEquals('split+key1=split+val1&split+key2=split+val2', generateParamString(new Map {'split key1'=>'split val1', 'split key2'=>'split val2'} )); + } + + static testMethod void testEncodeBase64() { + System.assertEquals('',urlSafeEncodeBase64('')); + System.assertEquals('QQ',urlSafeEncodeBase64('A')); + System.assertEquals('QUI',urlSafeEncodeBase64('AB')); + System.assertEquals('QUJDRA',urlSafeEncodeBase64('ABCD')); + } + + static testMethod void testJoin() { + System.assertEquals('', join(new List(),',')); + System.assertEquals('a', join(new List{'a'},',')); + System.assertEquals('a,b,c,d,e', join(new List{'a','b','c','d','e'},',')); + } + /* ACCESSOR METHODS FOR EXTERNAL TESTS */ public boolean test_buildOutgoingScope { diff --git a/src/classes/TwilioCapabilityPolicy.cls b/src/classes/TwilioCapabilityPolicy.cls new file mode 100644 index 0000000..ad625ee --- /dev/null +++ b/src/classes/TwilioCapabilityPolicy.cls @@ -0,0 +1,37 @@ +public class TwilioCapabilityPolicy { + public static final Map required = new Map{'required' => true }; + public static final Map optional = new Map{'required' => false }; + + private String url; + private String method; + public Map> queryFilter {get;set;} + public Map> postFilter {get;set;} + private Boolean allowed; + + public TwilioCapabilityPolicy(String url, String method, Map> queryFilter, Map> postFilter, Boolean allowed) { + this.url = url; + this.method = method; + this.queryFilter = queryFilter; + this.postFilter = postFilter; + this.allowed = allowed; + } + + public TwilioCapabilityPolicy(String url, String method) { + this(url, method, true); + } + + public TwilioCapabilityPolicy(String url, String method, Boolean allowed) { + this(url, method, new Map>(), new Map>(), allowed); + } + + public Map toMap() + { + return new Map { + 'url' => this.url, + 'method' => this.method, + 'query_filter' => this.queryFilter, + 'post_filter' => this.postFilter, + 'allow' => this.allowed + }; + } +} \ No newline at end of file diff --git a/src/classes/TwilioCapabilityPolicy.cls-meta.xml b/src/classes/TwilioCapabilityPolicy.cls-meta.xml new file mode 100644 index 0000000..b12420e --- /dev/null +++ b/src/classes/TwilioCapabilityPolicy.cls-meta.xml @@ -0,0 +1,5 @@ + + + 31.0 + Active + diff --git a/src/classes/TwilioClient.cls b/src/classes/TwilioClient.cls new file mode 100644 index 0000000..25aa90b --- /dev/null +++ b/src/classes/TwilioClient.cls @@ -0,0 +1,716 @@ +/* +Copyright (c) 2012 Twilio, Inc. + +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. +*/ +/** + * The Class TwilioClient. + */ +public abstract class TwilioClient { + + /** The Constant VERSION. */ + private static final String VERSION = '3.3.0'; + + /** The endpoint. */ + private String endpoint = 'https://api.twilio.com'; + + /** The account sid. */ + protected String accountSid; + + /** The auth token. */ + protected String authToken; + + /** The num retries. */ + private Integer numRetries = 3; + + + /** + * Explcitly construct a TwilioRestClient with the given API credentials. + * + * @param accountSid + * the 34 character Account identifier (starting with 'AC'). This + * can be found on your Twilio dashboard page. + * @param authToken + * the 32 character AuthToken. This can be found on your Twilio + * dashboard page. + * + */ + public TwilioClient(String accountSid, String authToken) { + this(accountSid, authToken, null); + } + + /** + * Explcitly construct a TwilioRestClient with the given API credentials and + * endpoint. + * + * @param accountSid + * the 34 character Account identifier (starting with 'AC'). This + * can be found on your Twilio dashboard page. + * @param authToken + * the 32 character AuthToken. This can be found on your Twilio + * dashboard page. + * @param endpoint + * the url of API endpoint you wish to use. (e.g. - + * 'https://api.twilio.com') + */ + public TwilioClient(String accountSid, String authToken, String endpoint) { + + validateAccountSid(accountSid); + validateAuthToken(authToken); + + this.accountSid = accountSid; + this.authToken = authToken; + + if ((endpoint != null) && (!endpoint.equals(''))) { + this.endpoint = endpoint; + } + } + + /** + * Gets the num retries. + * + * @return the num retries + */ + public Integer getNumRetries() { + return numRetries; + } + + /** + * Sets the num retries. + * + * @param numRetries + * the new num retries + */ + public void setNumRetries(Integer numRetries) { + this.numRetries = numRetries; + } + + // Check for a valid 32 character auth token + /** + * Validate auth token. + * + * @param authToken + * the auth token + */ + private void validateAuthToken(String authToken) { + if (authToken == null || authToken.length() != 32) + throw new TwilioRestException('AuthToken \'' + authToken + '\' is not valid.'); + } + + // Check for a valid 34 character account sid starting with 'AC' + /** + * Validate account sid. + * + * @param accountSid + * the account sid + */ + private void validateAccountSid(String accountSid) { + if (accountSid == null || !accountSid.startsWith('AC') || accountSid.length() != 34) + throw new TwilioRestException('AccountSid \'' + accountSid + '\' is not valid. It should be the 34 character unique identifier starting with \'AC\''); + } + + + /* + * + * Method builders + */ + /** + * Builds the method. + * + * @param method + * the method + * @param path + * the path + * @param params + * the params + * @return the http uri request + */ + private HttpRequest buildMethod(String method, String path, + Map params) { + if (method.equalsIgnoreCase('GET')) { + return generateGetRequest(path, params); + } else if (method.equalsIgnoreCase('POST')) { + return generatePostRequest(path, params); + } else if (method.equalsIgnoreCase('PUT')) { + return generatePutRequest(path, params); + } else if (method.equalsIgnoreCase('DELETE')) { + return generateDeleteRequest(path, params); + } else { + throw new TwilioRestException('Unknown Method: ' + method); + } + } + + private HttpRequest buildMethod(String method, String path, List params) + { + if (method.equalsIgnoreCase('GET')) { + return generateGetRequest(path, params); + } else if (method.equalsIgnoreCase('POST')) { + return generatePostRequest(path, params); + } else if (method.equalsIgnoreCase('PUT')) { + return generatePutRequest(path, params); + } else if (method.equalsIgnoreCase('DELETE')) { + return generateDeleteRequest(path, params); + } else { + throw new TwilioRestException('Unknown Method: ' + method); + } + } + + /** + * Generate get request. + * + * @param path + * the path + * @param params + * the params + * @return the http get + */ + private HttpRequest generateGetRequest(String path, Map params) { + + URL uri = buildUri(path, params); + HttpRequest req = new HttpRequest(); + req.setEndpoint(uri.toExternalForm()); + req.setMethod('GET'); + return req; + } + + private HttpRequest generateGetRequest(String path, List params) { + + URL uri = buildUri(path, params); + HttpRequest req = new HttpRequest(); + req.setEndpoint(uri.toExternalForm()); + req.setMethod('GET'); + return req; + } + + /** + * Generate post request. + * + * @param path + * the path + * @param params + * the params + * @return the http post + */ + private HttpRequest generatePostRequest(String path, Map params) { + URL uri = buildUri(path); + + String entity = buildEntityBody(params); + + HttpRequest req = new HttpRequest(); + req.setEndpoint(uri.toExternalForm()); + req.setMethod('POST'); + req.setBody(entity); + + return req; + } + + private HttpRequest generatePostRequest(String path, List params) { + URL uri = buildUri(path); + + String entity = buildEntityBody(params); + + HttpRequest req = new HttpRequest(); + req.setEndpoint(uri.toExternalForm()); + req.setMethod('POST'); + req.setBody(entity); + + return req; + } + /** + * Generate put request. + * + * @param path + * the path + * @param params + * the params + * @return the http put + */ + private HttpRequest generatePutRequest(String path, Map params) { + URL uri = buildUri(path); + + String entity = buildEntityBody(params); + + HttpRequest req = new HttpRequest(); + req.setEndpoint(uri.toExternalForm()); + req.setMethod('PUT'); + req.setBody(entity); + + return req; + } + + private HttpRequest generatePutRequest(String path, List params) { + URL uri = buildUri(path); + + String entity = buildEntityBody(params); + + HttpRequest req = new HttpRequest(); + req.setEndpoint(uri.toExternalForm()); + req.setMethod('PUT'); + req.setBody(entity); + + return req; + } + /** + * Generate delete request. + * + * @param path + * the path + * @param params + * the params + * @return the http delete + */ + private HttpRequest generateDeleteRequest(String path, + Map params) { + URL uri = buildUri(path); + + HttpRequest req = new HttpRequest(); + req.setEndpoint(uri.toExternalForm()); + req.setMethod('DELETE'); + return req; + } + + private HttpRequest generateDeleteRequest(String path,List params) { + URL uri = buildUri(path); + + HttpRequest req = new HttpRequest(); + req.setEndpoint(uri.toExternalForm()); + req.setMethod('DELETE'); + return req; + } + /* + * + * Helper functions for building methods + */ + /** + * Builds the entity body. + * + * @param params + * the params + * @return the url encoded form entity + */ + private String buildEntityBody(Map params) { + String entityBody=''; + if (params != null) { + for (String key : params.keySet()) { + try { + entityBody += (entityBody=='' ? '' : '&') + + key + '=' + EncodingUtil.urlEncode(params.get(key), 'UTF-8'); + } catch (Exception e) { + System.debug('ERROR: ' + e); + } + } + } + return entityBody; + } + + private String buildEntityBody(List params) { + String entityBody=''; + if (params != null) { + for (TwilioNameValuePair param : params) { + try { + entityBody += (entityBody=='' ? '' : '&') + + param.getName() + '=' + EncodingUtil.urlEncode(param.getValue(), 'UTF-8'); + } catch (Exception e) { + System.debug('ERROR: ' + e); + } + } + } + return entityBody; + } + /** + * Builds the uri. + * + * @param path + * the path + * @return the uRI + */ + private URL buildUri(String path) { + return buildUri(path, new Map()); + } + + /** + * Builds the uri. + * + * @param path + * the path + * @param queryStringParams + * the query string params + * @return the uRI + */ + private URL buildUri(String path, Map queryStringParams) { + String sb = path; + + if (queryStringParams != null && queryStringParams.size() > 0) { + sb += '?'; + sb += buildEntityBody(queryStringParams); + } + + URL uri; + try { + uri = new URL(sb); + } catch (Exception e) { + throw new TwilioRestException('Invalid uri: '+sb, e); + } + + return uri; + } + + private URL buildUri(String path, List queryStringParams) { + String sb = path; + + if (queryStringParams != null && queryStringParams.size() > 0) { + sb += '?'; + sb += buildEntityBody(queryStringParams); + } + + URL uri; + try { + uri = new URL(sb); + } catch (Exception e) { + throw new TwilioRestException('Invalid uri: '+sb, e); + } + + return uri; + } + /** + * sendRequst Sends a REST Request to the Twilio REST API. + * + * @param path + * the URL (absolute w.r.t. the endpoint URL - i.e. + * /2010-04-01/Accounts) + * @param method + * the HTTP method to use, defaults to GET + * @param vars + * for POST or PUT, a map of data to send, for GET will be + * appended to the URL as querystring params + * + * This method is public for backwards compatibility with the old + * twilio helper library + * @return the twilio rest response + */ + public TwilioRestResponse request(String path, String method, + Map vars) { + + HttpRequest request = setupRequest(path, method, vars); + + String responseBody; + Integer statusCode; + String contentType; + if (Test.isRunningTest()) { + // can't execute HTTP requests during test execution + system.debug('Request :'+request); + Twilio_TestHTTPMock.Response responseMock = Twilio_TestHTTPMock.getInstance().send(request); + system.debug(responseMock); + responseBody = (responseMock.getBody()==null)?'':responseMock.getBody(); + statusCode = responseMock.getStatusCode(); + contentType = responseMock.getHeader('Content-Type'); + } else { + // execute HTTP request + HttpResponse response = (new Http()).send(request); + responseBody = (response.getBody()==null)?'':response.getBody(); + system.debug(responseBody+'-----------------------------------------'+response); + statusCode = response.getStatusCode(); + contentType = response.getHeader('Content-Type'); + } + TwilioRestResponse restResponse = new TwilioRestResponse(request.getEndpoint(), + responseBody, statusCode); + restResponse.setContentType(contentType); + + return restResponse; + } + + private static List generateParameters(Map vars) + { + List qparams = new List(); + + if (vars != null) + { + for (String var : vars.keySet()) + { + qparams.add(new TwilioNameValuePair(var, vars.get(var))); + } + } + + return qparams; + } + + public TwilioRestResponse request(String path, String method,List paramList) { + + HttpRequest request = setupRequest(path, method, paramList); + + String responseBody; + Integer statusCode; + String contentType; + if (Test.isRunningTest()) { + // can't execute HTTP requests during test execution + system.debug('Request :'+request); + Twilio_TestHTTPMock.Response responseMock = Twilio_TestHTTPMock.getInstance().send(request); + responseBody = (responseMock.getBody()==null)?'':responseMock.getBody(); + statusCode = responseMock.getStatusCode(); + contentType = responseMock.getHeader('Content-Type'); + system.debug('Response Mock :'+responseMock); + } else { + // execute HTTP request + HttpResponse response = (new Http()).send(request); + responseBody = (response.getBody()==null)?'':response.getBody(); + system.debug(responseBody+'-----------------------------------------'+response); + statusCode = response.getStatusCode(); + contentType = response.getHeader('Content-Type'); + } + TwilioRestResponse restResponse = new TwilioRestResponse(request.getEndpoint(), + responseBody, statusCode); + restResponse.setContentType(contentType); + + return restResponse; + } + /** + * Setup request. + * + * @param path + * the path + * @param method + * the method + * @param vars + * the vars + * @return the http uri request + */ + private HttpRequest setupRequest(String path, String method, + Map params) { + + String normalizedPath = path.toLowerCase(); + String sb = ''; + + // If we've given a fully qualified uri then skip building the endpoint + if (normalizedPath.startsWith('http://') + || normalizedPath.startsWith('https://')) { + sb += path; + } else { + sb += this.getEndpoint(); + + if (!normalizedPath.startsWith('/')) { + sb += '/'; + } + sb += path; + } + + path = sb; + + HttpRequest request = buildMethod(method, path, params); + + request.setHeader('X-Twilio-Client', 'salesforce-' + VERSION); + request.setHeader('User-Agent', 'twilio-salesforce/' + VERSION); + request.setHeader('Accept', 'application/json'); + request.setHeader('Accept-Charset', 'utf-8'); + request.setHeader('Authorization', + 'Basic '+EncodingUtil.base64Encode(Blob.valueOf(this.accountSid + ':' + this.authToken))); + + return request; + } + + private HttpRequest setupRequest(String path, String method, + List params) { + + String normalizedPath = path.toLowerCase(); + String sb = ''; + + // If we've given a fully qualified uri then skip building the endpoint + if (normalizedPath.startsWith('http://') + || normalizedPath.startsWith('https://')) { + sb += path; + } else { + sb += this.getEndpoint(); + + if (!normalizedPath.startsWith('/')) { + sb += '/'; + } + sb += path; + } + + path = sb; + + HttpRequest request = buildMethod(method, path, params); + + request.setHeader('X-Twilio-Client', 'salesforce-' + VERSION); + request.setHeader('User-Agent', 'twilio-salesforce-' + VERSION); + request.setHeader('Accept', 'application/json'); + + request.setHeader('Authorization', + 'Basic '+EncodingUtil.base64Encode(Blob.valueOf(this.accountSid + ':' + this.authToken))); + + return request; + } + + /** + * Make a request, handles retries + back-off for server/network errors + * + * @param path + * the URL (absolute w.r.t. the endpoint URL - i.e. + * /2010-04-01/Accounts) + * @param method + * the HTTP method to use, defaults to GET + * @param vars + * for POST or PUT, a map of data to send, for GET will be + * appended to the URL as querystring params + * @return The response + */ + public TwilioRestResponse safeRequest(String path, String method, + Map vars) { + TwilioRestResponse response = null; + for (Integer retry = 0; retry < this.numRetries; retry++) { + response = request(path, method, vars); + if (response.isClientError()) { + System.debug('Twilio REST API Client Error: '+response.getResponseText()); + throw new TwilioRestException(response); + } else if (response.isServerError()) { + // TODO handle backoff scenario + //try { + // Thread.sleep(100 * retry); // Backoff on our sleep + //} catch (Exception e) { + //} + continue; + } + + return response; + } + Integer errorCode = response == null ? -1 : response.getHttpStatus(); + throw new TwilioRestException('Cannot fetch: ' + method + ' ' + path, + errorCode); + } + + public TwilioRestResponse safeRequestPair(String path, String method, + List paramList) + { + TwilioRestResponse response = null; + for (Integer retry = 0; retry < this.numRetries; retry++) + { + response = request(path, method, paramList); + if (response.isClientError()) { + System.debug('Twilio REST API Client Error: '+response.getResponseText()); + throw new TwilioRestException(response); + } else if (response.isServerError()) { + continue; + } + + return response; + } + Integer errorCode = response == null ? -1 : response.getHttpStatus(); + throw new TwilioRestException('Cannot fetch: ' + method + ' ' + path, + errorCode); + } + + /** + * Perform a GET request against the given fully qualified uri. + * + * @param fullUri the full uri, including protocol://hostname/path + * @return the response from the query + */ + public TwilioRestResponse get(String fullUri) { + TwilioRestResponse response = null; + + for (Integer retry = 0; retry < this.numRetries; retry++) { + response = request(fullUri, 'GET', new Map()); + if (response.isClientError()) { + throw new TwilioRestException(response); + } else if (response.isServerError()) { + //try { + // Thread.sleep(100 * retry); // Backoff on our sleep + //} catch (InterruptedException e) { + //} + continue; + } + + return response; + } + Integer errorCode = response == null ? -1 : response.getHttpStatus(); + throw new TwilioRestException('Cannot fetch: ' + fullUri + ' ', + errorCode); + } + + /** + * Get the current endpoint this client is pointed at. + * + * @return String the api endpoint + */ + public String getEndpoint() { + return endpoint; + } + + /** + * Set the endpoint this rest client uses. + * + * @param endpoint + * The location of the endpoint (e.g. https://api.twilio.com) + */ + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } + + + /** + * Validate the signature on an incoming call from Twilio + * + * @param expectedSignature + * The received signature. In an Apex REST method, this will be + * RestContext.request.headers.get('X-Twilio-Signature'). + * + * @param url + * The endpoint URL, for example + * https://mysite.force.com/services/apexrest/twiliosms. + * In an Apex REST method, this will be 'https://' + + * RestContext.request.headers.get('Host') + '/services/apexrest' + + * RestContext.request.requestURI. + * + * @param params + * The params map from the incoming message. In an Apex REST method, + * this will be RestContext.request.params. + * + * @return true if the signature is valid, false otherwise + */ + public boolean validateRequest(String expectedSignature, String url, Map params) { + try { + // sort the params alphabetically, and append the key and value of each to the url + String data = url; + if(params!=null){ + List sortedKeys = new List(params.keySet()); + sortedKeys.sort(); + + for (String s: sortedKeys) { + data += s; + String v=''; + if (params.get(s)!=null) + v=params.get(s); + data += v; + } + } + + //compute the hmac on input data bytes, with AuthToken as key + Blob mac = Crypto.generateMac('hmacSHA1', Blob.valueOf(data), Blob.valueOf(authToken)); + + //base64-encode the hmac + String signature = EncodingUtil.base64Encode(mac); + + return signature.equals(expectedSignature); + } catch (Exception e) { + return false; + } + } +} \ No newline at end of file diff --git a/src/classes/TwilioClient.cls-meta.xml b/src/classes/TwilioClient.cls-meta.xml new file mode 100644 index 0000000..b12420e --- /dev/null +++ b/src/classes/TwilioClient.cls-meta.xml @@ -0,0 +1,5 @@ + + + 31.0 + Active + diff --git a/src/classes/TwilioConference.cls b/src/classes/TwilioConference.cls index 023501b..b123177 100644 --- a/src/classes/TwilioConference.cls +++ b/src/classes/TwilioConference.cls @@ -141,7 +141,7 @@ global class TwilioConference extends TwilioResource.InstanceResource { * @return */ public TwilioParticipantList getParticipants() { - TwilioParticipantList twlist = new TwilioParticipantList(this.getClient(), this.getSid()); + TwilioParticipantList twlist = new TwilioParticipantList((TwilioRestClient)this.getClient(), this.getSid()); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } diff --git a/src/classes/TwilioConferenceList.cls b/src/classes/TwilioConferenceList.cls index 0917d52..b04d25e 100644 --- a/src/classes/TwilioConferenceList.cls +++ b/src/classes/TwilioConferenceList.cls @@ -56,9 +56,10 @@ global class TwilioConferenceList extends TwilioResource.ListResource } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioConference(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioConference conference = new TwilioConference((TwilioRestClient)client, params); + conference.setRequestAccountSid(this.getRequestAccountSid()); + return conference; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioConnectAppList.cls b/src/classes/TwilioConnectAppList.cls index c3c6736..a27f9cf 100644 --- a/src/classes/TwilioConnectAppList.cls +++ b/src/classes/TwilioConnectAppList.cls @@ -62,8 +62,10 @@ global class TwilioConnectAppList extends TwilioResource.ListResource } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, Map params) { - return new TwilioConnectApp(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioConnectApp connect = new TwilioConnectApp((TwilioRestClient)client, params); + connect.setRequestAccountSid(this.getRequestAccountSid()); + return connect; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioIncomingPhoneNumberList.cls b/src/classes/TwilioIncomingPhoneNumberList.cls index 40a2fc8..6aa4428 100644 --- a/src/classes/TwilioIncomingPhoneNumberList.cls +++ b/src/classes/TwilioIncomingPhoneNumberList.cls @@ -57,9 +57,10 @@ global class TwilioIncomingPhoneNumberList extends TwilioResource.ListResource } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioIncomingPhoneNumber(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioIncomingPhoneNumber incoming = new TwilioIncomingPhoneNumber((TwilioRestClient)client, params); + incoming.setRequestAccountSid(this.getRequestAccountSid()); + return incoming; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioIterator.cls b/src/classes/TwilioIterator.cls index 8ffd779..86e67aa 100644 --- a/src/classes/TwilioIterator.cls +++ b/src/classes/TwilioIterator.cls @@ -32,9 +32,9 @@ global class TwilioIterator { /** The itr. */ private Iterator itr; - private TwilioResource.ListResource twlist; + private TwilioResource.TwilioListResource twlist; - protected ObjectIteratorSupport(TwilioResource.ListResource twlist) { + protected ObjectIteratorSupport(TwilioResource.TwilioListResource twlist) { this.itr = twlist.getObjectPageData().iterator(); this.twlist = twlist; } diff --git a/src/classes/TwilioMediaList.cls b/src/classes/TwilioMediaList.cls index ba0081f..8bc6c85 100644 --- a/src/classes/TwilioMediaList.cls +++ b/src/classes/TwilioMediaList.cls @@ -35,8 +35,10 @@ global class TwilioMediaList extends TwilioResource.ListResource implements Iter /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, Map params) { - return new TwilioMedia(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioMedia media = new TwilioMedia((TwilioRestClient)client, params); + media.setRequestAccountSid(this.getRequestAccountSid()); + return media; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioMember.cls b/src/classes/TwilioMember.cls index 511cdc9..18745ba 100644 --- a/src/classes/TwilioMember.cls +++ b/src/classes/TwilioMember.cls @@ -68,7 +68,7 @@ global class TwilioMember extends TwilioResource.InstanceResource vars.put(METHOD, methodInfo); TwilioRestResponse response = this.getClient().safeRequest(this.getResourceLocation(), 'POST', vars); - TwilioMember member = new TwilioMember(this.getClient(), response.toMap(), getQueueSid()); + TwilioMember member = new TwilioMember((TwilioRestClient)this.getClient(), response.toMap(), getQueueSid()); member.setRequestAccountSid(this.getRequestAccountSid()); return member; } diff --git a/src/classes/TwilioMemberList.cls b/src/classes/TwilioMemberList.cls index 7f522cf..47a6e2b 100644 --- a/src/classes/TwilioMemberList.cls +++ b/src/classes/TwilioMemberList.cls @@ -18,8 +18,10 @@ global class TwilioMemberList extends TwilioResource.ListResource implements Ite } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, Map params) { - return new TwilioMember(client, params, queueSid); + public override Object makeNew(TwilioClient client, Map params) { + TwilioMember member = new TwilioMember((TwilioRestClient)client, params, queueSid); + member.setRequestAccountSid(this.getRequestAccountSid()); + return member; } /* implements method from TwilioResource.ListResource */ @@ -48,6 +50,6 @@ global class TwilioMemberList extends TwilioResource.ListResource implements Ite /* implement method from Iterable interface */ global Iterator iterator() { - return new TwilioIterator.MemberIterator(this); + return new TwilioIterator.MemberIterator(this); } } \ No newline at end of file diff --git a/src/classes/TwilioMessage.cls b/src/classes/TwilioMessage.cls index 7a4b874..e46d0c0 100644 --- a/src/classes/TwilioMessage.cls +++ b/src/classes/TwilioMessage.cls @@ -169,7 +169,7 @@ global class TwilioMessage extends TwilioResource.InstanceResource { public TwilioMedia getMedia(String mediaSid) { - TwilioMedia media = new TwilioMedia(this.getClient(), this.getSid(), mediaSid); + TwilioMedia media = new TwilioMedia((TwilioRestClient)this.getClient(), this.getSid(), mediaSid); media.setRequestAccountSid(this.getRequestAccountSid()); return media; } @@ -180,8 +180,45 @@ global class TwilioMessage extends TwilioResource.InstanceResource { * @return the MediaList associated with this message */ public TwilioMediaList getMedia() { - TwilioMediaList media = new TwilioMediaList(this.getClient(), this.getSid()); + TwilioMediaList media = new TwilioMediaList((TwilioRestClient)this.getClient(), this.getSid()); media.setRequestAccountSid(this.getRequestAccountSid()); return media; } + + /** + * Delete this Message. This will remove it from your + * account. + * + * @throws TwilioRestException + * if there is an error in the request + * @return true, if successful + * + */ + public boolean deleteMessage() { + TwilioRestResponse response = this.getClient().safeRequest( + this.getResourceLocation(), 'DELETE', null); + + return !response.isError(); + } + + /** + * Redact this Message. This will remove the body of the message from your + * account. + * + * @throws TwilioRestException + * if there is an error in the request + * @return true, if successful + * + */ + public TwilioMessage redact() { + Map vars = new Map(); + vars.put('Body', ''); + + TwilioRestResponse response = this.getClient().safeRequest( + this.getResourceLocation(), 'POST', vars); + + TwilioMessage message = new TwilioMessage((TwilioRestClient)this.getClient(), response.toMap()); + message.setRequestAccountSid(this.getRequestAccountSid()); + return message; + } } \ No newline at end of file diff --git a/src/classes/TwilioMessageList.cls b/src/classes/TwilioMessageList.cls index bfaf11b..5fefd3a 100644 --- a/src/classes/TwilioMessageList.cls +++ b/src/classes/TwilioMessageList.cls @@ -31,8 +31,10 @@ global class TwilioMessageList extends TwilioResource.ListResource implements It } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, Map params) { - return new TwilioMessage(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioMessage msg = new TwilioMessage((TwilioRestClient)client, params); + msg.setRequestAccountSid(this.getRequestAccountSid()); + return msg; } /* implements method from TwilioResource.ListResource */ @@ -51,7 +53,7 @@ global class TwilioMessageList extends TwilioResource.ListResource implements It } public TwilioMessage create(List params) { - return (TwilioMessage) this.createInstance(params); + return (TwilioMessage) this.createInstance(params); } public List getPageData() { diff --git a/src/classes/TwilioNotificationList.cls b/src/classes/TwilioNotificationList.cls index 871a483..06615fd 100644 --- a/src/classes/TwilioNotificationList.cls +++ b/src/classes/TwilioNotificationList.cls @@ -71,9 +71,10 @@ global class TwilioNotificationList extends TwilioResource.ListResource } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioNotification(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioNotification notification = new TwilioNotification((TwilioRestClient)client, params); + notification.setRequestAccountSid(this.getRequestAccountSid()); + return notification; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioOutgoingCallerIdList.cls b/src/classes/TwilioOutgoingCallerIdList.cls index c980880..76b62d1 100644 --- a/src/classes/TwilioOutgoingCallerIdList.cls +++ b/src/classes/TwilioOutgoingCallerIdList.cls @@ -57,9 +57,10 @@ global class TwilioOutgoingCallerIdList extends TwilioResource.ListResource } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioOutgoingCallerId(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioOutgoingCallerId callerId = new TwilioOutgoingCallerId((TwilioRestClient)client, params); + callerId.setRequestAccountSid(this.getRequestAccountSid()); + return callerId; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioParser.cls b/src/classes/TwilioParser.cls index 3b0c1b4..235dc7d 100644 --- a/src/classes/TwilioParser.cls +++ b/src/classes/TwilioParser.cls @@ -24,162 +24,307 @@ OTHER DEALINGS IN THE SOFTWARE. */ public class TwilioParser { - /** - * Helper method to convert JSON to a canonical object map. - * - * @return a normalized Map of objects. Repeated elements are List values, - * sub-objects are Map values. All other types are String values. - */ - public static Map jsonToMap(String jsonContent) { - - return jsonToMap(JSON.createParser(jsonContent)); - } - - public static List jsonToList(String jsonContent) { - return jsonToList(JSON.createParser(jsonContent)); - } + /** + * Helper method to convert JSON to a canonical object map. + * + * @return a normalized Map of objects. Repeated elements are List values, + * sub-objects are Map values. All other types are String values. + */ + public static Map jsonToMap(String jsonContent) { + + return jsonToMap(JSON.createParser(jsonContent)); + } + + public static List jsonToList(String jsonContent) { + return jsonToList(JSON.createParser(jsonContent)); + } - /** - * Helper method to convert JSON to a canonical object map. - * - * @return a normalized Map of objects. Repeated elements are List values, - * sub-objects are Map values. All other types are String values. - */ - @TestVisible - private static Map jsonToMap(JSONParser parser) { - Map mapped = new Map(); - - System.debug('BEGIN jsonToMap(JSONParser) : currentToken='+parser.getCurrentToken()+', currentName='+parser.getCurrentName()+', text='+parser.getText()); - - if (parser.getCurrentToken()==null) { - parser.nextToken(); // Advance to the start object marker. - } - if (parser.getCurrentToken() != JSONToken.START_OBJECT) { - throw new TwilioParseException('A JSON Object must start with \'{\''); - } - System.debug('PREWHILE jsonToMap(JSONParser) : currentToken='+parser.getCurrentToken()+', currentName='+parser.getCurrentName()+', text='+parser.getText()); - - while (parser.nextToken() != null) { - JSONToken curr = parser.getCurrentToken(); - - System.debug('WHILE jsonToMap(JSONParser) : currentToken='+parser.getCurrentToken()+', currentName='+parser.getCurrentName()+', text='+parser.getText()); + /** + * Helper method to convert JSON to a canonical object map. + * + * @return a normalized Map of objects. Repeated elements are List values, + * sub-objects are Map values. All other types are String values. + */ + private static Map jsonToMap(JSONParser parser) { + Map mapped = new Map(); + + System.debug('BEGIN jsonToMap(JSONParser) : currentToken='+parser.getCurrentToken()+', currentName='+parser.getCurrentName()+', text='+parser.getText()); + + if (parser.getCurrentToken()==null) { + parser.nextToken(); // Advance to the start object marker. + } + if (parser.getCurrentToken() != JSONToken.START_OBJECT) { + throw new TwilioParseException('A JSON Object must start with \'{\''); + } + System.debug('PREWHILE jsonToMap(JSONParser) : currentToken='+parser.getCurrentToken()+', currentName='+parser.getCurrentName()+', text='+parser.getText()); + + while (parser.nextToken() != null) { + JSONToken curr = parser.getCurrentToken(); + + System.debug('WHILE jsonToMap(JSONParser) : currentToken='+parser.getCurrentToken()+', currentName='+parser.getCurrentName()+', text='+parser.getText()); - - if (curr == JSONToken.END_OBJECT) { - // reached end of object - break; - } else if (curr == JSONToken.FIELD_NAME) { - System.debug('FIELD_NAME jsonToMap(JSONParser) : currentToken='+parser.getCurrentToken()+', currentName='+parser.getCurrentName()+', text='+parser.getText()); - - String fieldName = parser.getText(); - curr = parser.nextToken(); - - if (curr == JSONToken.START_OBJECT) { - // value is a JSON object - System.debug('START_OBJECT jsonToMap(JSONParser) : currentToken='+parser.getCurrentToken()+', currentName='+parser.getCurrentName()+', text='+parser.getText()); - mapped.put(fieldName, jsonToMap(parser)); - } else if (curr == JSONToken.START_ARRAY) { - // value is a JSON array - mapped.put(fieldName, jsonToList(parser)); - } else if (curr == JSONToken.VALUE_NULL) { - mapped.put(fieldName, null); - } else { - // value is a JSON primitive - mapped.put(fieldName, parser.getText()); - } - } else { - throw new TwilioParseException('Unexpected JSON value: '+parser.getText()); - } - } - System.debug('RETURN: '+mapped); - return mapped; - } - - @TestVisible - private static List jsonToList(JSONParser parser) { - List jsonArray = new List(); - - if (parser.getCurrentToken()==null) { - parser.nextToken(); // Advance to the start object marker. - } - if (parser.getCurrentToken() != JSONToken.START_ARRAY) { - throw new TwilioParseException('A JSON Array must start with \'[\''); - } - - while (parser.nextValue() != null) { - JSONToken curr = parser.getCurrentToken(); + + if (curr == JSONToken.END_OBJECT) { + // reached end of object + break; + } else if (curr == JSONToken.FIELD_NAME) { + System.debug('FIELD_NAME jsonToMap(JSONParser) : currentToken='+parser.getCurrentToken()+', currentName='+parser.getCurrentName()+', text='+parser.getText()); + + String fieldName = parser.getText(); + curr = parser.nextToken(); + + if (curr == JSONToken.START_OBJECT) { + // value is a JSON object + System.debug('START_OBJECT jsonToMap(JSONParser) : currentToken='+parser.getCurrentToken()+', currentName='+parser.getCurrentName()+', text='+parser.getText()); + mapped.put(fieldName, jsonToMap(parser)); + } else if (curr == JSONToken.START_ARRAY) { + // value is a JSON array + mapped.put(fieldName, jsonToList(parser)); + } else if (curr == JSONToken.VALUE_NULL) { + mapped.put(fieldName, null); + } else { + // value is a JSON primitive + mapped.put(fieldName, parser.getText()); + } + } else { + throw new TwilioParseException('Unexpected JSON value: '+parser.getText()); + } + } + System.debug('RETURN: '+mapped); + return mapped; + } + + private static List jsonToList(JSONParser parser) { + List jsonArray = new List(); + + if (parser.getCurrentToken()==null) { + parser.nextToken(); // Advance to the start object marker. + } + if (parser.getCurrentToken() != JSONToken.START_ARRAY) { + throw new TwilioParseException('A JSON Array must start with \'[\''); + } + + while (parser.nextValue() != null) { + JSONToken curr = parser.getCurrentToken(); if (curr == JSONToken.END_ARRAY) { - break; + break; } else if (curr == JSONToken.START_ARRAY) { jsonArray.add(jsonToList(parser)); } else if (curr == JSONToken.START_OBJECT){ jsonArray.add(jsonToMap(parser)); } else { - jsonArray.add(parser.getText()); + jsonArray.add(parser.getText()); } } return jsonArray; - } - - @TestVisible - private static final Map monthToInteger = - new Map { - 'Jan' => 1, - 'Feb' => 2, - 'Mar' => 3, - 'Apr' => 4, - 'May' => 5, - 'Jun' => 6, - 'Jul' => 7, - 'Aug' => 8, - 'Sep' => 9, - 'Oct' => 10, - 'Nov' => 11, - 'Dec' => 12 - }; - - - public static Datetime parseDatetime(String dateStr) { - if (dateStr==null) - return null; - - // split the original string - String[] tokens = dateStr.split(' ', 0); - //String dayOfWeek = tokens[0]; - Integer day = Integer.valueOf(tokens[1]); - Integer month = monthToInteger.get(tokens[2]); - Integer year = Integer.valueOf(tokens[3]); - String[] timeOfDay = tokens[4].split(':'); - String offset = tokens[5]; - - - // split the time substring - Integer hour = Integer.valueOf( timeOfDay[0] ); - Integer minute = Integer.valueOf( timeOfDay[1] ); - Integer second = Integer.valueOf( timeOfDay[2] ); - - Datetime dt = Datetime.newInstanceGmt( - year, - month, - day, - hour, - minute, - second - ); - - System.debug('DateString = \"'+dateStr+'\", Datetime = '+dt.formatLong()); - return dt; + } + + private static final Map monthToInteger = + new Map { + 'Jan' => 1, + 'Feb' => 2, + 'Mar' => 3, + 'Apr' => 4, + 'May' => 5, + 'Jun' => 6, + 'Jul' => 7, + 'Aug' => 8, + 'Sep' => 9, + 'Oct' => 10, + 'Nov' => 11, + 'Dec' => 12 + }; + + + public static Datetime parseDatetime(String dateStr) { + if (dateStr==null) + return null; + + // split the original string + String[] tokens = dateStr.split(' ', 0); + //String dayOfWeek = tokens[0]; + Integer day = Integer.valueOf(tokens[1]); + Integer month = monthToInteger.get(tokens[2]); + Integer year = Integer.valueOf(tokens[3]); + String[] timeOfDay = tokens[4].split(':'); + String offset = tokens[5]; + + + // split the time substring + Integer hour = Integer.valueOf( timeOfDay[0] ); + Integer minute = Integer.valueOf( timeOfDay[1] ); + Integer second = Integer.valueOf( timeOfDay[2] ); + + Datetime dt = Datetime.newInstanceGmt( + year, + month, + day, + hour, + minute, + second + ); + + System.debug('DateString = \"'+dateStr+'\", Datetime = '+dt.formatLong()); + return dt; } public static String formatDatetime(Datetime dt) { - return dt.format('yyyy-dd-MM'); + return dt.format('yyyy-dd-MM'); } public static String formatFilterDatetime(Integer year, Integer month, Integer dayOfMonth) { - return year+'-'+month+'-'+dayOfMonth; + return year+'-'+month+'-'+dayOfMonth; } - @TestVisible private class TwilioParseException extends Exception {} - + + @isTest + static void test_jsonToList() { + String body = '[ 100, 200, 300, 400 ]'; + List list1 = jsonToList(body); + + System.assertNotEquals(null, list1); + System.assertEquals(4, list1.size()); + System.assertEquals('100', list1[0]); + System.assertEquals('200', list1[1]); + System.assertEquals('300', list1[2]); + System.assertEquals('400', list1[3]); + + TwilioParseException e = null; + JSONParser p = JSON.createParser('{"foo":"bar"}'); + p.nextToken(); // '{' + p.nextToken(); // '"foo"' + try { + jsonToList(p); + } catch (TwilioParseException tpe) { + e = tpe; + } + System.assertNotEquals(null,e); + System.assertEquals('A JSON Array must start with \'[\'', e.getMessage()); + } + + @isTest + static void test_jonToList_NestedList() { + String body = '[ [ "1.1", "1.2" ], [ "2.1", "2.2", "2.3" ] ]'; + List result = jsonToList(body); + + System.assertNotEquals(null, result); + System.assertEquals(2, result.size()); + + System.assert(result[0] instanceof List); + List list1 = (List)result[0]; + System.assertEquals(2, list1.size()); + System.assertEquals('1.1', list1[0]); + System.assertEquals('1.2', list1[1]); + + System.assert(result[1] instanceof List); + List list2 = (List)result[1]; + System.assertEquals('2.1', list2[0]); + System.assertEquals('2.2', list2[1]); + System.assertEquals('2.3', list2[2]); + } + + @isTest + static void test_jsonToMap_Simple() { + String body = '{ "one":100, "two":"200", "three":300 }'; + Map map1 = jsonToMap(body); + + System.assertNotEquals(null, map1); + System.assertEquals(3, map1.size()); + System.assertEquals(true, map1.containsKey('one')); + System.assertEquals('100', map1.get('one')); + System.assertEquals(true, map1.containsKey('two')); + System.assertEquals('200', map1.get('two')); + System.assertEquals(true, map1.containsKey('three')); + System.assertEquals('300', map1.get('three')); + + TwilioParseException e = null; + JSONParser p = JSON.createParser('{"foo":"bar"}'); + p.nextToken(); // '{' + p.nextToken(); // '"foo"' + try { + jsonToMap(p); + } catch (TwilioParseException tpe) { + e = tpe; + } + System.assertNotEquals(null,e); + System.assertEquals('A JSON Object must start with \'{\'', e.getMessage()); + } + + @isTest + static void test_jsonToMap_NestedObject() { + String body = '{ "one":100, "two":"200", "three":{ "a":1, "b":2, "c":3 }, "four":400 }'; + Map map1 = jsonToMap(body); + + System.assertNotEquals(null, map1); + System.assertEquals(4, map1.size()); + System.assertEquals(true, map1.containsKey('one')); + System.assertEquals(true, map1.containsKey('two')); + System.assertEquals(true, map1.containsKey('three')); + System.assertEquals(true, map1.containsKey('four')); + System.assertEquals('100', map1.get('one')); + System.assertEquals('200', map1.get('two')); + System.assert(map1.get('three') instanceof Map); + + Map map2 = (Map)map1.get('three'); + System.assertEquals(3, map2.size()); + System.assertEquals(true, map2.containsKey('a')); + System.assertEquals(true, map2.containsKey('b')); + System.assertEquals(true, map2.containsKey('c')); + System.assertEquals('1', map2.get('a')); + System.assertEquals('2', map2.get('b')); + System.assertEquals('3', map2.get('c')); + } + + @isTest + static void test_jsonToMap_NestedArray() { + String body = '{ "one":{ "a":1, "b":2, "c":3 }, "two":[{"a":1,"b":2}, {"foo":1,"bar":2,"cat":3}] }'; + + Map map1 = jsonToMap(body); + System.assertEquals(2, map1.size()); + System.assertEquals(true, map1.containsKey('one')); + System.assertEquals(true, map1.containsKey('two')); + + Map map2 = (Map)map1.get('one'); + System.assertEquals(3, map2.size()); + System.assertEquals(true, map2.containsKey('a')); + System.assertEquals(true, map2.containsKey('b')); + System.assertEquals(true, map2.containsKey('c')); + System.assertEquals('1', map2.get('a')); + System.assertEquals('2', map2.get('b')); + System.assertEquals('3', map2.get('c')); + + List list1 = (List)map1.get('two'); + System.assertEquals(2, list1.size()); + + Map list1map1 = (Map)list1[0]; + System.assertEquals(2, list1map1.size()); + System.assertEquals(true, list1map1.containsKey('a')); + System.assertEquals(true, list1map1.containsKey('b')); + System.assertEquals('1', list1map1.get('a')); + System.assertEquals('2', list1map1.get('b')); + + Map list1map2 = (Map)list1[1]; + System.assertEquals(3, list1map2.size()); + System.assertEquals(true, list1map2.containsKey('foo')); + System.assertEquals(true, list1map2.containsKey('bar')); + System.assertEquals(true, list1map2.containsKey('cat')); + System.assertEquals('1', list1map2.get('foo')); + System.assertEquals('2', list1map2.get('bar')); + System.assertEquals('3', list1map2.get('cat')); + + } + + @isTest + static void test_parseDateTime() + { + System.assertEquals(null, parseDateTime(null)); + System.assertEquals(Datetime.newInstanceGmt(2001, 01, 14, 18, 19, 20), + parseDatetime('Mon, 14 Jan 2001 18:19:20 +0000')); + System.assertEquals(Datetime.newInstanceGmt(2005, 8, 1, 3, 45, 53), + parseDatetime('Tue, 01 Aug 2005 03:45:53 +0000')); + System.assertEquals(Datetime.newInstanceGmt(2022, 12, 29, 12, 1, 1), + parseDatetime('Wed, 29 Dec 2022 12:01:01 +0000')); + + } } \ No newline at end of file diff --git a/src/classes/TwilioParticipant.cls b/src/classes/TwilioParticipant.cls index 91ab2ae..e3141cb 100644 --- a/src/classes/TwilioParticipant.cls +++ b/src/classes/TwilioParticipant.cls @@ -173,7 +173,7 @@ global class TwilioParticipant extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioParticipant p = new TwilioParticipant(this.getClient(), response.toMap()); + TwilioParticipant p = new TwilioParticipant((TwilioRestClient)this.getClient(), response.toMap()); p.setRequestAccountSid(this.getRequestAccountSid()); return p; } @@ -191,7 +191,7 @@ global class TwilioParticipant extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioParticipant p = new TwilioParticipant(this.getClient(), response.toMap()); + TwilioParticipant p = new TwilioParticipant((TwilioRestClient)this.getClient(), response.toMap()); p.setRequestAccountSid(this.getRequestAccountSid()); return p; } diff --git a/src/classes/TwilioParticipantList.cls b/src/classes/TwilioParticipantList.cls index 7ed3c63..dff0144 100644 --- a/src/classes/TwilioParticipantList.cls +++ b/src/classes/TwilioParticipantList.cls @@ -71,9 +71,10 @@ global class TwilioParticipantList extends TwilioResource.ListResource } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioParticipant(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioParticipant participant = new TwilioParticipant((TwilioRestClient)client, params); + participant.setRequestAccountSid(this.getRequestAccountSid()); + return participant; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioQueue.cls b/src/classes/TwilioQueue.cls index 99791be..4cc8b40 100644 --- a/src/classes/TwilioQueue.cls +++ b/src/classes/TwilioQueue.cls @@ -63,19 +63,19 @@ global class TwilioQueue extends TwilioResource.InstanceResource public TwilioMemberList getMembers() { - TwilioMemberList memberlist = new TwilioMemberList(this.getClient(), this.getSid()); + TwilioMemberList memberlist = new TwilioMemberList((TwilioRestClient)this.getClient(), this.getSid()); memberlist.setRequestAccountSid(this.getRequestAccountSid()); return memberlist; } public TwilioMember getMember(String callSid) { - TwilioMember member = new TwilioMember(this.getClient(), this.getSid(), callSid); + TwilioMember member = new TwilioMember((TwilioRestClient)this.getClient(), this.getSid(), callSid); member.setRequestAccountSid(this.getRequestAccountSid()); return member; } public TwilioMember dequeueHeadOfQueue(String url, String method){ - TwilioMember m = new TwilioMember(this.getClient(), this.getSid()); + TwilioMember m = new TwilioMember((TwilioRestClient)this.getClient(), this.getSid()); m.setRequestAccountSid(this.getRequestAccountSid()); return m.dequeue(url, method); } diff --git a/src/classes/TwilioQueueList.cls b/src/classes/TwilioQueueList.cls index f20e5c1..19497f2 100644 --- a/src/classes/TwilioQueueList.cls +++ b/src/classes/TwilioQueueList.cls @@ -17,8 +17,10 @@ global class TwilioQueueList extends TwilioResource.ListResource implements Iter return (TwilioQueue) this.createInstance(params); } - public override Object makeNew(TwilioRestClient client, Map params) { - return new TwilioQueue(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioQueue q = new TwilioQueue((TwilioRestClient)client, params); + q.setRequestAccountSid(this.getRequestAccountSid()); + return q; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioRecording.cls b/src/classes/TwilioRecording.cls index 495961b..ed9d548 100644 --- a/src/classes/TwilioRecording.cls +++ b/src/classes/TwilioRecording.cls @@ -154,7 +154,7 @@ global class TwilioRecording extends TwilioResource.InstanceResource { } public TwilioTranscriptionList getTranscriptions() { - TwilioTranscriptionList twlist = new TwilioTranscriptionList(this.getClient(), this.getSid()); + TwilioTranscriptionList twlist = new TwilioTranscriptionList((TwilioRestClient)this.getClient(), this.getSid()); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } diff --git a/src/classes/TwilioRecordingList.cls b/src/classes/TwilioRecordingList.cls index db98096..3ba50cc 100644 --- a/src/classes/TwilioRecordingList.cls +++ b/src/classes/TwilioRecordingList.cls @@ -28,85 +28,86 @@ OTHER DEALINGS IN THE SOFTWARE. * For more information see http://www.twilio.com/docs/api/rest/recording */ global class TwilioRecordingList extends TwilioResource.ListResource - implements Iterable { + implements Iterable { - private String parentCallSid; + private String parentCallSid; - /** - * Instantiates a new recording list. - * - * @param client the client - */ - public TwilioRecordingList(TwilioRestClient client) { - super(client); - } + /** + * Instantiates a new recording list. + * + * @param client the client + */ + public TwilioRecordingList(TwilioRestClient client) { + super(client); + } - /** - * Instantiates a new recording list. - * - * @param client the client - * @param filters the filters - */ - public TwilioRecordingList(TwilioRestClient client, Map filters) { - super(client, filters); - } - - /** - * Instantiates a new recording list under a Call resource. - * - * @param client the client - * @param filters the filters - */ - public TwilioRecordingList(TwilioRestClient client, String parentCallSid) { - super(client); - this.parentCallSid = parentCallSid; - } + /** + * Instantiates a new recording list. + * + * @param client the client + * @param filters the filters + */ + public TwilioRecordingList(TwilioRestClient client, Map filters) { + super(client, filters); + } + + /** + * Instantiates a new recording list under a Call resource. + * + * @param client the client + * @param filters the filters + */ + public TwilioRecordingList(TwilioRestClient client, String parentCallSid) { + super(client); + this.parentCallSid = parentCallSid; + } - /* implements method from TwilioResource */ - public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() - + (this.parentCallSid!=null ? ('/Calls/'+this.parentCallSid) : '') - + '/Recordings.json'; - } + /* implements method from TwilioResource */ + public override String getResourceLocation() { + return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' + + this.getRequestAccountSid() + + (this.parentCallSid!=null ? ('/Calls/'+this.parentCallSid) : '') + + '/Recordings.json'; + } - /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioRecording(client, params); - } + /* implements method from TwilioResource.ListResource */ + public override Object makeNew(TwilioClient client, Map params) { + TwilioRecording recording = new TwilioRecording((TwilioRestClient)client, params); + recording.setRequestAccountSid(this.getRequestAccountSid()); + return recording; + } - /* implements method from TwilioResource.ListResource */ - public override String getListKey() { - return 'recordings'; - } - - /* returns the current response results page */ - public List getPageData() { - List returnList = new List(); - - for (Object o : this.getObjectPageData()) { - if (o instanceof TwilioRecording) { - returnList.add((TwilioRecording) o); - } - } - return returnList; - } - - /* returns an iterator spanning all data pages */ - global Iterator iterator() { - return new TwilioIterator.RecordingIterator(this); - } - - /** - * Delete. - * - * @return true, if successful - * @throws TwilioRestException the twilio rest exception - */ - public boolean deleteResource(String sid) { - TwilioAccount requestAccount = getClient().getAccount(getRequestAccountSid()); - TwilioRecording rec = requestAccount.getRecording(sid); - return rec.deleteResource(); - } + /* implements method from TwilioResource.ListResource */ + public override String getListKey() { + return 'recordings'; + } + + /* returns the current response results page */ + public List getPageData() { + List returnList = new List(); + + for (Object o : this.getObjectPageData()) { + if (o instanceof TwilioRecording) { + returnList.add((TwilioRecording) o); + } + } + return returnList; + } + + /* returns an iterator spanning all data pages */ + global Iterator iterator() { + return new TwilioIterator.RecordingIterator(this); + } + + /** + * Delete. + * + * @return true, if successful + * @throws TwilioRestException the twilio rest exception + */ + public boolean deleteResource(String sid) { + TwilioAccount requestAccount = ((TwilioRestClient)getClient()).getAccount(getRequestAccountSid()); + TwilioRecording rec = requestAccount.getRecording(sid); + return rec.deleteResource(); + } } \ No newline at end of file diff --git a/src/classes/TwilioResource.cls b/src/classes/TwilioResource.cls index 8afb074..a9154b4 100644 --- a/src/classes/TwilioResource.cls +++ b/src/classes/TwilioResource.cls @@ -26,7 +26,7 @@ public abstract class TwilioResource { /** The HTTP client. */ - private TwilioRestClient client; + private TwilioClient client; /** The request account sid. */ private String requestAccountSid; @@ -39,7 +39,7 @@ public abstract class TwilioResource * * @param client the client */ - public TwilioResource(TwilioRestClient client) { + public TwilioResource(TwilioClient client) { this.client = client; } @@ -48,7 +48,7 @@ public abstract class TwilioResource * * @return the client */ - protected TwilioRestClient getClient() { + protected TwilioClient getClient() { return this.client; } @@ -80,7 +80,6 @@ public abstract class TwilioResource protected void load(Map params) { String path = this.getResourceLocation(); TwilioRestResponse response = this.getClient().safeRequest(path, 'GET', params); - this.parseResponse(response); this.loaded = true; } @@ -132,14 +131,18 @@ public abstract class TwilioResource /** The properties. */ private Map properties; + /** The params. */ + private Map params; + /** * Instantiates a new instance resource. * * @param client the client */ - public InstanceResource(TwilioRestClient client) { + public InstanceResource(TwilioClient client) { super(client); this.properties = new Map(); + this.params = new Map(); } /** @@ -148,13 +151,26 @@ public abstract class TwilioResource * @param client the client * @param properties the properties */ - public InstanceResource(TwilioRestClient client, + public InstanceResource(TwilioClient client, Map properties) { super(client); this.properties = new Map(properties); + this.params = new Map(); this.setLoaded(true); } - + + /** + * Instantiates a new instance resource. + * + * @param client the client + * @param params the parameters for the instance resource + */ + public InstanceResource(TwilioClient client, Map params) { + super(client); + this.properties = new Map(); + this.params = new Map(params); + } + /** * Gets the property. * @@ -166,7 +182,7 @@ public abstract class TwilioResource Object prop = properties.get(name); if (prop == null && !this.isLoaded()) { - this.load(new Map()); + this.load(params); } prop = properties.get(name); @@ -206,8 +222,6 @@ public abstract class TwilioResource protected Datetime getPropertyISODatetime(String name) { DateTime dt = (DateTime) JSON.deserialize('"' + getProperty(name) + '"', DateTime.class); - system.debug('Date to Parse:' + name); - system.debug(dt); return DateTime.newInstance( dt.getTime()); } @@ -222,7 +236,7 @@ public abstract class TwilioResource protected Object getObject(String name) { Object prop = properties.get(name); if (prop == null && !this.isLoaded()) { - this.load(new Map()); + this.load(params); } prop = properties.get(name); @@ -278,7 +292,165 @@ public abstract class TwilioResource } } - public abstract class ListResource extends TwilioResource { + + public abstract class TwilioListResource extends TwilioResource { + /** The page data. */ + public List pageData; + + /** + * Instantiates a new list resource. + * + * @param client the client + */ + public TwilioListResource(TwilioClient client) { + this(client, new Map()); + } + + /** + * Instantiates a new list resource. + * + * @param client the client + * @param filters the filters + */ + public TwilioListResource(TwilioClient client, Map filters) { + super(client); + this.filters = filters; + } + + + /** + * Gets the page. + * + * @return the page + */ + public abstract Integer getPage(); + + /** + * Checks for next page. + * + * @return true, if successful + */ + public abstract boolean hasNextPage(); + + /** + * Fetch next page. + * + * @throws TwilioRestException the twilio rest exception + */ + public abstract void fetchNextPage(); + + /** + * Checks for prev page. + * + * @return true, if successful + */ + public abstract boolean hasPrevPage(); + + /** + * Fetch prev page. + * + * @throws TwilioRestException the twilio rest exception + */ + public abstract void fetchPrevPage(); + + + /** + * Gets the Integer value. + * + * @param data the data + * @return the Integer value + */ + private Integer getIntValue(Object data) { + if (data instanceof Integer) { + return (Integer) data; + } + if (data instanceof String) { + return Integer.valueOf((String) data); + } + + return -1; + } + + /** + * To list. + * + * @param response the response + * @return the list + */ + protected List toList(TwilioRestResponse response) { + List returnList = new List(); + + // Right now only json responses are used + Map m = response.toMap(); + + if (m.get(this.getListKey()) instanceof List) { + List objs = (List) m.get(this.getListKey()); + system.debug(m+'----------------------------'+this.getListKey()); + for (Object o : objs) { + if (o instanceof Map) { + Object instance = this.makeNew(this.getClient(), + (Map) o); + returnList.add(instance); + } + } + } + return returnList; + } + + /* implements method from TwilioResource.ListResource */ + public Object createInstance(Map params) { + TwilioRestResponse response = this.getClient().safeRequest( + this.getResourceLocation(), 'POST', params); + return makeNew(this.getClient(), response.toMap()); + } + + /* implements method from TwilioResource.ListResource */ + public Object createInstance(List params) { + TwilioRestResponse response = this.getClient().safeRequestPair( + this.getResourceLocation(), 'POST', params); + return makeNew(this.getClient(), response.toMap()); + } + + /** + * Gets the page data. + * + * @return the page data + */ + public List getObjectPageData() { + if (!this.isLoaded()) { + this.load(this.filters); + } + + return this.pageData; + } + + /** + * Returns the string key for finding this list of objects in the response. + * For example: + * + * + * + * + * this should return "Accounts" + * + * @return the string key for finding this list objects in the response + */ + protected abstract String getListKey(); + + /** + * Create a new object of type Object. + * + * @param client the client + * @param params the params + * @return a fully constructed object of type Object + */ + protected abstract Object makeNew(TwilioClient client, + Map params); + } + + + public abstract class ListResource extends TwilioListResource { + private final String PREV_PAGE_URI_KEY_JSON = 'previous_page_uri'; private final String NEXT_PAGE_URI_KEY_JSON = 'next_page_uri'; private final String START_KEY_JSON = 'start'; private final String END_KEY_JSON = 'end'; @@ -286,9 +458,9 @@ public abstract class TwilioResource private final String NUM_PAGES_KEY_JSON = 'num_pages'; private final String TOTAL_KEY_JSON = 'total'; - /** The page data. */ - public List pageData; - + /** The prev uri. */ + private String prevUri = null; + /** The next uri. */ private String nextUri = null; @@ -312,7 +484,7 @@ public abstract class TwilioResource * * @param client the client */ - public ListResource(TwilioRestClient client) { + public ListResource(TwilioClient client) { this(client, new Map()); } @@ -322,7 +494,7 @@ public abstract class TwilioResource * @param client the client * @param filters the filters */ - public ListResource(TwilioRestClient client, Map filters) { + public ListResource(TwilioClient client, Map filters) { super(client); this.filters = filters; } @@ -377,7 +549,7 @@ public abstract class TwilioResource * * @return the page */ - public Integer getPage() { + public override Integer getPage() { return page; } @@ -386,27 +558,47 @@ public abstract class TwilioResource * * @return true, if successful */ - public boolean hasNextPage() { + public override boolean hasNextPage() { return nextUri != null && this.nextUri.length() > 0; } - + + /** + * Checks for prev page. + * + * @return true, if successful + */ + public override boolean hasPrevPage() { + return prevUri != null && this.prevUri.length() > 0; + } + /** * Fetch next page. * * @throws TwilioRestException the twilio rest exception */ - public void fetchNextPage() { + public override void fetchNextPage() { // Fetch the next page and reset accounts TwilioRestResponse response = this.getClient().get(nextUri); this.parseResponse(response); } - + + /** + * Fetch prev page. + * + * @throws TwilioRestException the twilio rest exception + */ + public override void fetchPrevPage() { + // Fetch the next page and reset accounts + TwilioRestResponse response = this.getClient().get(prevUri); + this.parseResponse(response); + } + protected override void parseResponse(TwilioRestResponse response) { this.nextUri = null; // Setup paging Map data = response.toMap(); this.nextUri = (String) data.get(NEXT_PAGE_URI_KEY_JSON); - + this.prevUri = (String) data.get(PREV_PAGE_URI_KEY_JSON); this.startIx = this.getIntValue(data.get(START_KEY_JSON)); this.endIx = this.getIntValue(data.get(END_KEY_JSON)); this.page = this.getIntValue(data.get(PAGE_KEY_JSON)); @@ -416,99 +608,134 @@ public abstract class TwilioResource // Setup data this.pageData = this.toList(response); } + } + + public abstract class NextGenListResource extends TwilioListResource { + private final String FIRST_PAGE_URL_JSON = 'first_page_url'; + private final String NEXT_PAGE_URL_JSON = 'next_page_url'; + private final String PREV_PAGE_URL_JSON = 'previous_page_url'; + private final String PAGE_JSON = 'page'; + private final String PAGE_SIZE_JSON = 'page_size'; + private final String URL_JSON = 'url'; + private final String KEY_JSON = 'key'; + + + /** The first url. */ + private String firstUrl = null; + + /** The next url. */ + private String nextUrl = null; + + /** The prev url. */ + private String prevUrl = null; + + /** The page. */ + private Integer page = 0; + + /** The page size. */ + private Integer pageSize = 0; + + /** The url. */ + private String pageUrl = null; + + /** The key */ + private String key = null; /** - * Gets the Integer value. + * Instantiates a new list resource. * - * @param data the data - * @return the Integer value + * @param client the client */ - private Integer getIntValue(Object data) { - if (data instanceof Integer) { - return (Integer) data; - } - if (data instanceof String) { - return Integer.valueOf((String) data); - } + public NextGenListResource(TwilioClient client) { + this(client, new Map()); + } - return -1; + /** + * Instantiates a new list resource. + * + * @param client the client + * @param filters the filters + */ + public NextGenListResource(TwilioClient client, Map filters) { + super(client); + this.filters = filters; } /** - * To list. + * Gets the next uri. * - * @param response the response - * @return the list + * @return the next uri */ - protected List toList(TwilioRestResponse response) { - List returnList = new List(); - - // Right now only json responses are used - Map m = response.toMap(); + public String getNextUrl() { + return nextUrl; + } - if (m.get(this.getListKey()) instanceof List) { - List objs = (List) m.get(this.getListKey()); - system.debug(m+'----------------------------'+this.getListKey()); - for (Object o : objs) { - if (o instanceof Map) { - Object instance = this.makeNew(this.getClient(), - (Map) o); - returnList.add(instance); - } - } - } - return returnList; + /** + * Gets the page. + * + * @return the page + */ + public override Integer getPage() { + return page; } - - /* implements method from TwilioResource.ListResource */ - public Object createInstance(Map params) { - TwilioRestResponse response = this.getClient().safeRequest( - this.getResourceLocation(), 'POST', params); - return makeNew(this.getClient(), response.toMap()); + + + + /** + * Checks for next page. + * + * @return true, if successful + */ + public override boolean hasNextPage() { + return nextUrl != null && this.nextUrl.length() > 0; } - - /* implements method from TwilioResource.ListResource */ - public Object createInstance(List params) { - TwilioRestResponse response = this.getClient().safeRequestPair( - this.getResourceLocation(), 'POST', params); - return makeNew(this.getClient(), response.toMap()); - } - + /** - * Gets the page data. + * Fetch next page. * - * @return the page data + * @throws TwilioRestException the twilio rest exception */ - public List getObjectPageData() { - if (!this.isLoaded()) { - this.load(this.filters); - } - - return this.pageData; + public override void fetchNextPage() { + // Fetch the next page and reset accounts + TwilioRestResponse response = this.getClient().get(nextUrl); + this.parseResponse(response); } - + /** - * Returns the string key for finding this list of objects in the response. - * For example: - * - * - * - * - * this should return "Accounts" - * - * @return the string key for finding this list objects in the response + * Checks for next page. + * + * @return true, if successful */ - protected abstract String getListKey(); - + public override boolean hasPrevPage() { + return prevUrl != null && this.prevUrl.length() > 0; + } + /** - * Create a new object of type Object. + * Fetch next page. * - * @param client the client - * @param params the params - * @return a fully constructed object of type Object + * @throws TwilioRestException the twilio rest exception */ - protected abstract Object makeNew(TwilioRestClient client, - Map params); + public override void fetchPrevPage() { + // Fetch the next page and reset accounts + TwilioRestResponse response = this.getClient().get(prevUrl); + this.parseResponse(response); + } + + protected override void parseResponse(TwilioRestResponse response) { + this.nextUrl = null; + + // Setup paging + Map data = response.toMap(); + Map meta = (Map) data.get('meta'); + this.firstUrl = (String) meta.get(FIRST_PAGE_URL_JSON); + this.nextUrl = (String) meta.get(NEXT_PAGE_URL_JSON); + this.prevUrl = (String) meta.get(PREV_PAGE_URL_JSON); + this.page = this.getIntValue(meta.get(PAGE_JSON)); + this.pageSize = this.getIntValue(meta.get(PAGE_SIZE_JSON)); + this.pageUrl = (String) meta.get(URL_JSON); + this.key = (String) meta.get(KEY_JSON); + // Setup data + this.pageData = this.toList(response); + } } - } \ No newline at end of file diff --git a/src/classes/TwilioRestClient.cls b/src/classes/TwilioRestClient.cls index 2e3497b..ef85e05 100644 --- a/src/classes/TwilioRestClient.cls +++ b/src/classes/TwilioRestClient.cls @@ -25,29 +25,13 @@ OTHER DEALINGS IN THE SOFTWARE. /** * The Class TwilioRestClient. */ -public class TwilioRestClient { - - /** The Constant VERSION. */ - private static final String VERSION = '3.2.0'; - - /** The endpoint. */ - private String endpoint = 'https://api.twilio.com'; - - /** The Constant DEFAULT_VERSION. */ +public class TwilioRestClient extends TwilioClient{ public static final String DEFAULT_VERSION = '2010-04-01'; - /** The account sid. */ - private String accountSid; - - /** The auth token. */ - private String authToken; - - /** The num retries. */ - private Integer numRetries = 3; - /** The auth account. */ private TwilioAccount authAccount; + /** * Explcitly construct a TwilioRestClient with the given API credentials. * @@ -60,9 +44,13 @@ public class TwilioRestClient { * */ public TwilioRestClient(String accountSid, String authToken) { - this(accountSid, authToken, null); + super(accountSid, authToken, 'https://api.twilio.com'); + this.authAccount = new TwilioAccount(this); + this.authAccount.setSid(accountSid); + this.authAccount.setAuthToken(authToken); } + /** * Explcitly construct a TwilioRestClient with the given API credentials and * endpoint. @@ -78,600 +66,12 @@ public class TwilioRestClient { * 'https://api.twilio.com') */ public TwilioRestClient(String accountSid, String authToken, String endpoint) { - - validateAccountSid(accountSid); - validateAuthToken(authToken); - - this.accountSid = accountSid; - this.authToken = authToken; - - if ((endpoint != null) && (!endpoint.equals(''))) { - this.endpoint = endpoint; - } + super(accountSid, authToken, endpoint); this.authAccount = new TwilioAccount(this); - this.authAccount.setSid(this.accountSid); - this.authAccount.setAuthToken(this.authToken); - - } - - /** - * Gets the num retries. - * - * @return the num retries - */ - public Integer getNumRetries() { - return numRetries; - } - - /** - * Sets the num retries. - * - * @param numRetries - * the new num retries - */ - public void setNumRetries(Integer numRetries) { - this.numRetries = numRetries; - } - - // Check for a valid 32 character auth token - /** - * Validate auth token. - * - * @param authToken - * the auth token - */ - private void validateAuthToken(String authToken) { - if (authToken == null || authToken.length() != 32) - throw new TwilioRestException('AuthToken \'' + authToken + '\' is not valid.'); - } - - // Check for a valid 34 character account sid starting with 'AC' - /** - * Validate account sid. - * - * @param accountSid - * the account sid - */ - private void validateAccountSid(String accountSid) { - if (accountSid == null || !accountSid.startsWith('AC') || accountSid.length() != 34) - throw new TwilioRestException('AccountSid \'' + accountSid + '\' is not valid. It should be the 34 character unique identifier starting with \'AC\''); - } - - - /* - * - * Method builders - */ - /** - * Builds the method. - * - * @param method - * the method - * @param path - * the path - * @param params - * the params - * @return the http uri request - */ - private HttpRequest buildMethod(String method, String path, - Map params) { - if (method.equalsIgnoreCase('GET')) { - return generateGetRequest(path, params); - } else if (method.equalsIgnoreCase('POST')) { - return generatePostRequest(path, params); - } else if (method.equalsIgnoreCase('PUT')) { - return generatePutRequest(path, params); - } else if (method.equalsIgnoreCase('DELETE')) { - return generateDeleteRequest(path, params); - } else { - throw new TwilioRestException('Unknown Method: ' + method); - } - } - - private HttpRequest buildMethod(String method, String path, List params) - { - if (method.equalsIgnoreCase('GET')) { - return generateGetRequest(path, params); - } else if (method.equalsIgnoreCase('POST')) { - return generatePostRequest(path, params); - } else if (method.equalsIgnoreCase('PUT')) { - return generatePutRequest(path, params); - } else if (method.equalsIgnoreCase('DELETE')) { - return generateDeleteRequest(path, params); - } else { - throw new TwilioRestException('Unknown Method: ' + method); - } - } - - /** - * Generate get request. - * - * @param path - * the path - * @param params - * the params - * @return the http get - */ - private HttpRequest generateGetRequest(String path, Map params) { - - URL uri = buildUri(path, params); - HttpRequest req = new HttpRequest(); - req.setEndpoint(uri.toExternalForm()); - req.setMethod('GET'); - return req; - } - - private HttpRequest generateGetRequest(String path, List params) { - - URL uri = buildUri(path, params); - HttpRequest req = new HttpRequest(); - req.setEndpoint(uri.toExternalForm()); - req.setMethod('GET'); - return req; - } - - /** - * Generate post request. - * - * @param path - * the path - * @param params - * the params - * @return the http post - */ - private HttpRequest generatePostRequest(String path, Map params) { - URL uri = buildUri(path); - - String entity = buildEntityBody(params); - - HttpRequest req = new HttpRequest(); - req.setEndpoint(uri.toExternalForm()); - req.setMethod('POST'); - req.setBody(entity); - - return req; - } - - private HttpRequest generatePostRequest(String path, List params) { - URL uri = buildUri(path); - - String entity = buildEntityBody(params); - - HttpRequest req = new HttpRequest(); - req.setEndpoint(uri.toExternalForm()); - req.setMethod('POST'); - req.setBody(entity); - - return req; - } - /** - * Generate put request. - * - * @param path - * the path - * @param params - * the params - * @return the http put - */ - private HttpRequest generatePutRequest(String path, Map params) { - URL uri = buildUri(path); - - String entity = buildEntityBody(params); - - HttpRequest req = new HttpRequest(); - req.setEndpoint(uri.toExternalForm()); - req.setMethod('PUT'); - req.setBody(entity); - - return req; - } - - private HttpRequest generatePutRequest(String path, List params) { - URL uri = buildUri(path); - - String entity = buildEntityBody(params); - - HttpRequest req = new HttpRequest(); - req.setEndpoint(uri.toExternalForm()); - req.setMethod('PUT'); - req.setBody(entity); - - return req; - } - /** - * Generate delete request. - * - * @param path - * the path - * @param params - * the params - * @return the http delete - */ - private HttpRequest generateDeleteRequest(String path, - Map params) { - URL uri = buildUri(path); - - HttpRequest req = new HttpRequest(); - req.setEndpoint(uri.toExternalForm()); - req.setMethod('DELETE'); - return req; - } - - private HttpRequest generateDeleteRequest(String path,List params) { - URL uri = buildUri(path); - - HttpRequest req = new HttpRequest(); - req.setEndpoint(uri.toExternalForm()); - req.setMethod('DELETE'); - return req; - } - /* - * - * Helper functions for building methods - */ - /** - * Builds the entity body. - * - * @param params - * the params - * @return the url encoded form entity - */ - private String buildEntityBody(Map params) { - String entityBody=''; - if (params != null) { - for (String key : params.keySet()) { - try { - entityBody += (entityBody=='' ? '' : '&') - + key + '=' + EncodingUtil.urlEncode(params.get(key), 'UTF-8'); - } catch (Exception e) { - System.debug('ERROR: ' + e); - } - } - } - return entityBody; - } - - private String buildEntityBody(List params) { - String entityBody=''; - if (params != null) { - for (TwilioNameValuePair param : params) { - try { - entityBody += (entityBody=='' ? '' : '&') - + param.getName() + '=' + EncodingUtil.urlEncode(param.getValue(), 'UTF-8'); - } catch (Exception e) { - System.debug('ERROR: ' + e); - } - } - } - return entityBody; - } - /** - * Builds the uri. - * - * @param path - * the path - * @return the uRI - */ - private URL buildUri(String path) { - return buildUri(path, new Map()); - } - - /** - * Builds the uri. - * - * @param path - * the path - * @param queryStringParams - * the query string params - * @return the uRI - */ - private URL buildUri(String path, Map queryStringParams) { - String sb = path; - - if (queryStringParams != null && queryStringParams.size() > 0) { - sb += '?'; - sb += buildEntityBody(queryStringParams); - } - - URL uri; - try { - uri = new URL(sb); - } catch (Exception e) { - throw new TwilioRestException('Invalid uri: '+sb, e); - } - - return uri; + this.authAccount.setSid(accountSid); + this.authAccount.setAuthToken(authToken); } - - private URL buildUri(String path, List queryStringParams) { - String sb = path; - - if (queryStringParams != null && queryStringParams.size() > 0) { - sb += '?'; - sb += buildEntityBody(queryStringParams); - } - - URL uri; - try { - uri = new URL(sb); - } catch (Exception e) { - throw new TwilioRestException('Invalid uri: '+sb, e); - } - - return uri; - } - /** - * sendRequst Sends a REST Request to the Twilio REST API. - * - * @param path - * the URL (absolute w.r.t. the endpoint URL - i.e. - * /2010-04-01/Accounts) - * @param method - * the HTTP method to use, defaults to GET - * @param vars - * for POST or PUT, a map of data to send, for GET will be - * appended to the URL as querystring params - * - * This method is public for backwards compatibility with the old - * twilio helper library - * @return the twilio rest response - */ - public TwilioRestResponse request(String path, String method, - Map vars) { - - HttpRequest request = setupRequest(path, method, vars); - - String responseBody; - Integer statusCode; - String contentType; - if (Test.isRunningTest()) { - // can't execute HTTP requests during test execution - system.debug('Request :'+request); - Twilio_TestHTTPMock.Response responseMock = Twilio_TestHTTPMock.getInstance().send(request); - system.debug(responseMock); - responseBody = (responseMock.getBody()==null)?'':responseMock.getBody(); - statusCode = responseMock.getStatusCode(); - contentType = responseMock.getHeader('Content-Type'); - } else { - // execute HTTP request - HttpResponse response = (new Http()).send(request); - responseBody = (response.getBody()==null)?'':response.getBody(); - system.debug(responseBody+'-----------------------------------------'+response); - statusCode = response.getStatusCode(); - contentType = response.getHeader('Content-Type'); - } - TwilioRestResponse restResponse = new TwilioRestResponse(request.getEndpoint(), - responseBody, statusCode); - restResponse.setContentType(contentType); - - return restResponse; - } - - private static List generateParameters(Map vars) - { - List qparams = new List(); - - if (vars != null) - { - for (String var : vars.keySet()) - { - qparams.add(new TwilioNameValuePair(var, vars.get(var))); - } - } - - return qparams; - } - - public TwilioRestResponse request(String path, String method,List paramList) { - HttpRequest request = setupRequest(path, method, paramList); - - String responseBody; - Integer statusCode; - String contentType; - if (Test.isRunningTest()) { - // can't execute HTTP requests during test execution - system.debug('Request :'+request); - Twilio_TestHTTPMock.Response responseMock = Twilio_TestHTTPMock.getInstance().send(request); - responseBody = (responseMock.getBody()==null)?'':responseMock.getBody(); - statusCode = responseMock.getStatusCode(); - contentType = responseMock.getHeader('Content-Type'); - system.debug('Response Mock :'+responseMock); - } else { - // execute HTTP request - HttpResponse response = (new Http()).send(request); - responseBody = (response.getBody()==null)?'':response.getBody(); - system.debug(responseBody+'-----------------------------------------'+response); - statusCode = response.getStatusCode(); - contentType = response.getHeader('Content-Type'); - } - TwilioRestResponse restResponse = new TwilioRestResponse(request.getEndpoint(), - responseBody, statusCode); - restResponse.setContentType(contentType); - - return restResponse; - } - /** - * Setup request. - * - * @param path - * the path - * @param method - * the method - * @param vars - * the vars - * @return the http uri request - */ - private HttpRequest setupRequest(String path, String method, - Map params) { - - String normalizedPath = path.toLowerCase(); - String sb = ''; - - // If we've given a fully qualified uri then skip building the endpoint - if (normalizedPath.startsWith('http://') - || normalizedPath.startsWith('https://')) { - sb += path; - } else { - sb += this.getEndpoint(); - - if (!normalizedPath.startsWith('/')) { - sb += '/'; - } - sb += path; - } - - path = sb; - - HttpRequest request = buildMethod(method, path, params); - - request.setHeader('X-Twilio-Client', 'salesforce-' + VERSION); - request.setHeader('User-Agent', 'twilio-salesforce/' + VERSION); - request.setHeader('Accept', 'application/json'); - request.setHeader('Accept-Charset', 'utf-8'); - request.setHeader('Authorization', - 'Basic '+EncodingUtil.base64Encode(Blob.valueOf(this.accountSid + ':' + this.authToken))); - - return request; - } - - private HttpRequest setupRequest(String path, String method, - List params) { - - String normalizedPath = path.toLowerCase(); - String sb = ''; - - // If we've given a fully qualified uri then skip building the endpoint - if (normalizedPath.startsWith('http://') - || normalizedPath.startsWith('https://')) { - sb += path; - } else { - sb += this.getEndpoint(); - - if (!normalizedPath.startsWith('/')) { - sb += '/'; - } - sb += path; - } - - path = sb; - - HttpRequest request = buildMethod(method, path, params); - - request.setHeader('X-Twilio-Client', 'salesforce-' + VERSION); - request.setHeader('User-Agent', 'twilio-salesforce-' + VERSION); - request.setHeader('Accept', 'application/json'); - - request.setHeader('Authorization', - 'Basic '+EncodingUtil.base64Encode(Blob.valueOf(this.accountSid + ':' + this.authToken))); - - return request; - } - - /** - * Make a request, handles retries + back-off for server/network errors - * - * @param path - * the URL (absolute w.r.t. the endpoint URL - i.e. - * /2010-04-01/Accounts) - * @param method - * the HTTP method to use, defaults to GET - * @param vars - * for POST or PUT, a map of data to send, for GET will be - * appended to the URL as querystring params - * @return The response - */ - public TwilioRestResponse safeRequest(String path, String method, - Map vars) { - TwilioRestResponse response = null; - for (Integer retry = 0; retry < this.numRetries; retry++) { - response = request(path, method, vars); - if (response.isClientError()) { - System.debug('Twilio REST API Client Error: '+response.getResponseText()); - throw new TwilioRestException(response); - } else if (response.isServerError()) { - // TODO handle backoff scenario - //try { - // Thread.sleep(100 * retry); // Backoff on our sleep - //} catch (Exception e) { - //} - continue; - } - - return response; - } - Integer errorCode = response == null ? -1 : response.getHttpStatus(); - throw new TwilioRestException('Cannot fetch: ' + method + ' ' + path, - errorCode); - } - - public TwilioRestResponse safeRequestPair(String path, String method, - List paramList) - { - TwilioRestResponse response = null; - for (Integer retry = 0; retry < this.numRetries; retry++) - { - response = request(path, method, paramList); - if (response.isClientError()) { - System.debug('Twilio REST API Client Error: '+response.getResponseText()); - throw new TwilioRestException(response); - } else if (response.isServerError()) { - continue; - } - - return response; - } - Integer errorCode = response == null ? -1 : response.getHttpStatus(); - throw new TwilioRestException('Cannot fetch: ' + method + ' ' + path, - errorCode); - } - - /** - * Perform a GET request against the given fully qualified uri. - * - * @param fullUri the full uri, including protocol://hostname/path - * @return the response from the query - */ - public TwilioRestResponse get(String fullUri) { - TwilioRestResponse response = null; - - for (Integer retry = 0; retry < this.numRetries; retry++) { - response = request(fullUri, 'GET', new Map()); - if (response.isClientError()) { - throw new TwilioRestException(response); - } else if (response.isServerError()) { - //try { - // Thread.sleep(100 * retry); // Backoff on our sleep - //} catch (InterruptedException e) { - //} - continue; - } - - return response; - } - Integer errorCode = response == null ? -1 : response.getHttpStatus(); - throw new TwilioRestException('Cannot fetch: ' + fullUri + ' ', - errorCode); - } - - /** - * Get the current endpoint this client is pointed at. - * - * @return String the api endpoint - */ - public String getEndpoint() { - return endpoint; - } - - /** - * Set the endpoint this rest client uses. - * - * @param endpoint - * The location of the endpoint (e.g. https://api.twilio.com) - */ - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; - } /* * Resource related methods @@ -712,13 +112,7 @@ public class TwilioRestClient { public TwilioAccount getAccount() { return this.authAccount; } -/*shs - public TwilioAccount getAccount(map s) { - TwilioAccount account = new TwilioAccount(this,s); - return account; - } - */ /** * Get an account by account sid. * @@ -738,52 +132,4 @@ public class TwilioRestClient { return this.accountSid; } - /** - * Validate the signature on an incoming call from Twilio - * - * @param expectedSignature - * The received signature. In an Apex REST method, this will be - * RestContext.request.headers.get('X-Twilio-Signature'). - * - * @param url - * The endpoint URL, for example - * https://mysite.force.com/services/apexrest/twiliosms. - * In an Apex REST method, this will be 'https://' + - * RestContext.request.headers.get('Host') + '/services/apexrest' + - * RestContext.request.requestURI. - * - * @param params - * The params map from the incoming message. In an Apex REST method, - * this will be RestContext.request.params. - * - * @return true if the signature is valid, false otherwise - */ - public boolean validateRequest(String expectedSignature, String url, Map params) { - try { - // sort the params alphabetically, and append the key and value of each to the url - String data = url; - if(params!=null){ - List sortedKeys = new List(params.keySet()); - sortedKeys.sort(); - - for (String s: sortedKeys) { - data += s; - String v=''; - if (params.get(s)!=null) - v=params.get(s); - data += v; - } - } - - //compute the hmac on input data bytes, with AuthToken as key - Blob mac = Crypto.generateMac('hmacSHA1', Blob.valueOf(data), Blob.valueOf(authToken)); - - //base64-encode the hmac - String signature = EncodingUtil.base64Encode(mac); - - return signature.equals(expectedSignature); - } catch (Exception e) { - return false; - } - } } \ No newline at end of file diff --git a/src/classes/TwilioRestException.cls b/src/classes/TwilioRestException.cls index 2f7d535..3ceef71 100644 --- a/src/classes/TwilioRestException.cls +++ b/src/classes/TwilioRestException.cls @@ -24,70 +24,102 @@ OTHER DEALINGS IN THE SOFTWARE. */ public class TwilioRestException extends Exception { - /** The error code. */ - @TestVisible private Integer errorCode; - - /** The message. */ - @TestVisible private String message; - - /** The more info. */ - @TestVisible private String moreInfo; - - @TestVisible private Integer status; + /** The error code. */ + private Integer errorCode; + + /** The message. */ + private String message; + + /** The more info. */ + private String moreInfo; + + private Integer status; - /** - * Instantiates a new twilio rest exception. - * - * @param message the message - * @param errorCode the error code - */ - public TwilioRestException(String message, Integer errorCode) { - this(message, errorCode, null); - } + /** + * Instantiates a new twilio rest exception. + * + * @param message the message + * @param errorCode the error code + */ + public TwilioRestException(String message, Integer errorCode) { + this(message, errorCode, null); + } - /** - * Instantiates a new twilio rest exception. - * - * param message the message - * param errorCode the error code - * param moreInfo the more info - */ - public TwilioRestException(String message, Integer errorCode, String moreInfo) { - this.message = message; - this.errorCode = errorCode; - this.moreInfo = moreInfo; - } + /** + * Instantiates a new twilio rest exception. + * + * param message the message + * param errorCode the error code + * param moreInfo the more info + */ + public TwilioRestException(String message, Integer errorCode, String moreInfo) { + this.message = message; + this.errorCode = errorCode; + this.moreInfo = moreInfo; + } + + /** + * Parses the response. + * + * @param response the response + * @return the twilio rest exception + */ + public TwilioRestException(TwilioRestResponse response) { + Map data = response.toMap(); + String message = ''; + String moreInfo = null; + Integer errorCode = null; + if (response.isJson()) { + message = (String) data.get('message'); + + if (data.get('code') != null) { + errorCode = Integer.valueOf(data.get('code')); + } + if (data.get('more_info') != null) { + moreInfo = (String) data.get('more_info'); + } + if (data.get('status') != null) { + status = Integer.valueOf(data.get('status')); + } + } + else if (response.isXML()) { + // TODO add XML support some day + } + + this.message = message; + this.errorCode = errorCode; + this.moreInfo = moreInfo; + } + + @isTest + static void test() { + TwilioRestException tre1 = new TwilioRestException('message',1); + System.assertEquals('message', tre1.message); + System.assertEquals(1, tre1.errorCode); + System.assertEquals(null, tre1.moreInfo); + System.assertEquals(null, tre1.status); + + TwilioRestException tre2 = new TwilioRestException('message',1,'moreInfo'); + System.assertEquals('message', tre2.message); + System.assertEquals(1, tre2.errorCode); + System.assertEquals('moreInfo', tre2.moreInfo); + System.assertEquals(null, tre2.status); + + TwilioRestResponse response = new TwilioRestResponse('{"status": 404, "message": "The requested resource was not found"}',404); + response.setContentType('application/json'); + TwilioRestException tre3 = new TwilioRestException(response); + System.assertEquals('The requested resource was not found', tre3.message); + System.assertEquals(null, tre3.errorCode); + System.assertEquals(null, tre3.moreInfo); + System.assertEquals(404, tre3.status); + + response = new TwilioRestResponse('{"status": 400, "message": "No to number is specified", "code": 21201, "more_info": "http://www.twilio.com/docs/errors/21201"}',400); + response.setContentType('application/json'); + TwilioRestException tre4 = new TwilioRestException(response); + System.assertEquals('No to number is specified', tre4.message); + System.assertEquals(21201, tre4.errorCode); + System.assertEquals('http://www.twilio.com/docs/errors/21201', tre4.moreInfo); + System.assertEquals(400, tre4.status); + } - /** - * Parses the response. - * - * @param response the response - * @return the twilio rest exception - */ - public TwilioRestException(TwilioRestResponse response) { - Map data = response.toMap(); - String message = ''; - String moreInfo = null; - Integer errorCode = null; - if (response.isJson()) { - message = (String) data.get('message'); - - if (data.get('code') != null) { - errorCode = Integer.valueOf(data.get('code')); - } - if (data.get('more_info') != null) { - moreInfo = (String) data.get('more_info'); - } - if (data.get('status') != null) { - status = Integer.valueOf(data.get('status')); - } - } - else if (response.isXML()) { - // TODO add XML support some day - } - - this.message = message; - this.errorCode = errorCode; - this.moreInfo = moreInfo; - } } \ No newline at end of file diff --git a/src/classes/TwilioRestResponse.cls b/src/classes/TwilioRestResponse.cls index 5712009..1271e14 100644 --- a/src/classes/TwilioRestResponse.cls +++ b/src/classes/TwilioRestResponse.cls @@ -23,218 +23,218 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public class TwilioRestResponse { - - - /** The response text. */ - private String responseText; - - /** field accessor for response for backward compatibility - * @deprecated - */ - public String responseBody { get { return getResponseText(); } } - - /** The http status. */ - public Integer httpStatus { public get; private set;} - - /** The url. */ - private String url; - - /** The query string. */ - private String queryString; - - /** The error. */ - public Boolean error { public get; private set; } - - /** The content type. */ - private String contentType; - - /** - * Instantiates a new twilio rest response. - * - * @param url the url - * @param text the text - * @param status the status - */ - public TwilioRestResponse(String url, String text, Integer status) { - Pattern p = Pattern.compile('([^?]+)\\??(.*)'); - Matcher m = p.matcher(url); - m.matches(); - this.url = m.group(1); - this.queryString = m.group(2); - this.responseText = text; - this.httpStatus = status; - this.error = (status >= 400); - } - - /** - * Instantiates a new twilio rest response. - * - * @param text the response body - * @param status the status - * - * @deprecated - */ - public TwilioRestResponse(String text, Integer status) { - this.url = null; - this.queryString = null; - this.responseText = text; - this.httpStatus = status; - this.error = (status >= 400); - } - - /** - * Get the raw response body as a String - * - * @return the response body - */ - public String getResponseText() { - return responseText; - } - - /** - * Sets the response text. - * - * @param responseText the new response text - */ - public void setResponseText(String responseText) { - this.responseText = responseText; - } - - /** - - * Get the http status code associated with this response. - * - * @return the Integer value of the response status - */ - public Integer getHttpStatus() { - return httpStatus; - } - - /** - * Sets the http status. - * - * @param httpStatus the new http status - */ - public void setHttpStatus(Integer httpStatus) { - this.httpStatus = httpStatus; - } - - /** - * Get the url that resulted in this response - * - * @return the url - */ - public String getUrl() { - return url; - } - - /** - * Sets the url. - * - * @param url the new url - */ - public void setUrl(String url) { - this.url = url; - } - - /** - * Get the query string that resulted in this response - * - * @return - */ - public String getQueryString() { - return queryString; - } - - /** - * Sets the query string. - * - * @param queryString the new query string - */ - public void setQueryString(String queryString) { - this.queryString = queryString; - } - - /** - * Determine if this request resulted in any kind of error - * - * @return true if an error occured - */ - public boolean isError() { - return error; - } - - /** - * Sets the error. - * - * @param error the new error - */ - public void setError(boolean error) { - this.error = error; - } - - /** - * Determines if the response was a client side error (HTTP 4XX status) - * - * @return true if this was a client error - */ - public boolean isClientError() { - return (this.getHttpStatus() >= 400 && this.getHttpStatus() < 500); - } - - /** - * Determines if the response was a server side error (HTTP 5XX status) - * - * @return true if this was a server error - */ - public boolean isServerError() { - return this.getHttpStatus() >= 500; - } - - /** - * Sets the content type. - * - * @param contentType the new content type - */ - public void setContentType(String contentType) { - this.contentType = contentType; - } - - /** - * Method to determine if the response content type was a JSON type - * - * @return true if this looks like a JSON response - */ - public boolean isJson() { - return (this.contentType!=null && this.contentType.startsWithIgnoreCase('application/json')); - } - - /** - * Method to determine if the response content type was an XML type - * - * @return true if this looks like an XML response - */ - public boolean isXml() { - return (this.contentType!=null && (this.contentType.equalsIgnoreCase('text/xml') || this.contentType - .equalsIgnoreCase('application/xml'))); - } - - /** - * Helper method to convert the response to a canonical object map. This - * method will use the appropriate parser to map the response body to a Map - * of elements. - * - * @return a normalized Map of objects. Repeated elements are List values, - * sub-objects are Map values. All other types are String values. - */ - public Map toMap() { - Map mapped; - - if (isJson()) { - mapped = TwilioParser.jsonToMap(responseText); - } else { - throw new TwilioRestException('This method currently only supports JSON responses, not XML'); - } - return mapped; - } + + + /** The response text. */ + private String responseText; + + /** field accessor for response for backward compatibility + * @deprecated + */ + public String responseBody { get { return getResponseText(); } } + + /** The http status. */ + public Integer httpStatus { public get; private set;} + + /** The url. */ + private String url; + + /** The query string. */ + private String queryString; + + /** The error. */ + public Boolean error { public get; private set; } + + /** The content type. */ + private String contentType; + + /** + * Instantiates a new twilio rest response. + * + * @param url the url + * @param text the text + * @param status the status + */ + public TwilioRestResponse(String url, String text, Integer status) { + Pattern p = Pattern.compile('([^?]+)\\??(.*)'); + Matcher m = p.matcher(url); + m.matches(); + this.url = m.group(1); + this.queryString = m.group(2); + this.responseText = text; + this.httpStatus = status; + this.error = (status >= 400); + } + + /** + * Instantiates a new twilio rest response. + * + * @param text the response body + * @param status the status + * + * @deprecated + */ + public TwilioRestResponse(String text, Integer status) { + this.url = null; + this.queryString = null; + this.responseText = text; + this.httpStatus = status; + this.error = (status >= 400); + } + + /** + * Get the raw response body as a String + * + * @return the response body + */ + public String getResponseText() { + return responseText; + } + + /** + * Sets the response text. + * + * @param responseText the new response text + */ + public void setResponseText(String responseText) { + this.responseText = responseText; + } + + /** + + * Get the http status code associated with this response. + * + * @return the Integer value of the response status + */ + public Integer getHttpStatus() { + return httpStatus; + } + + /** + * Sets the http status. + * + * @param httpStatus the new http status + */ + public void setHttpStatus(Integer httpStatus) { + this.httpStatus = httpStatus; + } + + /** + * Get the url that resulted in this response + * + * @return the url + */ + public String getUrl() { + return url; + } + + /** + * Sets the url. + * + * @param url the new url + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * Get the query string that resulted in this response + * + * @return + */ + public String getQueryString() { + return queryString; + } + + /** + * Sets the query string. + * + * @param queryString the new query string + */ + public void setQueryString(String queryString) { + this.queryString = queryString; + } + + /** + * Determine if this request resulted in any kind of error + * + * @return true if an error occured + */ + public boolean isError() { + return error; + } + + /** + * Sets the error. + * + * @param error the new error + */ + public void setError(boolean error) { + this.error = error; + } + + /** + * Determines if the response was a client side error (HTTP 4XX status) + * + * @return true if this was a client error + */ + public boolean isClientError() { + return (this.getHttpStatus() >= 400 && this.getHttpStatus() < 500); + } + + /** + * Determines if the response was a server side error (HTTP 5XX status) + * + * @return true if this was a server error + */ + public boolean isServerError() { + return this.getHttpStatus() >= 500; + } + + /** + * Sets the content type. + * + * @param contentType the new content type + */ + public void setContentType(String contentType) { + this.contentType = contentType; + } + + /** + * Method to determine if the response content type was a JSON type + * + * @return true if this looks like a JSON response + */ + public boolean isJson() { + return (this.contentType!=null && this.contentType.startsWithIgnoreCase('application/json')); + } + + /** + * Method to determine if the response content type was an XML type + * + * @return true if this looks like an XML response + */ + public boolean isXml() { + return (this.contentType!=null && (this.contentType.equalsIgnoreCase('text/xml') || this.contentType + .equalsIgnoreCase('application/xml'))); + } + + /** + * Helper method to convert the response to a canonical object map. This + * method will use the appropriate parser to map the response body to a Map + * of elements. + * + * @return a normalized Map of objects. Repeated elements are List values, + * sub-objects are Map values. All other types are String values. + */ + public Map toMap() { + Map mapped; + + if (isJson()) { + mapped = TwilioParser.jsonToMap(responseText); + } else { + throw new TwilioRestException('This method currently only supports JSON responses, not XML'); + } + return mapped; + } } \ No newline at end of file diff --git a/src/classes/TwilioShortCode.cls b/src/classes/TwilioShortCode.cls index 467ae4c..5a4a7fb 100644 --- a/src/classes/TwilioShortCode.cls +++ b/src/classes/TwilioShortCode.cls @@ -28,159 +28,159 @@ OTHER DEALINGS IN THE SOFTWARE. * For more information see http://www.twilio.com/docs/api/rest/shortcodes */ global class TwilioShortCode extends TwilioResource.InstanceResource { - - /** The Constant SID_PROPERTY. */ - private static final String SID_PROPERTY = 'sid'; - - /** - * Instantiates a new incoming phone number. - * - * @param client the client - */ - public TwilioShortCode(TwilioRestClient client) { - super(client); - } - - /** - * Instantiates a new incoming phone number. - * - * @param client the client - * @param sid the sid - */ - public TwilioShortCode(TwilioRestClient client, String sid) { - super(client); - this.setProperty(SID_PROPERTY, sid); - } - - /** - * Instantiates a new incoming phone number. - * - * @param client the client - * @param properties the properties - */ - public TwilioShortCode(TwilioRestClient client, - Map properties) { - super(client, properties); - } - - /** - * Overrides TwilioResource.getResourceLocation() - */ - public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/SMS/ShortCodes/' - + this.getSid() + '.json'; - } - - /* - * Property getters - */ - /** - * Gets the sid. - * - * @return the sid - */ - public String getSid() { - return this.getProperty(SID_PROPERTY); - } - - /** - * Gets the date created. - * - * @return the date created - */ - public Datetime getDateCreated() { - return this.getPropertyDatetime('date_created'); - } - - /** - * Gets the date updated. - * - * @return the date updated - */ - public Datetime getDateUpdated() { - return this.getPropertyDatetime('date_updated'); - } - - /** - * Gets the friendly name. - * - * @return the friendly name - */ - public String getFriendlyName() { - return this.getProperty('friendly_name'); - } - - /** - * Gets the account sid. - * - * @return the account sid - */ - public String getAccountSid() { - return this.getProperty('account_sid'); - } - - /** - * Gets the short code number. - * - * @return the short code number - */ - public String getShortCode() { - return this.getProperty('short_code'); - } - - /** - * Gets the api version. - * - * @return the api version - */ - public String getApiVersion() { - return this.getProperty('api_version'); - } - - - /** - * Gets the sms url. - * - * @return the sms url - */ - public String getSmsUrl() { - return this.getProperty('sms_url'); - } - - /** - * Gets the sms method. - * - * @return the sms method - */ - public String getSmsMethod() { - return this.getProperty('sms_method'); - } - - /** - * Gets the sms fallback url. - * - * @return the sms fallback url - */ - public String getSmsFallbackUrl() { - return this.getProperty('sms_fallback_url'); - } - - /** - * Gets the sms fallback method. - * - * @return the sms fallback method - */ - public String getSmsFallbackMethod() { - return this.getProperty('sms_fallback_method'); - } - - /** - * Gets the Twilio URI for this resource. - * - * @return the resource URI - */ - public String getUri() { - return this.getProperty('uri'); - } + + /** The Constant SID_PROPERTY. */ + private static final String SID_PROPERTY = 'sid'; + + /** + * Instantiates a new incoming phone number. + * + * @param client the client + */ + public TwilioShortCode(TwilioRestClient client) { + super(client); + } + + /** + * Instantiates a new incoming phone number. + * + * @param client the client + * @param sid the sid + */ + public TwilioShortCode(TwilioRestClient client, String sid) { + super(client); + this.setProperty(SID_PROPERTY, sid); + } + + /** + * Instantiates a new incoming phone number. + * + * @param client the client + * @param properties the properties + */ + public TwilioShortCode(TwilioRestClient client, + Map properties) { + super(client, properties); + } + + /** + * Overrides TwilioResource.getResourceLocation() + */ + public override String getResourceLocation() { + return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' + + this.getRequestAccountSid() + '/SMS/ShortCodes/' + + this.getSid() + '.json'; + } + + /* + * Property getters + */ + /** + * Gets the sid. + * + * @return the sid + */ + public String getSid() { + return this.getProperty(SID_PROPERTY); + } + + /** + * Gets the date created. + * + * @return the date created + */ + public Datetime getDateCreated() { + return this.getPropertyDatetime('date_created'); + } + + /** + * Gets the date updated. + * + * @return the date updated + */ + public Datetime getDateUpdated() { + return this.getPropertyDatetime('date_updated'); + } + + /** + * Gets the friendly name. + * + * @return the friendly name + */ + public String getFriendlyName() { + return this.getProperty('friendly_name'); + } + + /** + * Gets the account sid. + * + * @return the account sid + */ + public String getAccountSid() { + return this.getProperty('account_sid'); + } + + /** + * Gets the short code number. + * + * @return the short code number + */ + public String getShortCode() { + return this.getProperty('short_code'); + } + + /** + * Gets the api version. + * + * @return the api version + */ + public String getApiVersion() { + return this.getProperty('api_version'); + } + + + /** + * Gets the sms url. + * + * @return the sms url + */ + public String getSmsUrl() { + return this.getProperty('sms_url'); + } + + /** + * Gets the sms method. + * + * @return the sms method + */ + public String getSmsMethod() { + return this.getProperty('sms_method'); + } + + /** + * Gets the sms fallback url. + * + * @return the sms fallback url + */ + public String getSmsFallbackUrl() { + return this.getProperty('sms_fallback_url'); + } + + /** + * Gets the sms fallback method. + * + * @return the sms fallback method + */ + public String getSmsFallbackMethod() { + return this.getProperty('sms_fallback_method'); + } + + /** + * Gets the Twilio URI for this resource. + * + * @return the resource URI + */ + public String getUri() { + return this.getProperty('uri'); + } } \ No newline at end of file diff --git a/src/classes/TwilioShortCodeList.cls b/src/classes/TwilioShortCodeList.cls index 4fec929..3b9af05 100644 --- a/src/classes/TwilioShortCodeList.cls +++ b/src/classes/TwilioShortCodeList.cls @@ -28,60 +28,61 @@ OTHER DEALINGS IN THE SOFTWARE. * For more information see http://www.twilio.com/docs/api/rest/shortcodes */ global class TwilioShortCodeList extends TwilioResource.ListResource - implements Iterable { + implements Iterable { - /** - * Instantiates a new incoming phone number list. - * - * @param client the client - */ - public TwilioShortCodeList(TwilioRestClient client) { - super(client); - } + /** + * Instantiates a new incoming phone number list. + * + * @param client the client + */ + public TwilioShortCodeList(TwilioRestClient client) { + super(client); + } - /** - * Instantiates a new incoming phone number list. - * - * @param client the client - * @param filters the filters - */ - public TwilioShortCodeList(TwilioRestClient client, - Map filters) { - super(client, filters); - } + /** + * Instantiates a new incoming phone number list. + * + * @param client the client + * @param filters the filters + */ + public TwilioShortCodeList(TwilioRestClient client, + Map filters) { + super(client, filters); + } - /* implements method from TwilioResource */ - public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/ShortCodes.json'; - } + /* implements method from TwilioResource */ + public override String getResourceLocation() { + return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' + + this.getRequestAccountSid() + '/SMS/ShortCodes.json'; + } - /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioShortCode(client, params); - } + /* implements method from TwilioResource.ListResource */ + public override Object makeNew(TwilioClient client, Map params) { + TwilioShortCode shortCode = new TwilioShortCode((TwilioRestClient)client, params); + shortCode.setRequestAccountSid(this.getRequestAccountSid()); + return shortCode; + } - /* implements method from TwilioResource.ListResource */ - public override String getListKey() { - return 'short_codes'; - } - - /* returns the current response results page */ - public List getPageData() { - List returnList = new List(); - - for (Object o : this.getObjectPageData()) { - if (o instanceof TwilioShortCode) { - returnList.add((TwilioShortCode) o); - } - } - return returnList; - } - - /* returns an iterator spanning all data pages */ - global Iterator iterator() { - return new TwilioIterator.ShortCodeIterator(this); - } - + /* implements method from TwilioResource.ListResource */ + public override String getListKey() { + return 'short_codes'; + } + + /* returns the current response results page */ + public List getPageData() { + List returnList = new List(); + + for (Object o : this.getObjectPageData()) { + if (o instanceof TwilioShortCode) { + returnList.add((TwilioShortCode) o); + } + } + return returnList; + } + + /* returns an iterator spanning all data pages */ + global Iterator iterator() { + return new TwilioIterator.ShortCodeIterator(this); + } + } \ No newline at end of file diff --git a/src/classes/TwilioSmsList.cls b/src/classes/TwilioSmsList.cls index 5b17380..c29aae8 100644 --- a/src/classes/TwilioSmsList.cls +++ b/src/classes/TwilioSmsList.cls @@ -55,8 +55,10 @@ global class TwilioSmsList extends TwilioResource.ListResource implements Iterab } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, Map params) { - return new TwilioSms(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioSms sms = new TwilioSms((TwilioRestClient)client, params); + sms.setRequestAccountSid(this.getRequestAccountSid()); + return sms; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioTRActivities.cls b/src/classes/TwilioTRActivities.cls index 4783657..3b49846 100644 --- a/src/classes/TwilioTRActivities.cls +++ b/src/classes/TwilioTRActivities.cls @@ -29,7 +29,7 @@ global class TwilioTRActivities extends TwilioResource.InstanceResource { * * @param client the client */ - public TwilioTRActivities(TwilioRestClient client) { + public TwilioTRActivities(TwilioTRRestClient client) { super(client); } @@ -39,7 +39,7 @@ global class TwilioTRActivities extends TwilioResource.InstanceResource { * @param client the activity * @param sid the sid */ - public TwilioTRActivities(TwilioRestClient client, String workspacesid, String sid) { + public TwilioTRActivities(TwilioTRRestClient client, String workspacesid, String sid) { super(client); this.setProperty('workspace_sid', workspacesid); this.setProperty('sid', sid); @@ -51,7 +51,7 @@ global class TwilioTRActivities extends TwilioResource.InstanceResource { * @param client the client * @param properties properties to set on the new call as key/value pairs */ - public TwilioTRActivities(TwilioRestClient client, Map properties) { + public TwilioTRActivities(TwilioTRRestClient client, Map properties) { super(client, properties); } @@ -59,10 +59,9 @@ global class TwilioTRActivities extends TwilioResource.InstanceResource { * Returns the URI of this resource, relative to the API endpoint. */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + this.getWorkspaceSid() + '/Activities/' - + this.getSid() + '.json'; + + this.getSid(); } @@ -132,5 +131,9 @@ global class TwilioTRActivities extends TwilioResource.InstanceResource { public Map getSubresourceUris() { return (Map)this.getObject('links'); } - + + /** Returns the resource's URL */ + public String getUrl() { + return getProperty('url'); + } } \ No newline at end of file diff --git a/src/classes/TwilioTRActivitiesList.cls b/src/classes/TwilioTRActivitiesList.cls index dc28743..b740a95 100644 --- a/src/classes/TwilioTRActivitiesList.cls +++ b/src/classes/TwilioTRActivitiesList.cls @@ -27,7 +27,7 @@ OTHER DEALINGS IN THE SOFTWARE. * * For more information see see http://www.twilio.com/docs/api/rest/call */ -global class TwilioTRActivitiesList extends TwilioResource.ListResource +global class TwilioTRActivitiesList extends TwilioResource.NextGenListResource implements Iterable { /** The workspace sid. */ @@ -38,7 +38,7 @@ global class TwilioTRActivitiesList extends TwilioResource.ListResource * * @param client the client */ - public TwilioTRActivitiesList(TwilioRestClient client) { + public TwilioTRActivitiesList(TwilioTRRestClient client) { super(client); } @@ -48,8 +48,9 @@ global class TwilioTRActivitiesList extends TwilioResource.ListResource * @param client the client * @param filters the filters */ - public TwilioTRActivitiesList(TwilioRestClient client, Map filters) { + public TwilioTRActivitiesList(TwilioTRRestClient client, String workspaceSid, Map filters) { super(client, filters); + this.workspaceSid = workspaceSid; } /** @@ -58,25 +59,21 @@ global class TwilioTRActivitiesList extends TwilioResource.ListResource * @param client the client * @param workspaceSid the workspace sid */ - public TwilioTRActivitiesList(TwilioRestClient client, String workspaceSid) { + public TwilioTRActivitiesList(TwilioTRRestClient client, String workspaceSid) { super(client); this.workspaceSid = workspaceSid; } /* implements method from TwilioResource */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' - + this.workspaceSid + '/Activities.json'; + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + + this.workspaceSid + '/Activities'; } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, + public override Object makeNew(TwilioClient client, Map params) { - TwilioTRActivities activities = new TwilioTRActivities(client, params); - activities.setRequestAccountSid(this.getRequestAccountSid()); - return activities; - //return new TwilioTRActivities(client, params); + return new TwilioTRActivities((TwilioTRRestClient)client, params); } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioTRReservation.cls b/src/classes/TwilioTRReservation.cls index 44da9e9..160da36 100644 --- a/src/classes/TwilioTRReservation.cls +++ b/src/classes/TwilioTRReservation.cls @@ -29,7 +29,7 @@ global class TwilioTRReservation extends TwilioResource.InstanceResource { * * @param client the client */ - public TwilioTRReservation(TwilioRestClient client) { + public TwilioTRReservation(TwilioTRRestClient client) { super(client); } @@ -39,7 +39,7 @@ global class TwilioTRReservation extends TwilioResource.InstanceResource { * @param client the client * @param sid the sid */ - public TwilioTRReservation(TwilioRestClient client, String workspaceSid, String taskSid, String sid) { + public TwilioTRReservation(TwilioTRRestClient client, String workspaceSid, String taskSid, String sid) { super(client); this.setProperty('workspace_sid', workspaceSid); this.setProperty('task_sid', taskSid); @@ -52,7 +52,7 @@ global class TwilioTRReservation extends TwilioResource.InstanceResource { * @param client the client * @param properties properties to set on the new call as key/value pairs */ - public TwilioTRReservation(TwilioRestClient client, Map properties) { + public TwilioTRReservation(TwilioTRRestClient client, Map properties) { super(client, properties); } @@ -60,11 +60,10 @@ global class TwilioTRReservation extends TwilioResource.InstanceResource { * Returns the URI of this resource, relative to the API endpoint. */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + this.getWorkspaceSid() + '/Tasks/' + this.getTaskSid() + '/Reservations/' - + this.getSid() + '.json'; + + this.getSid(); } @@ -152,7 +151,12 @@ global class TwilioTRReservation extends TwilioResource.InstanceResource { public Map getSubresourceUris() { return (Map)this.getObject('links'); } - + + /** Returns the resource's URL */ + public String getUrl() { + return getProperty('url'); + } + /** * Accept. * @@ -166,7 +170,7 @@ global class TwilioTRReservation extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioTRReservation r = new TwilioTRReservation(this.getClient(), response.toMap()); + TwilioTRReservation r = new TwilioTRReservation((TwilioTRRestClient)this.getClient(), response.toMap()); r.setRequestAccountSid(this.getRequestAccountSid()); return r; } @@ -184,7 +188,7 @@ global class TwilioTRReservation extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioTRReservation r = new TwilioTRReservation(this.getClient(), response.toMap()); + TwilioTRReservation r = new TwilioTRReservation((TwilioTRRestClient)this.getClient(), response.toMap()); r.setRequestAccountSid(this.getRequestAccountSid()); return r; } diff --git a/src/classes/TwilioTRReservationList.cls b/src/classes/TwilioTRReservationList.cls index 24b5244..2dbfc05 100644 --- a/src/classes/TwilioTRReservationList.cls +++ b/src/classes/TwilioTRReservationList.cls @@ -27,7 +27,7 @@ OTHER DEALINGS IN THE SOFTWARE. * * For more information see see http://www.twilio.com/docs/api/rest/call */ -global class TwilioTRReservationList extends TwilioResource.ListResource +global class TwilioTRReservationList extends TwilioResource.NextGenListResource implements Iterable { /** The workspace sid. */ @@ -38,7 +38,7 @@ global class TwilioTRReservationList extends TwilioResource.ListResource * * @param client the client */ - public TwilioTRReservationList(TwilioRestClient client) { + public TwilioTRReservationList(TwilioTRRestClient client) { super(client); } @@ -48,8 +48,9 @@ global class TwilioTRReservationList extends TwilioResource.ListResource * @param client the client * @param filters the filters */ - public TwilioTRReservationList(TwilioRestClient client, Map filters) { + public TwilioTRReservationList(TwilioTRRestClient client, String workspaceSid, Map filters) { super(client, filters); + this.workspaceSid = workspaceSid; } /** @@ -58,7 +59,7 @@ global class TwilioTRReservationList extends TwilioResource.ListResource * @param client the client * @param workspaceSid the workspace sid */ - public TwilioTRReservationList(TwilioRestClient client, String workspaceSid, String taskSid) { + public TwilioTRReservationList(TwilioTRRestClient client, String workspaceSid, String taskSid) { super(client); this.workspaceSid = workspaceSid; this.taskSid = taskSid; @@ -66,19 +67,15 @@ global class TwilioTRReservationList extends TwilioResource.ListResource /* implements method from TwilioResource */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + this.workspaceSid + '/Tasks/' - + this.taskSid + '/Reservations.json'; + + this.taskSid + '/Reservations'; } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, + public override Object makeNew(TwilioClient client, Map params) { - //return new TwilioTRReservation(client, params); - TwilioTRReservation reservation = new TwilioTRReservation(client, params); - reservation.setRequestAccountSid(this.getRequestAccountSid()); - return reservation; + return new TwilioTRReservation((TwilioTRRestClient)client, params); } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioTRRestClient.cls b/src/classes/TwilioTRRestClient.cls new file mode 100644 index 0000000..4ab3efa --- /dev/null +++ b/src/classes/TwilioTRRestClient.cls @@ -0,0 +1,92 @@ +/* +Copyright (c) 2012 Twilio, Inc. + +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. +*/ +/** + * The Class TwilioTRRestClient. + */ + +public class TwilioTRRestClient extends TwilioClient{ + + public static final String DEFAULT_VERSION = 'v1'; + /** + * Explcitly construct a TwilioRestClient with the given API credentials. + * + * @param accountSid + * the 34 character Account identifier (starting with 'AC'). This + * can be found on your Twilio dashboard page. + * @param authToken + * the 32 character AuthToken. This can be found on your Twilio + * dashboard page. + * + */ + + public TwilioTRRestClient(String accountSid, String authToken) { + super(accountSid, authToken, 'https://taskrouter.twilio.com'); + } + + + /** + * Explcitly construct a TwilioRestClient with the given API credentials and + * endpoint. + * + * @param accountSid + * the 34 character Account identifier (starting with 'AC'). This + * can be found on your Twilio dashboard page. + * @param authToken + * the 32 character AuthToken. This can be found on your Twilio + * dashboard page. + * @param endpoint + * the url of API endpoint you wish to use. (e.g. - + * 'https://api.twilio.com') + */ + public TwilioTRRestClient(String accountSid, String authToken, String endpoint) { + super(accountSid, authToken, endpoint); + } + + /** + * Returns the Workspaces list. + * See http://www.twilio.com/docs/api/rest/recording + */ + public TwilioTRWorkspaceList getWorkspaces() { + return this.getWorkspaces(new Map()); + } + + /** + * Returns a list of Workspaces in this account, applying the supplied filters. + * See http://www.twilio.com/docs/api/rest/applications + */ + public TwilioTRWorkspaceList getWorkspaces(Map filters) { + TwilioTRWorkspaceList twlist = new TwilioTRWorkspaceList(this, filters); + return twlist; + } + + /** + * Returns a given Workspace instance by sid. + */ + public TwilioTRWorkspace getWorkspace(String sid) { + TwilioTRWorkspace workspace = new TwilioTRWorkspace(this, sid); + return workspace; + } + +} \ No newline at end of file diff --git a/src/classes/TwilioTRRestClient.cls-meta.xml b/src/classes/TwilioTRRestClient.cls-meta.xml new file mode 100644 index 0000000..b12420e --- /dev/null +++ b/src/classes/TwilioTRRestClient.cls-meta.xml @@ -0,0 +1,5 @@ + + + 31.0 + Active + diff --git a/src/classes/TwilioTRTask.cls b/src/classes/TwilioTRTask.cls index 33086f3..1721db1 100644 --- a/src/classes/TwilioTRTask.cls +++ b/src/classes/TwilioTRTask.cls @@ -29,7 +29,7 @@ global class TwilioTRTask extends TwilioResource.InstanceResource { * * @param client the client */ - public TwilioTRTask(TwilioRestClient client) { + public TwilioTRTask(TwilioTRRestClient client) { super(client); } @@ -39,7 +39,7 @@ global class TwilioTRTask extends TwilioResource.InstanceResource { * @param client the client * @param sid the sid */ - public TwilioTRTask(TwilioRestClient client, String workspaceSid, String sid) { + public TwilioTRTask(TwilioTRRestClient client, String workspaceSid, String sid) { super(client); this.setProperty('workspace_sid', workspaceSid); this.setProperty('sid', sid); @@ -51,7 +51,7 @@ global class TwilioTRTask extends TwilioResource.InstanceResource { * @param client the client * @param properties properties to set on the new call as key/value pairs */ - public TwilioTRTask(TwilioRestClient client, Map properties) { + public TwilioTRTask(TwilioTRRestClient client, Map properties) { super(client, properties); } @@ -59,10 +59,9 @@ global class TwilioTRTask extends TwilioResource.InstanceResource { * Returns the URI of this resource, relative to the API endpoint. */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + this.getWorkspaceSid() + '/Tasks/' - + this.getSid() + '.json'; + + this.getSid(); } @@ -194,25 +193,38 @@ global class TwilioTRTask extends TwilioResource.InstanceResource { return (Map)this.getObject('links'); } + /** Returns the resource's URL */ + public String getUrl() { + return getProperty('url'); + } + /** * Get the reservation list * * @return */ public TwilioTRReservationList getReservations() { - System.debug('Get Reservations: ' + this.getSid()); - TwilioTRReservationList twlist = new TwilioTRReservationList(this.getClient(), this.getWorkspaceSid(), this.getSid()); + TwilioTRReservationList twlist = new TwilioTRReservationList((TwilioTRRestClient)this.getClient(), this.getWorkspaceSid(), this.getSid()); twlist.setRequestAccountSid(this.getRequestAccountSid()); return twlist; } + /** + * Returns the reservation list with the given filters. + */ + public TwilioTRReservationList getReservations(Map filters) { + TwilioTRReservationList twlist = new TwilioTRReservationList((TwilioTRRestClient)this.getClient(), this.getWorkspaceSid(), filters); + return twlist; + } + + /** * Get the reservation instance by sid * * @return */ public TwilioTRReservation getReservation(String sid) { - TwilioTRReservation reservation = new TwilioTRReservation(this.getClient(), this.getWorkspaceSid(), this.getSid(), sid); + TwilioTRReservation reservation = new TwilioTRReservation((TwilioTRRestClient)this.getClient(), this.getWorkspaceSid(), this.getSid(), sid); reservation.setRequestAccountSid(this.getRequestAccountSid()); return reservation; } @@ -233,7 +245,7 @@ global class TwilioTRTask extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'POST', vars); - TwilioTRTask t = new TwilioTRTask(this.getClient(), response.toMap()); + TwilioTRTask t = new TwilioTRTask((TwilioTRRestClient)this.getClient(), response.toMap()); t.setRequestAccountSid(this.getRequestAccountSid()); return t; } @@ -248,7 +260,7 @@ global class TwilioTRTask extends TwilioResource.InstanceResource { TwilioRestResponse response = this.getClient().safeRequest( this.getResourceLocation(), 'DELETE', null); - TwilioTRTask t = new TwilioTRTask(this.getClient(), response.toMap()); + TwilioTRTask t = new TwilioTRTask((TwilioTRRestClient)this.getClient(), response.toMap()); t.setRequestAccountSid(this.getRequestAccountSid()); return t; } diff --git a/src/classes/TwilioTRTaskList.cls b/src/classes/TwilioTRTaskList.cls index 7961348..c714ecd 100644 --- a/src/classes/TwilioTRTaskList.cls +++ b/src/classes/TwilioTRTaskList.cls @@ -27,7 +27,7 @@ OTHER DEALINGS IN THE SOFTWARE. * * For more information see see http://www.twilio.com/docs/api/rest/call */ -global class TwilioTRTaskList extends TwilioResource.ListResource +global class TwilioTRTaskList extends TwilioResource.NextGenListResource implements Iterable { /** The workspace sid. */ @@ -38,7 +38,7 @@ global class TwilioTRTaskList extends TwilioResource.ListResource * * @param client the client */ - public TwilioTRTaskList(TwilioRestClient client) { + public TwilioTRTaskList(TwilioTRRestClient client) { super(client); } @@ -48,8 +48,9 @@ global class TwilioTRTaskList extends TwilioResource.ListResource * @param client the client * @param filters the filters */ - public TwilioTRTaskList(TwilioRestClient client, Map filters) { + public TwilioTRTaskList(TwilioTRRestClient client, String workspaceSid, Map filters) { super(client, filters); + this.workspaceSid = workspaceSid; } /** @@ -58,25 +59,21 @@ global class TwilioTRTaskList extends TwilioResource.ListResource * @param client the client * @param workspaceSid the workspace sid */ - public TwilioTRTaskList(TwilioRestClient client, String workspaceSid) { + public TwilioTRTaskList(TwilioTRRestClient client, String workspaceSid) { super(client); this.workspaceSid = workspaceSid; } /* implements method from TwilioResource */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' - + this.workspaceSid + '/Tasks.json'; + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + + this.workspaceSid + '/Tasks'; } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, + public override Object makeNew(TwilioClient client, Map params) { - TwilioTRTask task = new TwilioTRTask(client, params); - task.setRequestAccountSid(this.getRequestAccountSid()); - return task; - //return new TwilioTRTask(client, params); + return new TwilioTRTask((TwilioTRRestClient)client, params); } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioTRTaskQueue.cls b/src/classes/TwilioTRTaskQueue.cls index 02f65ec..5004ab7 100644 --- a/src/classes/TwilioTRTaskQueue.cls +++ b/src/classes/TwilioTRTaskQueue.cls @@ -29,7 +29,7 @@ global class TwilioTRTaskQueue extends TwilioResource.InstanceResource { * * @param client the client */ - public TwilioTRTaskQueue(TwilioRestClient client) { + public TwilioTRTaskQueue(TwilioTRRestClient client) { super(client); } @@ -39,7 +39,7 @@ global class TwilioTRTaskQueue extends TwilioResource.InstanceResource { * @param client the client * @param sid the sid */ - public TwilioTRTaskQueue(TwilioRestClient client, String workspaceSid, String sid) { + public TwilioTRTaskQueue(TwilioTRRestClient client, String workspaceSid, String sid) { super(client); this.setProperty('sid', sid); this.setProperty('workspace_sid', workspaceSid); @@ -51,7 +51,7 @@ global class TwilioTRTaskQueue extends TwilioResource.InstanceResource { * @param client the client * @param properties properties to set on the new call as key/value pairs */ - public TwilioTRTaskQueue(TwilioRestClient client, Map properties) { + public TwilioTRTaskQueue(TwilioTRRestClient client, Map properties) { super(client, properties); } @@ -59,10 +59,9 @@ global class TwilioTRTaskQueue extends TwilioResource.InstanceResource { * Returns the URI of this resource, relative to the API endpoint. */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + this.getWorkspaceSid() + '/TaskQueues/' - + this.getSid() + '.json'; + + this.getSid(); } @@ -157,4 +156,8 @@ global class TwilioTRTaskQueue extends TwilioResource.InstanceResource { return (Map)this.getObject('links'); } + /** Returns the resource's URL */ + public String getUrl() { + return getProperty('url'); + } } \ No newline at end of file diff --git a/src/classes/TwilioTRTaskQueueList.cls b/src/classes/TwilioTRTaskQueueList.cls index 66f814c..fb2db46 100644 --- a/src/classes/TwilioTRTaskQueueList.cls +++ b/src/classes/TwilioTRTaskQueueList.cls @@ -27,7 +27,7 @@ OTHER DEALINGS IN THE SOFTWARE. * * For more information see see http://www.twilio.com/docs/api/rest/call */ -global class TwilioTRTaskQueueList extends TwilioResource.ListResource +global class TwilioTRTaskQueueList extends TwilioResource.NextGenListResource implements Iterable { /** The workspace sid. */ @@ -38,7 +38,7 @@ global class TwilioTRTaskQueueList extends TwilioResource.ListResource * * @param client the client */ - public TwilioTRTaskQueueList(TwilioRestClient client) { + public TwilioTRTaskQueueList(TwilioTRRestClient client) { super(client); } @@ -48,8 +48,9 @@ global class TwilioTRTaskQueueList extends TwilioResource.ListResource * @param client the client * @param filters the filters */ - public TwilioTRTaskQueueList(TwilioRestClient client, Map filters) { + public TwilioTRTaskQueueList(TwilioTRRestClient client, String workspaceSid, Map filters) { super(client, filters); + this.workspaceSid = workspaceSid; } /** @@ -58,29 +59,21 @@ global class TwilioTRTaskQueueList extends TwilioResource.ListResource * @param client the client * @param workspaceSid the workspace sid */ - public TwilioTRTaskQueueList(TwilioRestClient client, String workspaceSid) { + public TwilioTRTaskQueueList(TwilioTRRestClient client, String workspaceSid) { super(client); this.workspaceSid = workspaceSid; } /* implements method from TwilioResource */ - public override String getResourceLocation() { - system.debug('TaskList Resource Location:' + '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' - + this.workspaceSid + '/TaskQueues.json'); - - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' - + this.workspaceSid + '/TaskQueues.json'; + public override String getResourceLocation() { + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + + this.workspaceSid + '/TaskQueues'; } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, + public override Object makeNew(TwilioClient client, Map params) { - //return new TwilioTRTaskQueue(client, params); - TwilioTRTaskQueue taskqueue = new TwilioTRTaskQueue(client, params); - taskqueue.setRequestAccountSid(this.getRequestAccountSid()); - return taskqueue; + return new TwilioTRTaskQueue((TwilioTRRestClient)client, params); } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioTRTest.cls b/src/classes/TwilioTRTest.cls index 366a170..474a6fc 100644 --- a/src/classes/TwilioTRTest.cls +++ b/src/classes/TwilioTRTest.cls @@ -5,22 +5,22 @@ private class TwilioTRTest { // TwilioTRTask -- BEGIN // Get an API client and request the Twilio Account - private static TwilioRestClient client = new TwilioRestClient('AC00000000000000000000000000000000', authToken); - private static String rootURL = 'https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces'; - private static String resourceLocation_Task = rootURL + '/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000.json'; - private static String resourceLocation_TaskList = rootURL + '/WS00000000000000000000000000000000/Tasks.json'; - private static String resourceLocation_Worker = rootURL + '/WS00000000000000000000000000000000/Workers/WK00000000000000000000000000000000.json'; - private static String resourceLocation_WorkerList = rootURL + '/WS00000000000000000000000000000000/Workers.json'; - private static String resourceLocation_TaskQueue = rootURL + '/WS00000000000000000000000000000000/TaskQueues/WQ00000000000000000000000000000000.json'; - private static String resourceLocation_TaskQueueList = rootURL + '/WS00000000000000000000000000000000/TaskQueues.json'; - private static String resourceLocation_Reservation = rootURL + '/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000/Reservations/WR00000000000000000000000000000000.json'; - private static String resourceLocation_ReservationList = rootURL + '/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000/Reservations.json'; - private static String resourceLocation_Activities = rootURL + '/WS00000000000000000000000000000000/Activities/WA00000000000000000000000000000000.json'; - private static String resourceLocation_ActivitiesList = rootURL + '/WS00000000000000000000000000000000/Activities.json'; - private static String resourceLocation_Workflow = rootURL + '/WS00000000000000000000000000000000/Workflows/WW00000000000000000000000000000000.json'; - private static String resourceLocation_WorkflowList = rootURL + '/WS00000000000000000000000000000000/Workflows.json'; - private static String resourceLocation_Workspace = rootURL + '/WS00000000000000000000000000000000.json'; - private static String resourceLocation_WorkspaceList = rootURL + '.json'; + private static TwilioTRRestClient client = new TwilioTRRestClient('AC00000000000000000000000000000000', authToken); + private static String rootURL = 'https://taskrouter.twilio.com/v1/Workspaces'; + private static String resourceLocation_Task = rootURL + '/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000'; + private static String resourceLocation_TaskList = rootURL + '/WS00000000000000000000000000000000/Tasks'; + private static String resourceLocation_Worker = rootURL + '/WS00000000000000000000000000000000/Workers/WK00000000000000000000000000000000'; + private static String resourceLocation_WorkerList = rootURL + '/WS00000000000000000000000000000000/Workers'; + private static String resourceLocation_TaskQueue = rootURL + '/WS00000000000000000000000000000000/TaskQueues/WQ00000000000000000000000000000000'; + private static String resourceLocation_TaskQueueList = rootURL + '/WS00000000000000000000000000000000/TaskQueues'; + private static String resourceLocation_Reservation = rootURL + '/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000/Reservations/WR00000000000000000000000000000000'; + private static String resourceLocation_ReservationList = rootURL + '/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000/Reservations'; + private static String resourceLocation_Activities = rootURL + '/WS00000000000000000000000000000000/Activities/WA00000000000000000000000000000000'; + private static String resourceLocation_ActivitiesList = rootURL + '/WS00000000000000000000000000000000/Activities'; + private static String resourceLocation_Workflow = rootURL + '/WS00000000000000000000000000000000/Workflows/WW00000000000000000000000000000000'; + private static String resourceLocation_WorkflowList = rootURL + '/WS00000000000000000000000000000000/Workflows'; + private static String resourceLocation_Workspace = rootURL + '/WS00000000000000000000000000000000'; + private static String resourceLocation_WorkspaceList = rootURL; static { @@ -29,15 +29,15 @@ private class TwilioTRTest { '"attributes": "{}", "date_created": "2015-01-01T00:00:00Z", "date_updated": "2015-01-01T00:00:00Z", ' + '"priority": 1, "age": 36, "reason": null, "timeout": 86400, "workspace_sid": "WS00000000000000000000000000000000", "workflow_sid": "WW00000000000000000000000000000000",' + '"workflow_friendly_name": "Workflow Name", "task_queue_sid": "WQ00000000000000000000000000000000", "task_queue_friendly_name": "TaskQueue Name", ' + - '"url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000", ' + - '"links": {"task_queue": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/TaskQueues/WQ00000000000000000000000000000000", ' + - '"workflow": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Workflows/WW00000000000000000000000000000000",' + - '"workspace": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000"}}'; + '"url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000", ' + + '"links": {"task_queue": "hhttps://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/TaskQueues/WQ00000000000000000000000000000000", ' + + '"workflow": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Workflows/WW00000000000000000000000000000000",' + + '"workspace": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000"}}'; // --- TRTaskList Test Response String jsonResponse_TaskList = '{"tasks": [' + jsonResponse_Task + '],' + - '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Tasks?PageSize=50&Page=0",'+ - '"previous_page_url": null, "url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Tasks?PageSize=50&Page=0", "next_page_url": null, "key": "tasks"}}'; + '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Tasks?PageSize=50&Page=0",'+ + '"previous_page_url": null, "url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Tasks?PageSize=50&Page=0", "next_page_url": null, "key": "tasks"}}'; loadMockResponse(resourceLocation_Task, jsonResponse_Task); loadMockResponse(resourceLocation_TaskList, jsonResponse_TaskList); @@ -47,14 +47,14 @@ private class TwilioTRTest { String jsonResponse_Worker = '{"sid": "WK00000000000000000000000000000000", "friendly_name": "friendly name", "account_sid": "AC00000000000000000000000000000000",' + '"activity_sid": "WA00000000000000000000000000000000", "activity_name": "Idle", "workspace_sid": "WS00000000000000000000000000000000", ' + '"attributes": "{}", "available": true, "date_created": "2015-01-01T00:00:00Z", "date_updated": "2015-01-01T00:00:00Z", ' + - '"date_status_changed": "2015-01-01T00:00:00Z", "url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Workers/WK00000000000000000000000000000000",' + - '"links": {"activity": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Activities/WA00000000000000000000000000000000",' + - '"workspace": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000"}}'; + '"date_status_changed": "2015-01-01T00:00:00Z", "url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Workers/WK00000000000000000000000000000000",' + + '"links": {"activity": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Activities/WA00000000000000000000000000000000",' + + '"workspace": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000"}}'; // --- TRWorker Test Response String jsonResponse_WorkerList = '{"workers": [' + jsonResponse_Worker + '],' + - '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Workers?PageSize=50&Page=0",'+ - '"previous_page_url": null, "url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Workers?PageSize=50&Page=0", "next_page_url": null, "key": "workers"}}'; + '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Workers?PageSize=50&Page=0",'+ + '"previous_page_url": null, "url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Workers?PageSize=50&Page=0", "next_page_url": null, "key": "workers"}}'; loadMockResponse(resourceLocation_Worker, jsonResponse_Worker); loadMockResponse(resourceLocation_WorkerList, jsonResponse_WorkerList); @@ -72,8 +72,8 @@ private class TwilioTRTest { // --- TRTaskQueue Test Response String jsonResponse_TaskQueueList = '{"task_queues": [' + jsonResponse_TaskQueue + '],' + - '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/TaskQueues?PageSize=50&Page=0",'+ - '"previous_page_url": null, "url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/TaskQueues?PageSize=50&Page=0", "next_page_url": null, "key": "task_queues"}}'; + '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/TaskQueues?PageSize=50&Page=0",'+ + '"previous_page_url": null, "url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/TaskQueues?PageSize=50&Page=0", "next_page_url": null, "key": "task_queues"}}'; loadMockResponse(resourceLocation_TaskQueue, jsonResponse_TaskQueue); loadMockResponse(resourceLocation_TaskQueueList, jsonResponse_TaskQueueList); @@ -89,8 +89,8 @@ private class TwilioTRTest { '"workspace": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000"}}'; String jsonResponse_ReservationList = '{"reservations": [' + jsonResponse_Reservation + '],' + - '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000/Reservations?PageSize=50&Page=0",'+ - '"previous_page_url": null, "url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000/Reservations?PageSize=50&Page=0", "next_page_url": null, "key": "reservations"}}'; + '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000/Reservations?PageSize=50&Page=0",'+ + '"previous_page_url": null, "url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Tasks/WT00000000000000000000000000000000/Reservations?PageSize=50&Page=0", "next_page_url": null, "key": "reservations"}}'; loadMockResponse(resourceLocation_Reservation, jsonResponse_Reservation); loadMockResponse(resourceLocation_ReservationList, jsonResponse_ReservationList); @@ -99,13 +99,13 @@ private class TwilioTRTest { String jsonResponse_Activities = '{"sid": "WA00000000000000000000000000000000", "account_sid": "AC00000000000000000000000000000000",'+ '"workspace_sid": "WS00000000000000000000000000000000", "friendly_name": "Offline", "available": false, ' + '"date_created": "2015-01-01T00:00:00Z", "date_updated": "2015-01-01T00:00:00Z", '+ - '"url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Activities/WA00000000000000000000000000000000",'+ - '"links": {"workspace": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000"}}'; + '"url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Activities/WA00000000000000000000000000000000",'+ + '"links": {"workspace": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000"}}'; // --- TRActivities List Test Response String jsonResponse_ActivitiesList = '{"activities": [' + jsonResponse_Activities + '],' + - '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Activities?PageSize=50&Page=0",'+ - '"previous_page_url": null, "url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Activities?PageSize=50&Page=0", "next_page_url": null, "key": "activities"}}'; + '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Activities?PageSize=50&Page=0",'+ + '"previous_page_url": null, "url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Activities?PageSize=50&Page=0", "next_page_url": null, "key": "activities"}}'; loadMockResponse(resourceLocation_Activities, jsonResponse_Activities); loadMockResponse(resourceLocation_ActivitiesList, jsonResponse_ActivitiesList); @@ -117,12 +117,12 @@ private class TwilioTRTest { '"assignment_callback_url": "https://taskrouter/twilio/workspace/workflow", ' + '"fallback_assignment_callback_url": "https://taskrouter/twilio/fallback/workspace/workflow", "document_content_type": null, "configuration": "{}", ' + '"task_reservation_timeout": 60, "date_created": "2015-01-01T00:00:00Z", "date_updated": "2015-01-01T00:00:00Z", ' + - '"url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Workflows/WW00000000000000000000000000000000", '+ - '"links": {"workspace": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000"}}'; + '"url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Workflows/WW00000000000000000000000000000000", '+ + '"links": {"workspace": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000"}}'; String jsonResponse_WorkflowList = '{"workflows": [' + jsonResponse_Workflow + '],' + - '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Workflows?PageSize=50&Page=0",'+ - '"previous_page_url": null, "url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Workflows?PageSize=50&Page=0", "next_page_url": null, "key": "workflows"}}'; + '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Workflows?PageSize=50&Page=0",'+ + '"previous_page_url": null, "url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Workflows?PageSize=50&Page=0", "next_page_url": null, "key": "workflows"}}'; loadMockResponse(resourceLocation_Workflow, jsonResponse_Workflow); loadMockResponse(resourceLocation_WorkflowList, jsonResponse_WorkflowList); @@ -133,17 +133,17 @@ private class TwilioTRTest { '"friendly_name": "Friendly Name", "event_callback_url": "https://taskrouter/twilio/workspace", '+ '"default_activity_sid": "WA00000000000000000000000000000000", "date_created": "2015-01-01T00:00:00Z", ' + '"date_updated": "2015-01-01T00:00:00Z", "default_activity_name": "Offline", "timeout_activity_sid": "WA00000000000000000000000000000000",'+ - '"timeout_activity_name": "Idle", "url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000", ' + - '"links": {"activities": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Activities", '+ - '"task_queues": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/TaskQueues", ' + - '"statistics": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Statistics", ' + - '"tasks": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Tasks", '+ - '"workers": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Workers",' + - '"workflows": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces/WS00000000000000000000000000000000/Workflows"}}'; + '"timeout_activity_name": "Idle", "url": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000", ' + + '"links": {"activities": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Activities", '+ + '"task_queues": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/TaskQueues", ' + + '"statistics": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Statistics", ' + + '"tasks": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Tasks", '+ + '"workers": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Workers",' + + '"workflows": "https://taskrouter.twilio.com/v1/Workspaces/WS00000000000000000000000000000000/Workflows"}}'; String jsonResponse_WorkspaceList = '{"workspaces": [' + jsonResponse_Workspace + '],' + - '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces?PageSize=50&Page=0",'+ - '"previous_page_url": null, "url": "https://api.twilio.com/2010-04-01/Accounts/AC00000000000000000000000000000000/Workspaces?PageSize=50&Page=0", "next_page_url": null, "key": "workspaces"}}'; + '"meta": {"page": 0, "page_size": 50, "first_page_url": "https://taskrouter.twilio.com/v1/Workspaces?PageSize=50&Page=0",'+ + '"previous_page_url": null, "url": "https://taskrouter.twilio.com/v1/Workspaces?PageSize=50&Page=0", "next_page_url": null, "key": "workspaces"}}'; loadMockResponse(resourceLocation_Workspace, jsonResponse_Workspace); loadMockResponse(resourceLocation_WorkspaceList, jsonResponse_WorkspaceList); @@ -157,11 +157,13 @@ private class TwilioTRTest { static testMethod void testTwilioTRTask() { - + + TwilioTRRestClient cli = TwilioAPI.getDefaultTRClient(); + TwilioTRTaskList trTaskList = new TwilioTRTaskList(client); - trTaskList = new TwilioTRTaskList(client, new Map()); - trTaskList = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getTasks(); - TwilioTRTask trTask = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getTask('WT00000000000000000000000000000000'); + trTaskList = new TwilioTRTaskList(client, 'WS00000000000000000000000000000000', new Map()); + trTaskList = client.getWorkspace('WS00000000000000000000000000000000').getTasks(); + TwilioTRTask trTask = client.getWorkspace('WS00000000000000000000000000000000').getTask('WT00000000000000000000000000000000'); List trTasks = trTaskList.getPageData(); Iterator it = trTaskList.iterator(); @@ -183,8 +185,8 @@ private class TwilioTRTest { system.assertEquals(1, trTask.getPriority()); system.assertEquals(Datetime.newInstanceGmt(2015,01,01,00,00,00), trTask.getDateCreated()); system.assertEquals(Datetime.newInstanceGmt(2015,01,01,00,00,00), trTask.getDateUpdated()); - system.assertEquals(resourceLocation_Task, 'https://api.twilio.com' + trTask.getResourceLocation()); - system.assertEquals(resourceLocation_TaskList, 'https://api.twilio.com' + trTaskList.getResourceLocation()); + system.assertEquals(resourceLocation_Task, 'https://taskrouter.twilio.com' + trTask.getResourceLocation()); + system.assertEquals(resourceLocation_TaskList, 'https://taskrouter.twilio.com' + trTaskList.getResourceLocation()); system.assertEquals('tasks',trTaskList.getListKey()); trTask.cancel('This task is now canceled'); trTask.deleteTask(); @@ -193,9 +195,9 @@ private class TwilioTRTest { static testMethod void testTwilioTRWorker() { TwilioTRWorkerList trWorkerList = new TwilioTRWorkerList(client); - trWorkerList = new TwilioTRWorkerList(client, new Map()); - trWorkerList = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getWorkers(); - TwilioTRWorker trWorker = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getWorker('WK00000000000000000000000000000000'); + trWorkerList = new TwilioTRWorkerList(client, 'WS00000000000000000000000000000000', new Map()); + trWorkerList = client.getWorkspace('WS00000000000000000000000000000000').getWorkers(); + TwilioTRWorker trWorker = client.getWorkspace('WS00000000000000000000000000000000').getWorker('WK00000000000000000000000000000000'); List trWorkers = trWorkerList.getPageData(); @@ -214,17 +216,17 @@ private class TwilioTRTest { system.assertEquals(trWorker.getDateStatusChanged(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); system.assertEquals(trWorker.getDateCreated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); system.assertEquals(trWorker.getDateUpdated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); - system.assertEquals('https://api.twilio.com' + trWorker.getResourceLocation(), resourceLocation_Worker); - system.assertEquals(resourceLocation_WorkerList, 'https://api.twilio.com' + trWorkerList.getResourceLocation()); + system.assertEquals('https://taskrouter.twilio.com' + trWorker.getResourceLocation(), resourceLocation_Worker); + system.assertEquals(resourceLocation_WorkerList, 'https://taskrouter.twilio.com' + trWorkerList.getResourceLocation()); system.assertEquals('workers',trWorkerList.getListKey()); trWorker.getSubresourceUris(); } static testMethod void testTwilioTRTaskQueue() { TwilioTRTaskQueueList trTaskQueueList = new TwilioTRTaskQueueList(client); - trTaskQueueList = new TwilioTRTaskQueueList(client, new Map()); - trTaskQueueList = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getTaskQueues(); - TwilioTRTaskQueue trTaskQueue = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getTaskQueue('WQ00000000000000000000000000000000'); + trTaskQueueList = new TwilioTRTaskQueueList(client, 'WS00000000000000000000000000000000', new Map()); + trTaskQueueList = client.getWorkspace('WS00000000000000000000000000000000').getTaskQueues(); + TwilioTRTaskQueue trTaskQueue = client.getWorkspace('WS00000000000000000000000000000000').getTaskQueue('WQ00000000000000000000000000000000'); List trTaskQueues = trTaskQueueList.getPageData(); Iterator it = trTaskQueueList.iterator(); @@ -242,17 +244,17 @@ private class TwilioTRTest { system.assertEquals(trTaskQueue.getAssignmentActivityName(), 'Busy'); system.assertEquals(trTaskQueue.getDateCreated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); system.assertEquals(trTaskQueue.getDateUpdated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); - system.assertEquals('https://api.twilio.com' + trTaskQueue.getResourceLocation(), resourceLocation_TaskQueue); - system.assertEquals(resourceLocation_TaskQueueList, 'https://api.twilio.com' + trTaskQueueList.getResourceLocation()); + system.assertEquals('https://taskrouter.twilio.com' + trTaskQueue.getResourceLocation(), resourceLocation_TaskQueue); + system.assertEquals(resourceLocation_TaskQueueList, 'https://taskrouter.twilio.com' + trTaskQueueList.getResourceLocation()); system.assertEquals('task_queues',trTaskQueueList.getListKey()); trTaskQueue.getSubresourceUris(); } static testMethod void testTwilioTRReservation() { TwilioTRReservationList trReservationList = new TwilioTRReservationList(client); - trReservationList = new TwilioTRReservationList(client, new Map()); - trReservationList = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getTask('WT00000000000000000000000000000000').getReservations(); - TwilioTRReservation trReservation = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getTask('WT00000000000000000000000000000000').getReservation('WR00000000000000000000000000000000'); + trReservationList = new TwilioTRReservationList(client, 'WS00000000000000000000000000000000', new Map()); + trReservationList = client.getWorkspace('WS00000000000000000000000000000000').getTask('WT00000000000000000000000000000000').getReservations(); + TwilioTRReservation trReservation = client.getWorkspace('WS00000000000000000000000000000000').getTask('WT00000000000000000000000000000000').getReservation('WR00000000000000000000000000000000'); List trReservations = trReservationList.getPageData(); Iterator it = trReservationList.iterator(); @@ -268,8 +270,8 @@ private class TwilioTRTest { system.assertEquals(trReservation.getWorkerSid(), 'WK00000000000000000000000000000000'); system.assertEquals(trReservation.getDateCreated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); system.assertEquals(trReservation.getDateUpdated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); - system.assertEquals('https://api.twilio.com' + trReservation.getResourceLocation(), resourceLocation_Reservation); - system.assertEquals(resourceLocation_ReservationList, 'https://api.twilio.com' + trReservationList.getResourceLocation()); + system.assertEquals('https://taskrouter.twilio.com' + trReservation.getResourceLocation(), resourceLocation_Reservation); + system.assertEquals(resourceLocation_ReservationList, 'https://taskrouter.twilio.com' + trReservationList.getResourceLocation()); trReservation.accept(); trReservation.reject(); system.assertEquals('reservations',trReservationList.getListKey()); @@ -278,9 +280,9 @@ private class TwilioTRTest { static testMethod void testTwilioTRActivities() { TwilioTRActivitiesList trActivitiesList = new TwilioTRActivitiesList(client); - trActivitiesList = new TwilioTRActivitiesList(client, new Map()); - trActivitiesList = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getActivities(); - TwilioTRActivities trActivities = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getActivity('WA00000000000000000000000000000000'); + trActivitiesList = new TwilioTRActivitiesList(client, 'WS00000000000000000000000000000000', new Map()); + trActivitiesList = client.getWorkspace('WS00000000000000000000000000000000').getActivities(); + TwilioTRActivities trActivities = client.getWorkspace('WS00000000000000000000000000000000').getActivity('WA00000000000000000000000000000000'); List trActivitiesL = trActivitiesList.getPageData(); Iterator it = trActivitiesList.iterator(); @@ -294,17 +296,17 @@ private class TwilioTRTest { system.assertEquals(trActivities.getWorkspaceSid(), 'WS00000000000000000000000000000000'); system.assertEquals(trActivities.getDateCreated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); system.assertEquals(trActivities.getDateUpdated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); - system.assertEquals('https://api.twilio.com' + trActivities.getResourceLocation(), resourceLocation_Activities); - system.assertEquals(resourceLocation_ActivitiesList, 'https://api.twilio.com' + trActivitiesList.getResourceLocation()); + system.assertEquals('https://taskrouter.twilio.com' + trActivities.getResourceLocation(), resourceLocation_Activities); + system.assertEquals(resourceLocation_ActivitiesList, 'https://taskrouter.twilio.com' + trActivitiesList.getResourceLocation()); system.assertEquals('activities',trActivitiesList.getListKey()); trActivities.getSubresourceUris(); } static testMethod void testTwilioTRWorkflow() { TwilioTRWorkflowList trWorkflowList = new TwilioTRWorkflowList(client); - trWorkflowList = new TwilioTRWorkflowList(client, new Map()); - trWorkflowList = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getWorkflows(); - TwilioTRWorkflow trWorkflow = client.getAccount().getWorkspace('WS00000000000000000000000000000000').getWorkflow('WW00000000000000000000000000000000'); + trWorkflowList = new TwilioTRWorkflowList(client, 'WS00000000000000000000000000000000', new Map()); + trWorkflowList = client.getWorkspace('WS00000000000000000000000000000000').getWorkflows(); + TwilioTRWorkflow trWorkflow = client.getWorkspace('WS00000000000000000000000000000000').getWorkflow('WW00000000000000000000000000000000'); List trWorkflows = trWorkflowList.getPageData(); Iterator it = trWorkflowList.iterator(); @@ -322,8 +324,8 @@ private class TwilioTRTest { system.assertEquals(trWorkflow.getWorkspaceSid(), 'WS00000000000000000000000000000000'); system.assertEquals(trWorkflow.getDateCreated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); system.assertEquals(trWorkflow.getDateUpdated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); - system.assertEquals('https://api.twilio.com' + trWorkflow.getResourceLocation(), resourceLocation_Workflow); - system.assertEquals(resourceLocation_WorkflowList, 'https://api.twilio.com' + trWorkflowList.getResourceLocation()); + system.assertEquals('https://taskrouter.twilio.com' + trWorkflow.getResourceLocation(), resourceLocation_Workflow); + system.assertEquals(resourceLocation_WorkflowList, 'https://taskrouter.twilio.com' + trWorkflowList.getResourceLocation()); system.assertEquals('workflows',trWorkflowList.getListKey()); trWorkflow.getSubresourceUris(); } @@ -331,8 +333,8 @@ private class TwilioTRTest { static testMethod void testTwilioTRWorkspace() { TwilioTRWorkspaceList trWorkspaceList = new TwilioTRWorkspaceList(client); trWorkspaceList = new TwilioTRWorkspaceList(client, new Map()); - trWorkspaceList = client.getAccount().getWorkspaces(); - TwilioTRWorkspace trWorkspace= client.getAccount().getWorkspace('WS00000000000000000000000000000000'); + trWorkspaceList = client.getWorkspaces(); + TwilioTRWorkspace trWorkspace= client.getWorkspace('WS00000000000000000000000000000000'); List trWorkspaces = trWorkspaceList.getPageData(); Iterator it = trWorkspaceList.iterator(); @@ -349,8 +351,8 @@ private class TwilioTRTest { system.assertEquals(trWorkspace.getEventCallbackUrl(), 'https://taskrouter/twilio/workspace'); system.assertEquals(trWorkspace.getDateCreated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); system.assertEquals(trWorkspace.getDateUpdated(), Datetime.newInstanceGmt(2015,01,01,00,00,00)); - system.assertEquals('https://api.twilio.com' + trWorkspace.getResourceLocation(), resourceLocation_Workspace); - system.assertEquals(resourceLocation_WorkspaceList, 'https://api.twilio.com' + trWorkspaceList.getResourceLocation()); + system.assertEquals('https://taskrouter.twilio.com' + trWorkspace.getResourceLocation(), resourceLocation_Workspace); + system.assertEquals(resourceLocation_WorkspaceList, 'https://taskrouter.twilio.com' + trWorkspaceList.getResourceLocation()); system.assertEquals('workspaces',trWorkspaceList.getListKey()); trWorkspace.getSubresourceUris(); } diff --git a/src/classes/TwilioTRWorker.cls b/src/classes/TwilioTRWorker.cls index 3db6f09..1fb9dab 100644 --- a/src/classes/TwilioTRWorker.cls +++ b/src/classes/TwilioTRWorker.cls @@ -29,7 +29,7 @@ global class TwilioTRWorker extends TwilioResource.InstanceResource { * * @param client the client */ - public TwilioTRWorker(TwilioRestClient client) { + public TwilioTRWorker(TwilioTRRestClient client) { super(client); } @@ -39,7 +39,7 @@ global class TwilioTRWorker extends TwilioResource.InstanceResource { * @param client the client * @param sid the sid */ - public TwilioTRWorker(TwilioRestClient client, String workspacesid, String sid) { + public TwilioTRWorker(TwilioTRRestClient client, String workspacesid, String sid) { super(client); this.setProperty('workspace_sid', workspacesid); this.setProperty('sid', sid); @@ -51,7 +51,7 @@ global class TwilioTRWorker extends TwilioResource.InstanceResource { * @param client the client * @param properties properties to set on the new call as key/value pairs */ - public TwilioTRWorker(TwilioRestClient client, Map properties) { + public TwilioTRWorker(TwilioTRRestClient client, Map properties) { super(client, properties); } @@ -59,15 +59,9 @@ global class TwilioTRWorker extends TwilioResource.InstanceResource { * Returns the URI of this resource, relative to the API endpoint. */ public override String getResourceLocation() { - system.debug('Resource Location:' + '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + this.getWorkspaceSid() + '/Workers/' - + this.getSid() + '.json'); - - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' - + this.getWorkspaceSid() + '/Workers/' - + this.getSid() + '.json'; + + this.getSid(); } @@ -177,4 +171,8 @@ global class TwilioTRWorker extends TwilioResource.InstanceResource { return (Map)this.getObject('links'); } + /** Returns the resource's URL */ + public String getUrl() { + return getProperty('url'); + } } \ No newline at end of file diff --git a/src/classes/TwilioTRWorkerList.cls b/src/classes/TwilioTRWorkerList.cls index 4e12372..55990a1 100644 --- a/src/classes/TwilioTRWorkerList.cls +++ b/src/classes/TwilioTRWorkerList.cls @@ -27,7 +27,7 @@ OTHER DEALINGS IN THE SOFTWARE. * * For more information see see http://www.twilio.com/docs/api/rest/call */ -global class TwilioTRWorkerList extends TwilioResource.ListResource +global class TwilioTRWorkerList extends TwilioResource.NextGenListResource implements Iterable { /** The workspace sid. */ @@ -38,7 +38,7 @@ global class TwilioTRWorkerList extends TwilioResource.ListResource * * @param client the client */ - public TwilioTRWorkerList(TwilioRestClient client) { + public TwilioTRWorkerList(TwilioTRRestClient client) { super(client); } @@ -48,8 +48,9 @@ global class TwilioTRWorkerList extends TwilioResource.ListResource * @param client the client * @param filters the filters */ - public TwilioTRWorkerList(TwilioRestClient client, Map filters) { + public TwilioTRWorkerList(TwilioTRRestClient client, String workspaceSid, Map filters) { super(client, filters); + this.workspaceSid = workspaceSid; } /** @@ -58,25 +59,21 @@ global class TwilioTRWorkerList extends TwilioResource.ListResource * @param client the client * @param workspaceSid the workspace sid */ - public TwilioTRWorkerList(TwilioRestClient client, String workspaceSid) { + public TwilioTRWorkerList(TwilioTRRestClient client, String workspaceSid) { super(client); this.workspaceSid = workspaceSid; } /* implements method from TwilioResource */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' - + this.workspaceSid + '/Workers.json'; + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + + this.workspaceSid + '/Workers'; } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, + public override Object makeNew(TwilioClient client, Map params) { - //return new TwilioTRWorker(client, params); - TwilioTRWorker worker = new TwilioTRWorker(client, params); - worker.setRequestAccountSid(this.getRequestAccountSid()); - return worker; + return new TwilioTRWorker((TwilioTRRestClient)client, params); } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioTRWorkflow.cls b/src/classes/TwilioTRWorkflow.cls index 3b55a38..1defea4 100644 --- a/src/classes/TwilioTRWorkflow.cls +++ b/src/classes/TwilioTRWorkflow.cls @@ -29,7 +29,7 @@ global class TwilioTRWorkflow extends TwilioResource.InstanceResource { * * @param client the client */ - public TwilioTRWorkflow(TwilioRestClient client) { + public TwilioTRWorkflow(TwilioTRRestClient client) { super(client); } @@ -39,7 +39,7 @@ global class TwilioTRWorkflow extends TwilioResource.InstanceResource { * @param client the client * @param sid the sid */ - public TwilioTRWorkflow(TwilioRestClient client, String workspaceSid, String sid) { + public TwilioTRWorkflow(TwilioTRRestClient client, String workspaceSid, String sid) { super(client); this.setProperty('workspace_sid', workspaceSid); this.setProperty('sid', sid); @@ -51,7 +51,7 @@ global class TwilioTRWorkflow extends TwilioResource.InstanceResource { * @param client the client * @param properties properties to set on the new call as key/value pairs */ - public TwilioTRWorkflow(TwilioRestClient client, Map properties) { + public TwilioTRWorkflow(TwilioTRRestClient client, Map properties) { super(client, properties); } @@ -59,13 +59,11 @@ global class TwilioTRWorkflow extends TwilioResource.InstanceResource { * Returns the URI of this resource, relative to the API endpoint. */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + this.getWorkspaceSid() + '/Workflows/' - + this.getSid() + '.json'; + + this.getSid(); } - /* * Property getters */ @@ -165,5 +163,9 @@ global class TwilioTRWorkflow extends TwilioResource.InstanceResource { public Map getSubresourceUris() { return (Map)this.getObject('links'); } - + + /** Returns the resource's URL */ + public String getUrl() { + return getProperty('url'); + } } \ No newline at end of file diff --git a/src/classes/TwilioTRWorkflowList.cls b/src/classes/TwilioTRWorkflowList.cls index 19866e8..c27029e 100644 --- a/src/classes/TwilioTRWorkflowList.cls +++ b/src/classes/TwilioTRWorkflowList.cls @@ -27,7 +27,7 @@ OTHER DEALINGS IN THE SOFTWARE. * * For more information see see http://www.twilio.com/docs/api/rest/call */ -global class TwilioTRWorkflowList extends TwilioResource.ListResource +global class TwilioTRWorkflowList extends TwilioResource.NextGenListResource implements Iterable { /** The workspace sid. */ @@ -38,7 +38,7 @@ global class TwilioTRWorkflowList extends TwilioResource.ListResource * * @param client the client */ - public TwilioTRWorkflowList(TwilioRestClient client) { + public TwilioTRWorkflowList(TwilioTRRestClient client) { super(client); } @@ -48,8 +48,9 @@ global class TwilioTRWorkflowList extends TwilioResource.ListResource * @param client the client * @param filters the filters */ - public TwilioTRWorkflowList(TwilioRestClient client, Map filters) { + public TwilioTRWorkflowList(TwilioTRRestClient client, String workspaceSid, Map filters) { super(client, filters); + this.workspaceSid = workspaceSid; } /** @@ -58,25 +59,21 @@ global class TwilioTRWorkflowList extends TwilioResource.ListResource * @param client the client * @param workspaceSid the workspace sid */ - public TwilioTRWorkflowList(TwilioRestClient client, String workspaceSid) { + public TwilioTRWorkflowList(TwilioTRRestClient client, String workspaceSid) { super(client); this.workspaceSid = workspaceSid; } /* implements method from TwilioResource */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' - + this.workspaceSid + '/Workflows.json'; + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + + this.workspaceSid + '/Workflows'; } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, + public override Object makeNew(TwilioClient client, Map params) { - //return new TwilioTRWorkflow(client, params); - TwilioTRWorkflow workflow = new TwilioTRWorkflow(client, params); - workflow.setRequestAccountSid(this.getRequestAccountSid()); - return workflow; + return new TwilioTRWorkflow((TwilioTRRestClient)client, params); } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/TwilioTRWorkspace.cls b/src/classes/TwilioTRWorkspace.cls index feb0a22..617b879 100644 --- a/src/classes/TwilioTRWorkspace.cls +++ b/src/classes/TwilioTRWorkspace.cls @@ -29,7 +29,7 @@ global class TwilioTRWorkspace extends TwilioResource.InstanceResource { * * @param client the client */ - public TwilioTRWorkspace(TwilioRestClient client) { + public TwilioTRWorkspace(TwilioTRRestClient client) { super(client); } @@ -39,7 +39,7 @@ global class TwilioTRWorkspace extends TwilioResource.InstanceResource { * @param client the client * @param sid the sid */ - public TwilioTRWorkspace(TwilioRestClient client, String sid) { + public TwilioTRWorkspace(TwilioTRRestClient client, String sid) { super(client); this.setProperty('sid', sid); } @@ -50,7 +50,7 @@ global class TwilioTRWorkspace extends TwilioResource.InstanceResource { * @param client the client * @param properties properties to set on the new call as key/value pairs */ - public TwilioTRWorkspace(TwilioRestClient client, Map properties) { + public TwilioTRWorkspace(TwilioTRRestClient client, Map properties) { super(client, properties); } @@ -58,13 +58,7 @@ global class TwilioTRWorkspace extends TwilioResource.InstanceResource { * Returns the URI of this resource, relative to the API endpoint. */ public override String getResourceLocation() { - system.debug('TRWorkspace Resource Location:' + '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' + this.getSid() - + '.json'); - - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces/' + this.getSid() - + '.json'; + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces/' + this.getSid(); } /** @@ -142,23 +136,34 @@ global class TwilioTRWorkspace extends TwilioResource.InstanceResource { return (Map)this.getObject('links'); } + /** Returns the resource's URL */ + public String getUrl() { + return getProperty('url'); + } + /** * Get the task list * * @return */ public TwilioTRTaskList getTasks() { - TwilioTRTaskList twlist = new TwilioTRTaskList(this.getClient(), this.getSid()); - twlist.setRequestAccountSid(this.getRequestAccountSid()); + TwilioTRTaskList twlist = new TwilioTRTaskList((TwilioTRRestClient)this.getClient(), this.getSid()); return twlist; } + /** + * Returns the task list with the given filters. + */ + public TwilioTRTaskList getTasks(Map filters) { + TwilioTRTaskList twlist = new TwilioTRTaskList((TwilioTRRestClient)this.getClient(), this.getSid(), filters); + return twlist; + } + /** * Returns a given task instance by sid */ public TwilioTRTask getTask(String sid) { - TwilioTRTask task = new TwilioTRTask(this.getClient(), this.getSid(), sid); - task.setRequestAccountSid(this.getRequestAccountSid()); + TwilioTRTask task = new TwilioTRTask((TwilioTRRestClient)this.getClient(), this.getSid(), sid); return task; } @@ -168,17 +173,23 @@ global class TwilioTRWorkspace extends TwilioResource.InstanceResource { * @return */ public TwilioTRTaskQueueList getTaskQueues() { - TwilioTRTaskQueueList twlist = new TwilioTRTaskQueueList(this.getClient(), this.getSid()); - twlist.setRequestAccountSid(this.getRequestAccountSid()); + TwilioTRTaskQueueList twlist = new TwilioTRTaskQueueList((TwilioTRRestClient)this.getClient(), this.getSid()); return twlist; } + /** + * Returns the taskqueue list with the given filters. + */ + public TwilioTRTaskQueueList getTaskQueues(Map filters) { + TwilioTRTaskQueueList twlist = new TwilioTRTaskQueueList((TwilioTRRestClient)this.getClient(), this.getSid(), filters); + return twlist; + } + /** * Returns a given taskqueue instance by sid */ public TwilioTRTaskQueue getTaskQueue(String sid) { - TwilioTRTaskQueue queue = new TwilioTRTaskQueue(this.getClient(), this.getSid(), sid); - queue.setRequestAccountSid(this.getRequestAccountSid()); + TwilioTRTaskQueue queue = new TwilioTRTaskQueue((TwilioTRRestClient)this.getClient(), this.getSid(), sid); return queue; } @@ -189,17 +200,23 @@ global class TwilioTRWorkspace extends TwilioResource.InstanceResource { * @return */ public TwilioTRWorkflowList getWorkflows() { - TwilioTRWorkflowList twlist = new TwilioTRWorkflowList(this.getClient(), this.getSid()); - twlist.setRequestAccountSid(this.getRequestAccountSid()); + TwilioTRWorkflowList twlist = new TwilioTRWorkflowList((TwilioTRRestClient)this.getClient(), this.getSid()); return twlist; } + /** + * Returns the workflow list with the given filters. + */ + public TwilioTRWorkflowList getWorkflows(Map filters) { + TwilioTRWorkflowList twlist = new TwilioTRWorkflowList((TwilioTRRestClient)this.getClient(), this.getSid(), filters); + return twlist; + } + /** * Returns a given workflow instance by sid */ public TwilioTRWorkflow getWorkflow(String sid) { - TwilioTRWorkflow workflow = new TwilioTRWorkflow(this.getClient(), this.getSid(), sid); - workflow.setRequestAccountSid(this.getRequestAccountSid()); + TwilioTRWorkflow workflow = new TwilioTRWorkflow((TwilioTRRestClient)this.getClient(), this.getSid(), sid); return workflow; } @@ -209,17 +226,24 @@ global class TwilioTRWorkspace extends TwilioResource.InstanceResource { * @return */ public TwilioTRWorkerList getWorkers() { - TwilioTRWorkerList twlist = new TwilioTRWorkerList(this.getClient(), this.getSid()); - twlist.setRequestAccountSid(this.getRequestAccountSid()); + TwilioTRWorkerList twlist = new TwilioTRWorkerList((TwilioTRRestClient)this.getClient(), this.getSid()); return twlist; } + /** + * Returns the worker list with the given filters. + */ + public TwilioTRWorkerList getWorkers(Map filters) { + TwilioTRWorkerList twlist = new TwilioTRWorkerList((TwilioTRRestClient)this.getClient(), this.getSid(), filters); + return twlist; + } + + /** * Returns a given worker instance by sid */ public TwilioTRWorker getWorker(String sid) { - TwilioTRWorker worker = new TwilioTRWorker(this.getClient(), this.getSid(), sid); - worker.setRequestAccountSid(this.getRequestAccountSid()); + TwilioTRWorker worker = new TwilioTRWorker((TwilioTRRestClient)this.getClient(), this.getSid(), sid); return worker; } @@ -229,21 +253,26 @@ global class TwilioTRWorkspace extends TwilioResource.InstanceResource { * @return */ public TwilioTRActivitiesList getActivities() { - TwilioTRActivitiesList twlist = new TwilioTRActivitiesList(this.getClient(), this.getSid()); - twlist.setRequestAccountSid(this.getRequestAccountSid()); + TwilioTRActivitiesList twlist = new TwilioTRActivitiesList((TwilioTRRestClient)this.getClient(), this.getSid()); return twlist; } + /** + * Returns the worker list with the given filters. + */ + public TwilioTRActivitiesList getActivities(Map filters) { + TwilioTRActivitiesList twlist = new TwilioTRActivitiesList((TwilioTRRestClient)this.getClient(), this.getSid(), filters); + return twlist; + } + /** * Get the activiy * * @return */ public TwilioTRActivities getActivity(String sid) { - TwilioTRActivities activity = new TwilioTRActivities(this.getClient(), this.getSid(), sid); - activity.setRequestAccountSid(this.getRequestAccountSid()); + TwilioTRActivities activity = new TwilioTRActivities((TwilioTRRestClient)this.getClient(), this.getSid(), sid); return activity; } - } \ No newline at end of file diff --git a/src/classes/TwilioTRWorkspaceList.cls b/src/classes/TwilioTRWorkspaceList.cls index 76e5a81..f41ec8c 100644 --- a/src/classes/TwilioTRWorkspaceList.cls +++ b/src/classes/TwilioTRWorkspaceList.cls @@ -27,7 +27,7 @@ OTHER DEALINGS IN THE SOFTWARE. * * For more information see see http://www.twilio.com/docs/api/rest/call */ -global class TwilioTRWorkspaceList extends TwilioResource.ListResource +global class TwilioTRWorkspaceList extends TwilioResource.NextGenListResource implements Iterable { /** @@ -35,7 +35,7 @@ global class TwilioTRWorkspaceList extends TwilioResource.ListResource * * @param client the client */ - public TwilioTRWorkspaceList(TwilioRestClient client) { + public TwilioTRWorkspaceList(TwilioTRRestClient client) { super(client); } @@ -45,22 +45,19 @@ global class TwilioTRWorkspaceList extends TwilioResource.ListResource * @param client the client * @param filters the filters */ - public TwilioTRWorkspaceList(TwilioRestClient client, Map filters) { + public TwilioTRWorkspaceList(TwilioTRRestClient client, Map filters) { super(client, filters); } /* implements method from TwilioResource */ public override String getResourceLocation() { - return '/' + TwilioRestClient.DEFAULT_VERSION + '/Accounts/' - + this.getRequestAccountSid() + '/Workspaces.json'; + return '/' + TwilioTRRestClient.DEFAULT_VERSION + '/Workspaces'; } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, + public override Object makeNew(TwilioClient client, Map params) { - TwilioTRWorkspace w = new TwilioTRWorkspace(client, params); - w.setRequestAccountSid(this.getRequestAccountSid()); - return w; + return new TwilioTRWorkspace((TwilioTRRestClient)client, params); } /* implements method from TwilioResource.ListResource */ @@ -75,7 +72,6 @@ global class TwilioTRWorkspaceList extends TwilioResource.ListResource /* returns the current response results page */ public List getPageData() { List returnList = new List(); - for (Object o : this.getObjectPageData()) { if (o instanceof TwilioTRWorkspace) { returnList.add((TwilioTRWorkspace) o); diff --git a/src/classes/TwilioTranscriptionList.cls b/src/classes/TwilioTranscriptionList.cls index 0b3aeec..76987d7 100644 --- a/src/classes/TwilioTranscriptionList.cls +++ b/src/classes/TwilioTranscriptionList.cls @@ -72,9 +72,10 @@ global class TwilioTranscriptionList extends TwilioResource.ListResource } /* implements method from TwilioResource.ListResource */ - public override Object makeNew(TwilioRestClient client, - Map params) { - return new TwilioTranscription(client, params); + public override Object makeNew(TwilioClient client, Map params) { + TwilioTranscription transcription = new TwilioTranscription((TwilioRestClient)client, params); + transcription.setRequestAccountSid(this.getRequestAccountSid()); + return transcription; } /* implements method from TwilioResource.ListResource */ diff --git a/src/classes/Twilio_TestApplication.cls b/src/classes/Twilio_TestApplication.cls index c659868..cf009a5 100644 --- a/src/classes/Twilio_TestApplication.cls +++ b/src/classes/Twilio_TestApplication.cls @@ -26,216 +26,216 @@ OTHER DEALINGS IN THE SOFTWARE. private class Twilio_TestApplication { final static String authToken = '12345678901234567890123456789012'; - - static testmethod void testTwilioAplications_get() { - String accountJsonResponseBody ='{"applications":[{"sid":"AP023e78c7f13a4fe683ef2e5ddc510399","date_created":' - +'"Wed, 01 Feb 2012 10:49:17 +0000","date_updated":"Wed, 01 Feb 2012 10:49:17 +0000","account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3",' - +'"friendly_name":"Testapp1","api_version":"2010-04-01","voice_url":null,"voice_method":"POST","voice_fallback_url":null,' - +'"voice_fallback_method":"POST","status_callback":null,"status_callback_method":"POST","voice_caller_id_lookup":false,' - +'"sms_url":null,"sms_method":"POST","sms_fallback_url":null,"sms_fallback_method":"POST","sms_status_callback":null,' - +'"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json"},' - +'{"sid":"AP381adc6d74f6403eb704383fcfc21d2b","date_created":"Wed, 01 Feb 2012 10:49:05 +0000","date_updated":' - +'"Wed, 01 Feb 2012 10:49:05 +0000","account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","friendly_name":"Testapp",' - +'"api_version":"2010-04-01","voice_url":null,"voice_method":"POST","voice_fallback_url":null,"voice_fallback_method":"POST",' - +'"status_callback":null,"status_callback_method":"POST","voice_caller_id_lookup":false,"sms_url":null,"sms_method":"POST",' - +'"sms_fallback_url":null,"sms_fallback_method":"POST","sms_status_callback":null,' - +'"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP381adc6d74f6403eb704383fcfc21d2b.json"}],' - +'"page":0,"num_pages":1,"page_size":50,"total":2,"start":0,"end":1,"uri":' - +'"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json",' - +'"first_page_uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?Page=0&PageSize=50",'+ - +'"previous_page_uri":null,"next_page_uri":null,"last_page_uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?Page=0&PageSize=50"}'; + + static testmethod void testTwilioAplications_get() { + String accountJsonResponseBody ='{"applications":[{"sid":"AP023e78c7f13a4fe683ef2e5ddc510399","date_created":' + +'"Wed, 01 Feb 2012 10:49:17 +0000","date_updated":"Wed, 01 Feb 2012 10:49:17 +0000","account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3",' + +'"friendly_name":"Testapp1","api_version":"2010-04-01","voice_url":null,"voice_method":"POST","voice_fallback_url":null,' + +'"voice_fallback_method":"POST","status_callback":null,"status_callback_method":"POST","voice_caller_id_lookup":false,' + +'"sms_url":null,"sms_method":"POST","sms_fallback_url":null,"sms_fallback_method":"POST","sms_status_callback":null,' + +'"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json"},' + +'{"sid":"AP381adc6d74f6403eb704383fcfc21d2b","date_created":"Wed, 01 Feb 2012 10:49:05 +0000","date_updated":' + +'"Wed, 01 Feb 2012 10:49:05 +0000","account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","friendly_name":"Testapp",' + +'"api_version":"2010-04-01","voice_url":null,"voice_method":"POST","voice_fallback_url":null,"voice_fallback_method":"POST",' + +'"status_callback":null,"status_callback_method":"POST","voice_caller_id_lookup":false,"sms_url":null,"sms_method":"POST",' + +'"sms_fallback_url":null,"sms_fallback_method":"POST","sms_status_callback":null,' + +'"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP381adc6d74f6403eb704383fcfc21d2b.json"}],' + +'"page":0,"num_pages":1,"page_size":50,"total":2,"start":0,"end":1,"uri":' + +'"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json",' + +'"first_page_uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?Page=0&PageSize=50",'+ + +'"previous_page_uri":null,"next_page_uri":null,"last_page_uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?Page=0&PageSize=50"}'; // register a mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Account instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Applications.json', - new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) - ); - - // Get an API client and request the Twilio Account - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3', authToken); - TwilioApplicationList twapps = client.getAccount().getApplications(); - System.assertNotEquals(null, twapps); - - List twappslist = twapps.getPageData(); - System.assertNotEquals(null, twappslist); - System.assertEquals(2, twappslist.size()); - System.assertEquals('AP023e78c7f13a4fe683ef2e5ddc510399', twappslist[0].getSid()); - System.assertEquals('Testapp1',twappslist[0].getFriendlyName()); - System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twappslist[0].getDateCreated()); - System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twappslist[0].getDateUpdated()); - System.assertEquals('AC03c2fcd60e144e7cbeed179fcbf812a3',twappslist[0].getAccountSid()); - System.assertEquals('2010-04-01',twappslist[0].getApiVersion()); - System.assertEquals(null,twappslist[0].getVoiceUrl()); - System.assertEquals(null,twappslist[0].getStatus()); - System.assertEquals(null,twappslist[0].getStatusCallback()); - System.assertEquals('POST',twappslist[0].getVoiceMethod()); - System.assertEquals(null,twappslist[0].getVoiceFallbackUrl()); - System.assertEquals('POST',twappslist[0].getVoiceFallbackMethod()); - System.assertEquals('POST',twappslist[0].getStatusCallbackMethod()); - System.assertEquals('false',twappslist[0].getVoiceCallerIdLookup()); - System.assertEquals(null,twappslist[0].getSmsUrl()); - System.assertEquals(null,twappslist[0].getSmsMethod()); - System.assertEquals(null,twappslist[0].getSmsFallbackUrl()); - System.assertEquals('POST',twappslist[0].getSmsFallbackMethod()); - System.assertEquals(null,twappslist[0].getSmsStatusCallback()); - - Iterator it = twapps.iterator(); + // for the HTTP GET method and at the Twilio Account instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Applications.json', + new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) + ); + + // Get an API client and request the Twilio Account + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3', authToken); + TwilioApplicationList twapps = client.getAccount().getApplications(); + System.assertNotEquals(null, twapps); + + List twappslist = twapps.getPageData(); + System.assertNotEquals(null, twappslist); + System.assertEquals(2, twappslist.size()); + System.assertEquals('AP023e78c7f13a4fe683ef2e5ddc510399', twappslist[0].getSid()); + System.assertEquals('Testapp1',twappslist[0].getFriendlyName()); + System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twappslist[0].getDateCreated()); + System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twappslist[0].getDateUpdated()); + System.assertEquals('AC03c2fcd60e144e7cbeed179fcbf812a3',twappslist[0].getAccountSid()); + System.assertEquals('2010-04-01',twappslist[0].getApiVersion()); + System.assertEquals(null,twappslist[0].getVoiceUrl()); + System.assertEquals(null,twappslist[0].getStatus()); + System.assertEquals(null,twappslist[0].getStatusCallback()); + System.assertEquals('POST',twappslist[0].getVoiceMethod()); + System.assertEquals(null,twappslist[0].getVoiceFallbackUrl()); + System.assertEquals('POST',twappslist[0].getVoiceFallbackMethod()); + System.assertEquals('POST',twappslist[0].getStatusCallbackMethod()); + System.assertEquals('false',twappslist[0].getVoiceCallerIdLookup()); + System.assertEquals(null,twappslist[0].getSmsUrl()); + System.assertEquals(null,twappslist[0].getSmsMethod()); + System.assertEquals(null,twappslist[0].getSmsFallbackUrl()); + System.assertEquals('POST',twappslist[0].getSmsFallbackMethod()); + System.assertEquals(null,twappslist[0].getSmsStatusCallback()); + + Iterator it = twapps.iterator(); System.assertEquals(true, it.hasNext()); - - TwilioApplication twapps1=it.next(); - System.assertEquals(true, it.hasNext()); - twapps1=it.next(); - - System.assertEquals('AP381adc6d74f6403eb704383fcfc21d2b', twapps1.getSid()); - System.assertEquals('Testapp',twapps1.getFriendlyName()); - System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,05),twapps1.getDateCreated()); - System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,05),twapps1.getDateUpdated()); - System.assertEquals('AC03c2fcd60e144e7cbeed179fcbf812a3',twapps1.getAccountSid()); - System.assertEquals('2010-04-01',twapps1.getApiVersion()); - System.assertEquals(null,twapps1.getVoiceUrl()); - System.assertEquals('POST',twapps1.getVoiceMethod()); - System.assertEquals(null,twapps1.getVoiceFallbackUrl()); - System.assertEquals('POST',twapps1.getVoiceFallbackMethod()); - System.assertEquals('POST',twapps1.getStatusCallbackMethod()); - System.assertEquals('false',twapps1.getVoiceCallerIdLookup()); - System.assertEquals(null,twapps1.getSmsUrl()); - System.assertEquals(null,twapps1.getSmsMethod()); - System.assertEquals(null,twapps1.getSmsFallbackUrl()); - System.assertEquals('POST',twapps1.getSmsFallbackMethod()); - System.assertEquals(null,twapps1.getSmsStatusCallback()); - System.assertEquals(false, it.hasNext()); - } - - static testmethod void testTwilioAplications_filter() { - String accountJsonResponseBody ='{"applications":[{"sid":"AP023e78c7f13a4fe683ef2e5ddc510399",' - +'"date_created":"Wed, 01 Feb 2012 10:49:17 +0000","date_updated":"Wed, 01 Feb 2012 10:49:17 +0000",' - +'"account_sid":"AC03c2fcd60e144e7cbeee413fcbf812a3","friendly_name":"Testapp1","api_version":"2010-04-01",' - +'"voice_url":null,"voice_method":"POST","voice_fallback_url":null,"voice_fallback_method":"POST","status_callback":null,' - +'"status_callback_method":"POST","voice_caller_id_lookup":false,"sms_url":null,"sms_method":"POST","sms_fallback_url":null,' - +'"sms_fallback_method":"POST","sms_status_callback":null,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json"}],' - +'"page":0,"num_pages":1,"page_size":50,"total":1,"start":0,"end":0,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?' - +'VoiceMethod=POST&FriendlyName=Testapp1","first_page_uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?' - +'VoiceMethod=POST&FriendlyName=Testapp1&Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":null,"last_page_uri":"/2010-04-01/Accounts' - +'/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?VoiceMethod=POST&FriendlyName=Testapp1&Page=0&PageSize=50"}'; + + TwilioApplication twapps1=it.next(); + System.assertEquals(true, it.hasNext()); + twapps1=it.next(); + + System.assertEquals('AP381adc6d74f6403eb704383fcfc21d2b', twapps1.getSid()); + System.assertEquals('Testapp',twapps1.getFriendlyName()); + System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,05),twapps1.getDateCreated()); + System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,05),twapps1.getDateUpdated()); + System.assertEquals('AC03c2fcd60e144e7cbeed179fcbf812a3',twapps1.getAccountSid()); + System.assertEquals('2010-04-01',twapps1.getApiVersion()); + System.assertEquals(null,twapps1.getVoiceUrl()); + System.assertEquals('POST',twapps1.getVoiceMethod()); + System.assertEquals(null,twapps1.getVoiceFallbackUrl()); + System.assertEquals('POST',twapps1.getVoiceFallbackMethod()); + System.assertEquals('POST',twapps1.getStatusCallbackMethod()); + System.assertEquals('false',twapps1.getVoiceCallerIdLookup()); + System.assertEquals(null,twapps1.getSmsUrl()); + System.assertEquals(null,twapps1.getSmsMethod()); + System.assertEquals(null,twapps1.getSmsFallbackUrl()); + System.assertEquals('POST',twapps1.getSmsFallbackMethod()); + System.assertEquals(null,twapps1.getSmsStatusCallback()); + System.assertEquals(false, it.hasNext()); + } + + static testmethod void testTwilioAplications_filter() { + String accountJsonResponseBody ='{"applications":[{"sid":"AP023e78c7f13a4fe683ef2e5ddc510399",' + +'"date_created":"Wed, 01 Feb 2012 10:49:17 +0000","date_updated":"Wed, 01 Feb 2012 10:49:17 +0000",' + +'"account_sid":"AC03c2fcd60e144e7cbeee413fcbf812a3","friendly_name":"Testapp1","api_version":"2010-04-01",' + +'"voice_url":null,"voice_method":"POST","voice_fallback_url":null,"voice_fallback_method":"POST","status_callback":null,' + +'"status_callback_method":"POST","voice_caller_id_lookup":false,"sms_url":null,"sms_method":"POST","sms_fallback_url":null,' + +'"sms_fallback_method":"POST","sms_status_callback":null,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json"}],' + +'"page":0,"num_pages":1,"page_size":50,"total":1,"start":0,"end":0,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?' + +'VoiceMethod=POST&FriendlyName=Testapp1","first_page_uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?' + +'VoiceMethod=POST&FriendlyName=Testapp1&Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":null,"last_page_uri":"/2010-04-01/Accounts' + +'/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?VoiceMethod=POST&FriendlyName=Testapp1&Page=0&PageSize=50"}'; // register a mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Account instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Applications.json?VoiceMethod=POST&FriendlyName=Testapp1', - new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) - ); - - map params=new map(); - params.put('FriendlyName','Testapp1'); - params.put('VoiceMethod','POST'); - // Get an API client and request the Twilio Account - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3', authToken); - TwilioApplicationList twapps = client.getAccount().getApplications(params); - System.assertNotEquals(null, twapps); - - System.assertNotEquals(null, twapps); - - List twappslist = twapps.getPageData(); - System.assertNotEquals(null, twappslist); - System.assertEquals(1, twappslist.size()); - System.assertEquals('AP023e78c7f13a4fe683ef2e5ddc510399', twappslist[0].getSid()); - System.assertEquals('Testapp1',twappslist[0].getFriendlyName()); - System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twappslist[0].getDateCreated()); - System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twappslist[0].getDateUpdated()); - System.assertEquals('AC03c2fcd60e144e7cbeee413fcbf812a3',twappslist[0].getAccountSid()); - System.assertEquals('2010-04-01',twappslist[0].getApiVersion()); - System.assertEquals(null,twappslist[0].getVoiceUrl()); - System.assertEquals('POST',twappslist[0].getVoiceMethod()); - System.assertEquals(null,twappslist[0].getVoiceFallbackUrl()); - System.assertEquals('POST',twappslist[0].getVoiceFallbackMethod()); - System.assertEquals('POST',twappslist[0].getStatusCallbackMethod()); - System.assertEquals('false',twappslist[0].getVoiceCallerIdLookup()); - System.assertEquals(null,twappslist[0].getSmsUrl()); - System.assertEquals(null,twappslist[0].getSmsMethod()); - System.assertEquals(null,twappslist[0].getSmsFallbackUrl()); - System.assertEquals('POST',twappslist[0].getSmsFallbackMethod()); - System.assertEquals(null,twappslist[0].getSmsStatusCallback()); - } - - static testmethod void testTwilioAplication_get() { - String accountJsonResponseBody ='{"sid":"AP023e78c7f13a4fe683ef2e5ddc510399","date_created":"Wed, 01 Feb 2012 10:49:17 +0000",' - +'"date_updated":"Wed, 01 Feb 2012 10:49:17 +0000","account_sid":"AC03c2fcd60e144e7cbeee413fcbf812a3","friendly_name":"Testapp1",' - +'"api_version":"2010-04-01","voice_url":null,"voice_method":"POST","voice_fallback_url":null,"voice_fallback_method":"POST",' - +'"status_callback":null,"status_callback_method":"POST","voice_caller_id_lookup":false,"sms_url":null,"sms_method":"POST","sms_fallback_url":null,' - +'"sms_fallback_method":"POST","sms_status_callback":null,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json"}'; - + // for the HTTP GET method and at the Twilio Account instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Applications.json?VoiceMethod=POST&FriendlyName=Testapp1', + new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) + ); + + map params=new map(); + params.put('VoiceMethod','POST'); + params.put('FriendlyName','Testapp1'); + // Get an API client and request the Twilio Account + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3', authToken); + TwilioApplicationList twapps = client.getAccount().getApplications(params); + System.assertNotEquals(null, twapps); + + System.assertNotEquals(null, twapps); + + List twappslist = twapps.getPageData(); + System.assertNotEquals(null, twappslist); + System.assertEquals(1, twappslist.size()); + System.assertEquals('AP023e78c7f13a4fe683ef2e5ddc510399', twappslist[0].getSid()); + System.assertEquals('Testapp1',twappslist[0].getFriendlyName()); + System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twappslist[0].getDateCreated()); + System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twappslist[0].getDateUpdated()); + System.assertEquals('AC03c2fcd60e144e7cbeee413fcbf812a3',twappslist[0].getAccountSid()); + System.assertEquals('2010-04-01',twappslist[0].getApiVersion()); + System.assertEquals(null,twappslist[0].getVoiceUrl()); + System.assertEquals('POST',twappslist[0].getVoiceMethod()); + System.assertEquals(null,twappslist[0].getVoiceFallbackUrl()); + System.assertEquals('POST',twappslist[0].getVoiceFallbackMethod()); + System.assertEquals('POST',twappslist[0].getStatusCallbackMethod()); + System.assertEquals('false',twappslist[0].getVoiceCallerIdLookup()); + System.assertEquals(null,twappslist[0].getSmsUrl()); + System.assertEquals(null,twappslist[0].getSmsMethod()); + System.assertEquals(null,twappslist[0].getSmsFallbackUrl()); + System.assertEquals('POST',twappslist[0].getSmsFallbackMethod()); + System.assertEquals(null,twappslist[0].getSmsStatusCallback()); + } + + static testmethod void testTwilioAplication_get() { + String accountJsonResponseBody ='{"sid":"AP023e78c7f13a4fe683ef2e5ddc510399","date_created":"Wed, 01 Feb 2012 10:49:17 +0000",' + +'"date_updated":"Wed, 01 Feb 2012 10:49:17 +0000","account_sid":"AC03c2fcd60e144e7cbeee413fcbf812a3","friendly_name":"Testapp1",' + +'"api_version":"2010-04-01","voice_url":null,"voice_method":"POST","voice_fallback_url":null,"voice_fallback_method":"POST",' + +'"status_callback":null,"status_callback_method":"POST","voice_caller_id_lookup":false,"sms_url":null,"sms_method":"POST","sms_fallback_url":null,' + +'"sms_fallback_method":"POST","sms_status_callback":null,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json"}'; + // register a mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Account instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json', - new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) - ); - - - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3','9339f87c4573196830a8f497bceb8fa9'); - TwilioApplication twaps = client.getAccount().getApplication('AP023e78c7f13a4fe683ef2e5ddc510399'); - - System.assertEquals('AP023e78c7f13a4fe683ef2e5ddc510399', twaps.getSid()); - System.assertEquals('Testapp1',twaps.getFriendlyName()); - System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twaps.getDateCreated()); - System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twaps.getDateUpdated()); - System.assertEquals('AC03c2fcd60e144e7cbeee413fcbf812a3',twaps.getAccountSid()); - System.assertEquals('2010-04-01',twaps.getApiVersion()); - System.assertEquals(null,twaps.getVoiceUrl()); - System.assertEquals('POST',twaps.getVoiceMethod()); - System.assertEquals(null,twaps.getVoiceFallbackUrl()); - System.assertEquals('POST',twaps.getVoiceFallbackMethod()); - System.assertEquals('POST',twaps.getStatusCallbackMethod()); - System.assertEquals('false',twaps.getVoiceCallerIdLookup()); - System.assertEquals(null,twaps.getSmsUrl()); - System.assertEquals(null,twaps.getSmsMethod()); - System.assertEquals(null,twaps.getSmsFallbackUrl()); - System.assertEquals('POST',twaps.getSmsFallbackMethod()); - System.assertEquals(null,twaps.getSmsStatusCallback()); - System.assertEquals('/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json',twaps.getUri()); - } - - static testmethod void testTwilioAplication_create() { - String accountJsonResponseBody ='{"sid":"AP023e78c7f13a4fe683ef2e5ddc510399","date_created":"Wed, 01 Feb 2012 10:49:17 +0000",' - +'"date_updated":"Wed, 01 Feb 2012 10:49:17 +0000","account_sid":"AC03c2fcd60e144e7cbeee413fcbf812a3","friendly_name":"Testapp1",' - +'"api_version":"2010-04-01","voice_url":null,"voice_method":"POST","voice_fallback_url":null,"voice_fallback_method":"POST",' - +'"status_callback":null,"status_callback_method":"POST","voice_caller_id_lookup":false,"sms_url":null,"sms_method":"POST","sms_fallback_url":null,' - +'"sms_fallback_method":"POST","sms_status_callback":null,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json"}'; - + // for the HTTP GET method and at the Twilio Account instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json', + new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) + ); + + + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3','9339f87c4573196830a8f497bceb8fa9'); + TwilioApplication twaps = client.getAccount().getApplication('AP023e78c7f13a4fe683ef2e5ddc510399'); + + System.assertEquals('AP023e78c7f13a4fe683ef2e5ddc510399', twaps.getSid()); + System.assertEquals('Testapp1',twaps.getFriendlyName()); + System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twaps.getDateCreated()); + System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twaps.getDateUpdated()); + System.assertEquals('AC03c2fcd60e144e7cbeee413fcbf812a3',twaps.getAccountSid()); + System.assertEquals('2010-04-01',twaps.getApiVersion()); + System.assertEquals(null,twaps.getVoiceUrl()); + System.assertEquals('POST',twaps.getVoiceMethod()); + System.assertEquals(null,twaps.getVoiceFallbackUrl()); + System.assertEquals('POST',twaps.getVoiceFallbackMethod()); + System.assertEquals('POST',twaps.getStatusCallbackMethod()); + System.assertEquals('false',twaps.getVoiceCallerIdLookup()); + System.assertEquals(null,twaps.getSmsUrl()); + System.assertEquals(null,twaps.getSmsMethod()); + System.assertEquals(null,twaps.getSmsFallbackUrl()); + System.assertEquals('POST',twaps.getSmsFallbackMethod()); + System.assertEquals(null,twaps.getSmsStatusCallback()); + System.assertEquals('/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json',twaps.getUri()); + } + + static testmethod void testTwilioAplication_create() { + String accountJsonResponseBody ='{"sid":"AP023e78c7f13a4fe683ef2e5ddc510399","date_created":"Wed, 01 Feb 2012 10:49:17 +0000",' + +'"date_updated":"Wed, 01 Feb 2012 10:49:17 +0000","account_sid":"AC03c2fcd60e144e7cbeee413fcbf812a3","friendly_name":"Testapp1",' + +'"api_version":"2010-04-01","voice_url":null,"voice_method":"POST","voice_fallback_url":null,"voice_fallback_method":"POST",' + +'"status_callback":null,"status_callback_method":"POST","voice_caller_id_lookup":false,"sms_url":null,"sms_method":"POST","sms_fallback_url":null,' + +'"sms_fallback_method":"POST","sms_status_callback":null,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications/AP023e78c7f13a4fe683ef2e5ddc510399.json"}'; + // register a mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Account instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'POST', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Applications.json', - new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) - ); - - - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3','9339f87c4573196830a8f497bceb8fa9'); - map params=new map(); - params.put('FriendlyName','Testapp1'); - params.put('VoiceMethod','POST'); - TwilioApplication twaps = client.getAccount().getApplications().create(params); - - System.assertEquals('AP023e78c7f13a4fe683ef2e5ddc510399', twaps.getSid()); - System.assertEquals('Testapp1',twaps.getFriendlyName()); - System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twaps.getDateCreated()); - System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twaps.getDateUpdated()); - System.assertEquals('AC03c2fcd60e144e7cbeee413fcbf812a3',twaps.getAccountSid()); - System.assertEquals('2010-04-01',twaps.getApiVersion()); - System.assertEquals(null,twaps.getVoiceUrl()); - System.assertEquals('POST',twaps.getVoiceMethod()); - System.assertEquals(null,twaps.getVoiceFallbackUrl()); - System.assertEquals('POST',twaps.getVoiceFallbackMethod()); - System.assertEquals('POST',twaps.getStatusCallbackMethod()); - System.assertEquals('false',twaps.getVoiceCallerIdLookup()); - System.assertEquals(null,twaps.getSmsUrl()); - System.assertEquals(null,twaps.getSmsMethod()); - System.assertEquals(null,twaps.getSmsFallbackUrl()); - System.assertEquals('POST',twaps.getSmsFallbackMethod()); - System.assertEquals(null,twaps.getSmsStatusCallback()); - } - + // for the HTTP GET method and at the Twilio Account instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'POST', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Applications.json', + new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) + ); + + + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3','9339f87c4573196830a8f497bceb8fa9'); + map params=new map(); + params.put('FriendlyName','Testapp1'); + params.put('VoiceMethod','POST'); + TwilioApplication twaps = client.getAccount().getApplications().create(params); + + System.assertEquals('AP023e78c7f13a4fe683ef2e5ddc510399', twaps.getSid()); + System.assertEquals('Testapp1',twaps.getFriendlyName()); + System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twaps.getDateCreated()); + System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twaps.getDateUpdated()); + System.assertEquals('AC03c2fcd60e144e7cbeee413fcbf812a3',twaps.getAccountSid()); + System.assertEquals('2010-04-01',twaps.getApiVersion()); + System.assertEquals(null,twaps.getVoiceUrl()); + System.assertEquals('POST',twaps.getVoiceMethod()); + System.assertEquals(null,twaps.getVoiceFallbackUrl()); + System.assertEquals('POST',twaps.getVoiceFallbackMethod()); + System.assertEquals('POST',twaps.getStatusCallbackMethod()); + System.assertEquals('false',twaps.getVoiceCallerIdLookup()); + System.assertEquals(null,twaps.getSmsUrl()); + System.assertEquals(null,twaps.getSmsMethod()); + System.assertEquals(null,twaps.getSmsFallbackUrl()); + System.assertEquals('POST',twaps.getSmsFallbackMethod()); + System.assertEquals(null,twaps.getSmsStatusCallback()); + } + } \ No newline at end of file diff --git a/src/classes/Twilio_TestCalls.cls b/src/classes/Twilio_TestCalls.cls index f7ee8e2..a6dac30 100644 --- a/src/classes/Twilio_TestCalls.cls +++ b/src/classes/Twilio_TestCalls.cls @@ -25,30 +25,30 @@ OTHER DEALINGS IN THE SOFTWARE. @isTest class Twilio_TestCalls { - final static String authToken = '12345678901234567890123456789012'; - + final static String authToken = '12345678901234567890123456789012'; + static testmethod void testTwilioCall_get() { // create the response body to be returned when the Call URI is requested - String json='{"sid":"CA5ea9c5d78e1f35fc01c204682d056e22","date_created":"Mon, 02 Jan 2012 06:41:14 +0000","date_updated":"Mon, 02 Jan 2012 06:41:42 ' - +'+0000","parent_call_sid":"CA39f78143e0374332b21c9b256e6d4e9a","account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","to":"+918722266660",' - +'"to_formatted":"+918722266660","from":"+919902400323","from_formatted":"+919902400323","phone_number_sid":' - +'"PN17c8630939e44e7e92a45c51bcdb7122","status":"completed","start_time":"Mon, 02 Jan 2012 06:41:33 +0000",' - +'"end_time":"Mon, 02 Jan 2012 06:41:42 +0000","duration":"9","price":"-0.09000",' - +'"direction":"outbound-dial","answered_by":null,"api_version":"2010-04-01","annotation":null,' - +'"forwarded_from":"","group_sid":null,"caller_name":null,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22.json",' - +'"subresource_uris":{"notifications":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22/Notifications.json",' - +'"recordings":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22/Recordings.json"}}'; + String json='{"sid":"CA5ea9c5d78e1f35fc01c204682d056e22","date_created":"Mon, 02 Jan 2012 06:41:14 +0000","date_updated":"Mon, 02 Jan 2012 06:41:42 ' + +'+0000","parent_call_sid":"CA39f78143e0374332b21c9b256e6d4e9a","account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","to":"+918722266660",' + +'"to_formatted":"+918722266660","from":"+919902400323","from_formatted":"+919902400323","phone_number_sid":' + +'"PN17c8630939e44e7e92a45c51bcdb7122","status":"completed","start_time":"Mon, 02 Jan 2012 06:41:33 +0000",' + +'"end_time":"Mon, 02 Jan 2012 06:41:42 +0000","duration":"9","price":"-0.09000",' + +'"direction":"outbound-dial","answered_by":null,"api_version":"2010-04-01","annotation":null,' + +'"forwarded_from":"","group_sid":null,"caller_name":null,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22.json",' + +'"subresource_uris":{"notifications":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22/Notifications.json",' + +'"recordings":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22/Recordings.json"}}'; - // register the mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Call instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22.json', - new Twilio_TestHTTPMock.Response(json,200) - ); - - // Get an API client and request the Twilio Call - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeed179fcbf812a3',authToken); + // register the mock Response with the Twilio_TestHTTPMock singleton service + // for the HTTP GET method and at the Twilio Call instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22.json', + new Twilio_TestHTTPMock.Response(json,200) + ); + + // Get an API client and request the Twilio Call + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeed179fcbf812a3',authToken); TwilioCall call = client.getAccount().getCall('CA5ea9c5d78e1f35fc01c204682d056e22'); // assert correct behavior @@ -78,51 +78,51 @@ class Twilio_TestCalls { static testmethod void testTwilioCall_post() { String json= - '{"sid": "CA5ea9c5d78e1f35fc01c204682d056e22",' - +'"date_created": "Tue, 10 Aug 2010 08:02:17 +0000",' - +'"date_updated": "Tue, 10 Aug 2010 08:02:47 +0000",' - +'"parent_call_sid": null,' - +'"account_sid": "AC03c2fcd60e144e7cbeed179fcbf812a3",' - +'"to": "+14153855708",' - +'"from": "+14158141819",' - +'"phone_number_sid": null,' - +'"status": "completed",' - +'"start_time": "Tue, 10 Aug 2010 08:02:31 +0000",' - +'"end_time": "Tue, 10 Aug 2010 08:02:47 +0000",' - +'"duration": "16",' - +'"price": "-0.03000",' - +'"direction": "outbound-api",' - +'"answered_by": null,' - +'"api_version": "2010-04-01",' - +'"annotation": null,' - +'"forwarded_from": null,' - +'"caller_name": null,' - +'"uri": "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22.json",' - +'"subresource_uris":{' - +'"notifications": "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22/Notifications.json",' - +'"recordings": "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22/Recordings.json"' - +'}}'; + '{"sid": "CA5ea9c5d78e1f35fc01c204682d056e22",' + +'"date_created": "Tue, 10 Aug 2010 08:02:17 +0000",' + +'"date_updated": "Tue, 10 Aug 2010 08:02:47 +0000",' + +'"parent_call_sid": null,' + +'"account_sid": "AC03c2fcd60e144e7cbeed179fcbf812a3",' + +'"to": "+14153855708",' + +'"from": "+14158141819",' + +'"phone_number_sid": null,' + +'"status": "completed",' + +'"start_time": "Tue, 10 Aug 2010 08:02:31 +0000",' + +'"end_time": "Tue, 10 Aug 2010 08:02:47 +0000",' + +'"duration": "16",' + +'"price": "-0.03000",' + +'"direction": "outbound-api",' + +'"answered_by": null,' + +'"api_version": "2010-04-01",' + +'"annotation": null,' + +'"forwarded_from": null,' + +'"caller_name": null,' + +'"uri": "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22.json",' + +'"subresource_uris":{' + +'"notifications": "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22/Notifications.json",' + +'"recordings": "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22/Recordings.json"' + +'}}'; - // register the mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Call instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'POST', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22.json', - new Twilio_TestHTTPMock.Response(json,201) - ); - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22.json', - new Twilio_TestHTTPMock.Response(json,200) - ); - - // define fields to update - Map params = new Map { - 'Status' => 'completed' - }; - - // Get an API client and request the Twilio Call - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeed179fcbf812a3',authToken); + // register the mock Response with the Twilio_TestHTTPMock singleton service + // for the HTTP GET method and at the Twilio Call instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'POST', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22.json', + new Twilio_TestHTTPMock.Response(json,201) + ); + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5ea9c5d78e1f35fc01c204682d056e22.json', + new Twilio_TestHTTPMock.Response(json,200) + ); + + // define fields to update + Map params = new Map { + 'Status' => 'completed' + }; + + // Get an API client and request the Twilio Call + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeed179fcbf812a3',authToken); client.getAccount().getCall('CA5ea9c5d78e1f35fc01c204682d056e22').updateResource(params); TwilioCall call = client.getAccount().getCall('CA5ea9c5d78e1f35fc01c204682d056e22'); @@ -148,43 +148,43 @@ class Twilio_TestCalls { static testmethod void testTwilioCall_redirect() { - String json= - '{"sid": "CAe1644a7eed5088b159577c5802d8be38",' - +'"date_created": "Tue, 10 Aug 2010 08:02:17 +0000",' - +'"date_updated": "Tue, 10 Aug 2010 08:02:47 +0000",' - +'"parent_call_sid": null,' - +'"account_sid": "AC5ef872f6da5a21de157d80997a64bd33",' - +'"to": "+14153855708",' - +'"from": "+14158141819",' - +'"phone_number_sid": null,' - +'"status": "in-progress",' - +'"start_time": "Tue, 10 Aug 2010 08:02:31 +0000",' - +'"end_time": "Tue, 10 Aug 2010 08:02:47 +0000",' - +'"duration": "16",' - +'"price": "-0.03000",' - +'"direction": "outbound-api",' - +'"answered_by": null,' - +'"api_version": "2010-04-01",' - +'"annotation": null,' - +'"forwarded_from": null,' - +'"caller_name": null,' - +'"uri": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json",' - +'"subresource_uris":{' - +'"notifications": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Notifications.json",' - +'"recordings": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Recordings.json"' - +'}}'; - - // register the mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Call instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'POST', - 'https://api.twilio.com/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json', - new Twilio_TestHTTPMock.Response(json,201) - ); - TwilioRestClient client = new TwilioRestClient('AC5ef872f6da5a21de157d80997a64bd33',authToken); - Twiliocall call = client.getAccount().getCall('CAe1644a7eed5088b159577c5802d8be38').redirect('http://www.myapp.com/myhandler.php','POST'); - - System.assertEquals('in-progress',call.getStatus()); + String json= + '{"sid": "CAe1644a7eed5088b159577c5802d8be38",' + +'"date_created": "Tue, 10 Aug 2010 08:02:17 +0000",' + +'"date_updated": "Tue, 10 Aug 2010 08:02:47 +0000",' + +'"parent_call_sid": null,' + +'"account_sid": "AC5ef872f6da5a21de157d80997a64bd33",' + +'"to": "+14153855708",' + +'"from": "+14158141819",' + +'"phone_number_sid": null,' + +'"status": "in-progress",' + +'"start_time": "Tue, 10 Aug 2010 08:02:31 +0000",' + +'"end_time": "Tue, 10 Aug 2010 08:02:47 +0000",' + +'"duration": "16",' + +'"price": "-0.03000",' + +'"direction": "outbound-api",' + +'"answered_by": null,' + +'"api_version": "2010-04-01",' + +'"annotation": null,' + +'"forwarded_from": null,' + +'"caller_name": null,' + +'"uri": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json",' + +'"subresource_uris":{' + +'"notifications": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Notifications.json",' + +'"recordings": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Recordings.json"' + +'}}'; + + // register the mock Response with the Twilio_TestHTTPMock singleton service + // for the HTTP GET method and at the Twilio Call instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'POST', + 'https://api.twilio.com/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json', + new Twilio_TestHTTPMock.Response(json,201) + ); + TwilioRestClient client = new TwilioRestClient('AC5ef872f6da5a21de157d80997a64bd33',authToken); + Twiliocall call = client.getAccount().getCall('CAe1644a7eed5088b159577c5802d8be38').redirect('http://www.myapp.com/myhandler.php','POST'); + + System.assertEquals('in-progress',call.getStatus()); System.assertEquals('CAe1644a7eed5088b159577c5802d8be38',call.getSid()); System.assertEquals('AC5ef872f6da5a21de157d80997a64bd33',call.getAccountSid()); } @@ -192,88 +192,88 @@ class Twilio_TestCalls { static testmethod void testTwilioCall_hangup() { - String json= - '{"sid": "CAe1644a7eed5088b159577c5802d8be38",' - +'"date_created": "Tue, 10 Aug 2010 08:02:17 +0000",' - +'"date_updated": "Tue, 10 Aug 2010 08:02:47 +0000",' - +'"parent_call_sid": null,' - +'"account_sid": "AC5ef872f6da5a21de157d80997a64bd33",' - +'"to": "+14153855708",' - +'"from": "+14158141819",' - +'"phone_number_sid": null,' - +'"status": "completed",' - +'"start_time": "Tue, 10 Aug 2010 08:02:31 +0000",' - +'"end_time": "Tue, 10 Aug 2010 08:02:47 +0000",' - +'"duration": "16",' - +'"price": "-0.03000",' - +'"direction": "outbound-api",' - +'"answered_by": null,' - +'"api_version": "2010-04-01",' - +'"annotation": null,' - +'"forwarded_from": null,' - +'"caller_name": null,' - +'"uri": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json",' - +'"subresource_uris":{' - +'"notifications": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Notifications.json",' - +'"recordings": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Recordings.json"' - +'}}'; - - // register the mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Call instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'POST', - 'https://api.twilio.com/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json', - new Twilio_TestHTTPMock.Response(json,201) - ); + String json= + '{"sid": "CAe1644a7eed5088b159577c5802d8be38",' + +'"date_created": "Tue, 10 Aug 2010 08:02:17 +0000",' + +'"date_updated": "Tue, 10 Aug 2010 08:02:47 +0000",' + +'"parent_call_sid": null,' + +'"account_sid": "AC5ef872f6da5a21de157d80997a64bd33",' + +'"to": "+14153855708",' + +'"from": "+14158141819",' + +'"phone_number_sid": null,' + +'"status": "completed",' + +'"start_time": "Tue, 10 Aug 2010 08:02:31 +0000",' + +'"end_time": "Tue, 10 Aug 2010 08:02:47 +0000",' + +'"duration": "16",' + +'"price": "-0.03000",' + +'"direction": "outbound-api",' + +'"answered_by": null,' + +'"api_version": "2010-04-01",' + +'"annotation": null,' + +'"forwarded_from": null,' + +'"caller_name": null,' + +'"uri": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json",' + +'"subresource_uris":{' + +'"notifications": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Notifications.json",' + +'"recordings": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Recordings.json"' + +'}}'; + + // register the mock Response with the Twilio_TestHTTPMock singleton service + // for the HTTP GET method and at the Twilio Call instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'POST', + 'https://api.twilio.com/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json', + new Twilio_TestHTTPMock.Response(json,201) + ); - TwilioRestClient client = new TwilioRestClient('AC5ef872f6da5a21de157d80997a64bd33',authToken); - Twiliocall call = client.getAccount().getCall('CAe1644a7eed5088b159577c5802d8be38').hangup(); - - System.assertEquals('completed',call.getStatus()); + TwilioRestClient client = new TwilioRestClient('AC5ef872f6da5a21de157d80997a64bd33',authToken); + Twiliocall call = client.getAccount().getCall('CAe1644a7eed5088b159577c5802d8be38').hangup(); + + System.assertEquals('completed',call.getStatus()); System.assertEquals('CAe1644a7eed5088b159577c5802d8be38',call.getSid()); System.assertEquals('AC5ef872f6da5a21de157d80997a64bd33',call.getAccountSid()); } static testmethod void testTwilioCall_cancel() { - String json= - '{"sid": "CAe1644a7eed5088b159577c5802d8be38",' - +'"date_created": "Tue, 10 Aug 2010 08:02:17 +0000",' - +'"date_updated": "Tue, 10 Aug 2010 08:02:47 +0000",' - +'"parent_call_sid": null,' - +'"account_sid": "AC5ef872f6da5a21de157d80997a64bd33",' - +'"to": "+14153855708",' - +'"from": "+14158141819",' - +'"phone_number_sid": null,' - +'"status": "completed",' - +'"start_time": "Tue, 10 Aug 2010 08:02:31 +0000",' - +'"end_time": "Tue, 10 Aug 2010 08:02:47 +0000",' - +'"duration": "16",' - +'"price": "-0.03000",' - +'"direction": "outbound-api",' - +'"answered_by": null,' - +'"api_version": "2010-04-01",' - +'"annotation": null,' - +'"forwarded_from": null,' - +'"caller_name": null,' - +'"uri": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json",' - +'"subresource_uris":{' - +'"notifications": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Notifications.json",' - +'"recordings": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Recordings.json"' - +'}}'; - - // register the mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Call instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'POST', - 'https://api.twilio.com/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json', - new Twilio_TestHTTPMock.Response(json,201) - ); + String json= + '{"sid": "CAe1644a7eed5088b159577c5802d8be38",' + +'"date_created": "Tue, 10 Aug 2010 08:02:17 +0000",' + +'"date_updated": "Tue, 10 Aug 2010 08:02:47 +0000",' + +'"parent_call_sid": null,' + +'"account_sid": "AC5ef872f6da5a21de157d80997a64bd33",' + +'"to": "+14153855708",' + +'"from": "+14158141819",' + +'"phone_number_sid": null,' + +'"status": "completed",' + +'"start_time": "Tue, 10 Aug 2010 08:02:31 +0000",' + +'"end_time": "Tue, 10 Aug 2010 08:02:47 +0000",' + +'"duration": "16",' + +'"price": "-0.03000",' + +'"direction": "outbound-api",' + +'"answered_by": null,' + +'"api_version": "2010-04-01",' + +'"annotation": null,' + +'"forwarded_from": null,' + +'"caller_name": null,' + +'"uri": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json",' + +'"subresource_uris":{' + +'"notifications": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Notifications.json",' + +'"recordings": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38/Recordings.json"' + +'}}'; + + // register the mock Response with the Twilio_TestHTTPMock singleton service + // for the HTTP GET method and at the Twilio Call instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'POST', + 'https://api.twilio.com/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Calls/CAe1644a7eed5088b159577c5802d8be38.json', + new Twilio_TestHTTPMock.Response(json,201) + ); - TwilioRestClient client = new TwilioRestClient('AC5ef872f6da5a21de157d80997a64bd33',authToken); - Twiliocall call = client.getAccount().getCall('CAe1644a7eed5088b159577c5802d8be38').cancel(); - - System.assertEquals('completed',call.getStatus()); + TwilioRestClient client = new TwilioRestClient('AC5ef872f6da5a21de157d80997a64bd33',authToken); + Twiliocall call = client.getAccount().getCall('CAe1644a7eed5088b159577c5802d8be38').cancel(); + + System.assertEquals('completed',call.getStatus()); System.assertEquals('CAe1644a7eed5088b159577c5802d8be38',call.getSid()); System.assertEquals('AC5ef872f6da5a21de157d80997a64bd33',call.getAccountSid()); } @@ -282,26 +282,26 @@ class Twilio_TestCalls { static testmethod void testTwilioCallList_get() { // create the response body to be returned when the Calls URI is requested - String json='{"calls":[{"sid":"CA62efc923742a4c40beeca377581f4a55","date_created":"Tue, 27 Dec 2011 09:54:38 +0000","date_updated":"Tue, 27 Dec 2011 09:54:38 +0000",' - +'"parent_call_sid":null,"account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","to":"+15108706378","to_formatted":"(510) 870-6378","from":"+14157234000",' - +'"from_formatted":"(415) 723-4000","phone_number_sid":null,"status":"no-answer","start_time":"Tue, 27 Dec 2011 09:54:38 +0000","end_time":null,' - +'"duration":null,"price":null,"direction":"outbound-api","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":null,' - +'"group_sid":null,"caller_name":null,"uri":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA62efc923742a4c40beeca377581f4a55.json","subresource_uris":' - +'{"notifications":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA62efc923742a4c40beeca377581f4a55Notifications.json",' - +'"recordings":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA62efc923742a4c40beeca377581f4a55Recordings.json"}},' - +'{"sid":"CAdd42863f1f474cd690ecd98aba3a0c14","date_created":"Tue, 27 Dec 2011 09:25:58 +0000","date_updated":"Tue, 27 Dec 2011 09:25:58 +0000","parent_call_sid":null,"account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","to":"+15108706378","to_formatted":"(510) 870-6378","from":"+14157234000","from_formatted":"(415) 723-4000","phone_number_sid":null,"status":"no-answer","start_time":"Tue, 27 Dec 2011 09:25:58 +0000","end_time":null,"duration":null,"price":null,"direction":"outbound-api","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":null,"group_sid":null,"caller_name":null,"uri":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCAdd42863f1f474cd690ecd98aba3a0c14.json","subresource_uris":{"notifications":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCAdd42863f1f474cd690ecd98aba3a0c14Notifications.json","recordings":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCAdd42863f1f474cd690ecd98aba3a0c14Recordings.json"}},' - +'{"sid":"CA001697081686d17bf58a1e9bcf848fcd","date_created":"Tue, 27 Dec 2011 07:14:46 +0000","date_updated":"Tue, 27 Dec 2011 07:14:58 +0000","parent_call_sid":null,"account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","to":"","to_formatted":"","from":"client:sandbox","from_formatted":"sandbox","phone_number_sid":"","status":"completed","start_time":"Tue, 27 Dec 2011 07:14:46 +0000","end_time":"Tue, 27 Dec 2011 07:14:58 +0000","duration":"12","price":"-0.00250","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"","group_sid":null,"caller_name":null,"uri":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA001697081686d17bf58a1e9bcf848fcd.json","subresource_uris":{"notifications":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA001697081686d17bf58a1e9bcf848fcdNotifications.json","recordings":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA001697081686d17bf58a1e9bcf848fcdRecordings.json"}}],"page":0,"total":3}'; - - // register the mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Call List URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json', - new Twilio_TestHTTPMock.Response(json,200) - ); + String json='{"calls":[{"sid":"CA62efc923742a4c40beeca377581f4a55","date_created":"Tue, 27 Dec 2011 09:54:38 +0000","date_updated":"Tue, 27 Dec 2011 09:54:38 +0000",' + +'"parent_call_sid":null,"account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","to":"+15108706378","to_formatted":"(510) 870-6378","from":"+14157234000",' + +'"from_formatted":"(415) 723-4000","phone_number_sid":null,"status":"no-answer","start_time":"Tue, 27 Dec 2011 09:54:38 +0000","end_time":null,' + +'"duration":null,"price":null,"direction":"outbound-api","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":null,' + +'"group_sid":null,"caller_name":null,"uri":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA62efc923742a4c40beeca377581f4a55.json","subresource_uris":' + +'{"notifications":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA62efc923742a4c40beeca377581f4a55Notifications.json",' + +'"recordings":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA62efc923742a4c40beeca377581f4a55Recordings.json"}},' + +'{"sid":"CAdd42863f1f474cd690ecd98aba3a0c14","date_created":"Tue, 27 Dec 2011 09:25:58 +0000","date_updated":"Tue, 27 Dec 2011 09:25:58 +0000","parent_call_sid":null,"account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","to":"+15108706378","to_formatted":"(510) 870-6378","from":"+14157234000","from_formatted":"(415) 723-4000","phone_number_sid":null,"status":"no-answer","start_time":"Tue, 27 Dec 2011 09:25:58 +0000","end_time":null,"duration":null,"price":null,"direction":"outbound-api","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":null,"group_sid":null,"caller_name":null,"uri":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCAdd42863f1f474cd690ecd98aba3a0c14.json","subresource_uris":{"notifications":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCAdd42863f1f474cd690ecd98aba3a0c14Notifications.json","recordings":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCAdd42863f1f474cd690ecd98aba3a0c14Recordings.json"}},' + +'{"sid":"CA001697081686d17bf58a1e9bcf848fcd","date_created":"Tue, 27 Dec 2011 07:14:46 +0000","date_updated":"Tue, 27 Dec 2011 07:14:58 +0000","parent_call_sid":null,"account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","to":"","to_formatted":"","from":"client:sandbox","from_formatted":"sandbox","phone_number_sid":"","status":"completed","start_time":"Tue, 27 Dec 2011 07:14:46 +0000","end_time":"Tue, 27 Dec 2011 07:14:58 +0000","duration":"12","price":"-0.00250","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"","group_sid":null,"caller_name":null,"uri":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA001697081686d17bf58a1e9bcf848fcd.json","subresource_uris":{"notifications":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA001697081686d17bf58a1e9bcf848fcdNotifications.json","recordings":"2010-04-01AccountsAC03c2fcd60e144e7cbeed179fcbf812a3CallsCA001697081686d17bf58a1e9bcf848fcdRecordings.json"}}],"page":0,"total":3}'; + + // register the mock Response with the Twilio_TestHTTPMock singleton service + // for the HTTP GET method and at the Twilio Call List URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json', + new Twilio_TestHTTPMock.Response(json,200) + ); // Get an API client and request the Twilio Call List - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeed179fcbf812a3',authToken); + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeed179fcbf812a3',authToken); TwilioCallList twcalls = client.getAccount().getCalls(); List calls = twcalls.getPageData(); @@ -331,31 +331,31 @@ class Twilio_TestCalls { static testmethod void testTwilioCallList_createCall() { - String json='{"sid":"CA1768192f80674687ac779c0abe5dd5db","date_created":"Fri, 13 Jan 2012 11:27:54 +0000","date_updated":"Fri, ' - +'13 Jan 2012 11:27:54 +0000","parent_call_sid":null,"account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","to":"+919902400323",' - +'"to_formatted":"+919902400323","from":"+919902400323","from_formatted":"+919902400323","phone_number_sid":"PN17c8630939e44e7e92a45c51bcdb7122"' - +',"status":"queued","start_time":null,"end_time":null,"duration":null,"price":null,"direction":"outbound-api","answered_by":null,"api_version":' - +'"2010-04-01","annotation":null,"forwarded_from":null,"group_sid":null,"caller_name":null,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3' - +'/Calls/CA1768192f80674687ac779c0abe5dd5db.json","subresource_uris":{"notifications":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/' - +'CA1768192f80674687ac779c0abe5dd5db/Notifications.json","recordings":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/' - +'CA1768192f80674687ac779c0abe5dd5db/Recordings.json"}}'; + String json='{"sid":"CA1768192f80674687ac779c0abe5dd5db","date_created":"Fri, 13 Jan 2012 11:27:54 +0000","date_updated":"Fri, ' + +'13 Jan 2012 11:27:54 +0000","parent_call_sid":null,"account_sid":"AC03c2fcd60e144e7cbeed179fcbf812a3","to":"+919902400323",' + +'"to_formatted":"+919902400323","from":"+919902400323","from_formatted":"+919902400323","phone_number_sid":"PN17c8630939e44e7e92a45c51bcdb7122"' + +',"status":"queued","start_time":null,"end_time":null,"duration":null,"price":null,"direction":"outbound-api","answered_by":null,"api_version":' + +'"2010-04-01","annotation":null,"forwarded_from":null,"group_sid":null,"caller_name":null,"uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3' + +'/Calls/CA1768192f80674687ac779c0abe5dd5db.json","subresource_uris":{"notifications":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/' + +'CA1768192f80674687ac779c0abe5dd5db/Notifications.json","recordings":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/' + +'CA1768192f80674687ac779c0abe5dd5db/Recordings.json"}}'; - // register the mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Call instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'POST', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json', - new Twilio_TestHTTPMock.Response(json,201) - ); - Map params=new Map(); - params.put('From','+919902400323' ); - params.put('To', '+919902400323'); - params.put('Url', 'http://shsimha-developer-edition.ap1.force.com/clicktocall?called=+918722266660'); - - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeed179fcbf812a3',authToken); - Twiliocall call = client.getAccount().getCalls().create(params); - - System.assertEquals('queued',call.getStatus()); + // register the mock Response with the Twilio_TestHTTPMock singleton service + // for the HTTP GET method and at the Twilio Call instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'POST', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json', + new Twilio_TestHTTPMock.Response(json,201) + ); + Map params=new Map(); + params.put('From','+919902400323' ); + params.put('To', '+919902400323'); + params.put('Url', 'http://shsimha-developer-edition.ap1.force.com/clicktocall?called=+918722266660'); + + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeed179fcbf812a3',authToken); + Twiliocall call = client.getAccount().getCalls().create(params); + + System.assertEquals('queued',call.getStatus()); System.assertEquals('CA1768192f80674687ac779c0abe5dd5db',call.getSid()); System.assertEquals('AC03c2fcd60e144e7cbeed179fcbf812a3',call.getAccountSid()); System.assertEquals(Datetime.newInstanceGmt(2012,01,13,11,27,54),call.getDateCreated()); @@ -377,168 +377,168 @@ class Twilio_TestCalls { static testmethod void testTwilioCallList_iterator() { - String jsonPage0 = - '{ "calls" : [ ' - // calls[0] - +'{ "account_sid" : "AC03c2fcd60e144e7cbeed179fcbf812a3",' - +'"annotation" : null,' - +'"answered_by" : null,' - +'"api_version" : "2010-04-01",' - +'"caller_name" : null,' - +'"date_created" : "Thu, 19 Jan 2012 21:51:38 +0000",' - +'"date_updated" : "Thu, 19 Jan 2012 21:51:43 +0000",' - +'"direction" : "inbound",' - +'"duration" : "4",' - +'"end_time" : "Thu, 19 Jan 2012 21:51:43 +0000",' - +'"forwarded_from" : "+14157893609",' - +'"from" : "+17073996131",' - +'"from_formatted" : "(707) 399-6131",' - +'"group_sid" : null,' - +'"parent_call_sid" : null,' - +'"phone_number_sid" : "PNa6dfec5c0a2561be6680e4ab5117283c",' - +'"price" : "-0.01000",' - +'"sid" : "CAbca8dd0af46b637c6a6fd6dd0e01fab5",' - +'"start_time" : "Thu, 19 Jan 2012 21:51:39 +0000",' - +'"status" : "completed",' - +'"subresource_uris" : { "notifications" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAbca8dd0af46b637c6a6fd6dd0e01fab5/Notifications.json",' - +'"recordings" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAbca8dd0af46b637c6a6fd6dd0e01fab5/Recordings.json"' - +'},' - +'"to" : "+14157893609",' - +'"to_formatted" : "(415) 789-3609",' - +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAbca8dd0af46b637c6a6fd6dd0e01fab5.json"' - +'},' - // calls[1] - +'{ "account_sid" : "AC03c2fcd60e144e7cbeed179fcbf812a3",' - +'"annotation" : null,' - +'"answered_by" : null,' - +'"api_version" : "2010-04-01",' - +'"caller_name" : null,' - +'"date_created" : "Tue, 17 Jan 2012 21:21:45 +0000",' - +'"date_updated" : "Tue, 17 Jan 2012 21:21:50 +0000",' - +'"direction" : "inbound",' - +'"duration" : "4",' - +'"end_time" : "Tue, 17 Jan 2012 21:21:50 +0000",' - +'"forwarded_from" : "+14158774850",' - +'"from" : "+17378742833",' - +'"from_formatted" : "(737) 874-2833",' - +'"group_sid" : null,' - +'"parent_call_sid" : null,' - +'"phone_number_sid" : "PNebe1495ddc055eb2508cb3f9d4ed043d",' - +'"price" : "-0.01000",' - +'"sid" : "CA5c16c13e5d5615bd73d16664e562d895",' - +'"start_time" : "Tue, 17 Jan 2012 21:21:46 +0000",' - +'"status" : "completed",' - +'"subresource_uris" : { "notifications" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5c16c13e5d5615bd73d16664e562d895/Notifications.json",' - +'"recordings" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5c16c13e5d5615bd73d16664e562d895/Recordings.json"' - +'},' - +'"to" : "+14158774850",' - +'"to_formatted" : "(415) 877-4850",' - +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5c16c13e5d5615bd73d16664e562d895.json"' - +'}' - +'],' - +'"end" : 1,' - +'"first_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=0",' - +'"last_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=1",' - +'"next_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=1&AfterSid=CA5c16c13e5d5615bd73d16664e562d895",' - +'"num_pages" : 2,' - +'"page" : 0,' - +'"page_size" : 2,' - +'"previous_page_uri" : null,' - +'"start" : 0,' - +'"total" : 4,' - +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=0"' - +'}'; - - - String jsonPage1 = - '{ "calls" : [' - // calls[0] - +'{ "account_sid" : "AC03c2fcd60e144e7cbeed179fcbf812a3",' - +'"annotation" : null,' - +'"answered_by" : null,' - +'"api_version" : "2010-04-01",' - +'"caller_name" : null,' - +'"date_created" : "Thu, 12 Jan 2012 17:31:58 +0000",' - +'"date_updated" : "Thu, 12 Jan 2012 17:32:05 +0000",' - +'"direction" : "outbound-dial",' - +'"duration" : "0",' - +'"end_time" : "Thu, 12 Jan 2012 17:32:05 +0000",' - +'"forwarded_from" : "",' - +'"from" : "+14155551111",' - +'"from_formatted" : "(415) 555-1111",' - +'"group_sid" : null,' - +'"parent_call_sid" : "CAd6d7055b76d849489c3acabf4eb0140b",' - +'"phone_number_sid" : "PN2e8b297009170f06944fcfb74f5cd0ee",' - +'"price" : null,' - +'"sid" : "CAb659fd2fa5fd820c05a5277fae70a98b",' - +'"start_time" : "Thu, 12 Jan 2012 17:31:58 +0000",' - +'"status" : "no-answer",' - +'"subresource_uris" : { "notifications" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAb659fd2fa5fd820c05a5277fae70a98b/Notifications.json",' - +' "recordings" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAb659fd2fa5fd820c05a5277fae70a98b/Recordings.json"' - +' },' - +'"to" : "+14155551234",' - +'"to_formatted" : "(415) 555-1234",' - +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAb659fd2fa5fd820c05a5277fae70a98b.json"' - +'},' - // calls[1] - +'{ "account_sid" : "AC03c2fcd60e144e7cbeed179fcbf812a3",' - +'"annotation" : null,' - +'"answered_by" : null,' - +'"api_version" : "2010-04-01",' - +'"caller_name" : null,' - +'"date_created" : "Thu, 12 Jan 2012 17:31:48 +0000",' - +'"date_updated" : "Thu, 12 Jan 2012 17:32:05 +0000",' - +'"direction" : "outbound-api",' - +'"duration" : "8",' - +'"end_time" : "Thu, 12 Jan 2012 17:32:05 +0000",' - +'"forwarded_from" : null,' - +'"from" : "+14155551111",' - +'"from_formatted" : "(415) 555-1111",' - +'"group_sid" : null,' - +'"parent_call_sid" : null,' - +'"phone_number_sid" : "PN2e8b297009170f06944fcfb74f5cd0ee",' - +'"price" : "-0.02000",' - +'"sid" : "CAd6d7055b76d849489c3acabf4eb0140b",' - +'"start_time" : "Thu, 12 Jan 2012 17:31:57 +0000",' - +'"status" : "completed",' - +'"subresource_uris" : { "notifications" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAd6d7055b76d849489c3acabf4eb0140b/Notifications.json",' - +' "recordings" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAd6d7055b76d849489c3acabf4eb0140b/Recordings.json"' - +' },' - +'"to" : "+14152188121",' - +'"to_formatted" : "(415) 555-1234",' - +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAd6d7055b76d849489c3acabf4eb0140b.json"' - +'}' - +'],' - +'"end" : 3,' - +'"first_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=0",' - +'"last_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=1",' - +'"next_page_uri" : null,' - +'"num_pages" : 2,' - +'"page" : 1,' - +'"page_size" : 2,' - +'"previous_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=0",' - +'"start" : 2,' - +'"total" : 4,' - +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=1"' - +'}'; - - + String jsonPage0 = + '{ "calls" : [ ' + // calls[0] + +'{ "account_sid" : "AC03c2fcd60e144e7cbeed179fcbf812a3",' + +'"annotation" : null,' + +'"answered_by" : null,' + +'"api_version" : "2010-04-01",' + +'"caller_name" : null,' + +'"date_created" : "Thu, 19 Jan 2012 21:51:38 +0000",' + +'"date_updated" : "Thu, 19 Jan 2012 21:51:43 +0000",' + +'"direction" : "inbound",' + +'"duration" : "4",' + +'"end_time" : "Thu, 19 Jan 2012 21:51:43 +0000",' + +'"forwarded_from" : "+14157893609",' + +'"from" : "+17073996131",' + +'"from_formatted" : "(707) 399-6131",' + +'"group_sid" : null,' + +'"parent_call_sid" : null,' + +'"phone_number_sid" : "PNa6dfec5c0a2561be6680e4ab5117283c",' + +'"price" : "-0.01000",' + +'"sid" : "CAbca8dd0af46b637c6a6fd6dd0e01fab5",' + +'"start_time" : "Thu, 19 Jan 2012 21:51:39 +0000",' + +'"status" : "completed",' + +'"subresource_uris" : { "notifications" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAbca8dd0af46b637c6a6fd6dd0e01fab5/Notifications.json",' + +'"recordings" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAbca8dd0af46b637c6a6fd6dd0e01fab5/Recordings.json"' + +'},' + +'"to" : "+14157893609",' + +'"to_formatted" : "(415) 789-3609",' + +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAbca8dd0af46b637c6a6fd6dd0e01fab5.json"' + +'},' + // calls[1] + +'{ "account_sid" : "AC03c2fcd60e144e7cbeed179fcbf812a3",' + +'"annotation" : null,' + +'"answered_by" : null,' + +'"api_version" : "2010-04-01",' + +'"caller_name" : null,' + +'"date_created" : "Tue, 17 Jan 2012 21:21:45 +0000",' + +'"date_updated" : "Tue, 17 Jan 2012 21:21:50 +0000",' + +'"direction" : "inbound",' + +'"duration" : "4",' + +'"end_time" : "Tue, 17 Jan 2012 21:21:50 +0000",' + +'"forwarded_from" : "+14158774850",' + +'"from" : "+17378742833",' + +'"from_formatted" : "(737) 874-2833",' + +'"group_sid" : null,' + +'"parent_call_sid" : null,' + +'"phone_number_sid" : "PNebe1495ddc055eb2508cb3f9d4ed043d",' + +'"price" : "-0.01000",' + +'"sid" : "CA5c16c13e5d5615bd73d16664e562d895",' + +'"start_time" : "Tue, 17 Jan 2012 21:21:46 +0000",' + +'"status" : "completed",' + +'"subresource_uris" : { "notifications" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5c16c13e5d5615bd73d16664e562d895/Notifications.json",' + +'"recordings" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5c16c13e5d5615bd73d16664e562d895/Recordings.json"' + +'},' + +'"to" : "+14158774850",' + +'"to_formatted" : "(415) 877-4850",' + +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CA5c16c13e5d5615bd73d16664e562d895.json"' + +'}' + +'],' + +'"end" : 1,' + +'"first_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=0",' + +'"last_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=1",' + +'"next_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=1&AfterSid=CA5c16c13e5d5615bd73d16664e562d895",' + +'"num_pages" : 2,' + +'"page" : 0,' + +'"page_size" : 2,' + +'"previous_page_uri" : null,' + +'"start" : 0,' + +'"total" : 4,' + +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=0"' + +'}'; + + + String jsonPage1 = + '{ "calls" : [' + // calls[0] + +'{ "account_sid" : "AC03c2fcd60e144e7cbeed179fcbf812a3",' + +'"annotation" : null,' + +'"answered_by" : null,' + +'"api_version" : "2010-04-01",' + +'"caller_name" : null,' + +'"date_created" : "Thu, 12 Jan 2012 17:31:58 +0000",' + +'"date_updated" : "Thu, 12 Jan 2012 17:32:05 +0000",' + +'"direction" : "outbound-dial",' + +'"duration" : "0",' + +'"end_time" : "Thu, 12 Jan 2012 17:32:05 +0000",' + +'"forwarded_from" : "",' + +'"from" : "+14155551111",' + +'"from_formatted" : "(415) 555-1111",' + +'"group_sid" : null,' + +'"parent_call_sid" : "CAd6d7055b76d849489c3acabf4eb0140b",' + +'"phone_number_sid" : "PN2e8b297009170f06944fcfb74f5cd0ee",' + +'"price" : null,' + +'"sid" : "CAb659fd2fa5fd820c05a5277fae70a98b",' + +'"start_time" : "Thu, 12 Jan 2012 17:31:58 +0000",' + +'"status" : "no-answer",' + +'"subresource_uris" : { "notifications" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAb659fd2fa5fd820c05a5277fae70a98b/Notifications.json",' + +' "recordings" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAb659fd2fa5fd820c05a5277fae70a98b/Recordings.json"' + +' },' + +'"to" : "+14155551234",' + +'"to_formatted" : "(415) 555-1234",' + +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAb659fd2fa5fd820c05a5277fae70a98b.json"' + +'},' + // calls[1] + +'{ "account_sid" : "AC03c2fcd60e144e7cbeed179fcbf812a3",' + +'"annotation" : null,' + +'"answered_by" : null,' + +'"api_version" : "2010-04-01",' + +'"caller_name" : null,' + +'"date_created" : "Thu, 12 Jan 2012 17:31:48 +0000",' + +'"date_updated" : "Thu, 12 Jan 2012 17:32:05 +0000",' + +'"direction" : "outbound-api",' + +'"duration" : "8",' + +'"end_time" : "Thu, 12 Jan 2012 17:32:05 +0000",' + +'"forwarded_from" : null,' + +'"from" : "+14155551111",' + +'"from_formatted" : "(415) 555-1111",' + +'"group_sid" : null,' + +'"parent_call_sid" : null,' + +'"phone_number_sid" : "PN2e8b297009170f06944fcfb74f5cd0ee",' + +'"price" : "-0.02000",' + +'"sid" : "CAd6d7055b76d849489c3acabf4eb0140b",' + +'"start_time" : "Thu, 12 Jan 2012 17:31:57 +0000",' + +'"status" : "completed",' + +'"subresource_uris" : { "notifications" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAd6d7055b76d849489c3acabf4eb0140b/Notifications.json",' + +' "recordings" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAd6d7055b76d849489c3acabf4eb0140b/Recordings.json"' + +' },' + +'"to" : "+14152188121",' + +'"to_formatted" : "(415) 555-1234",' + +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls/CAd6d7055b76d849489c3acabf4eb0140b.json"' + +'}' + +'],' + +'"end" : 3,' + +'"first_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=0",' + +'"last_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=1",' + +'"next_page_uri" : null,' + +'"num_pages" : 2,' + +'"page" : 1,' + +'"page_size" : 2,' + +'"previous_page_uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=0",' + +'"start" : 2,' + +'"total" : 4,' + +'"uri" : "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=1"' + +'}'; + + // register the mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Call List instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json', - new Twilio_TestHTTPMock.Response(jsonPage0,200) - ); - - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=1&AfterSid=CA5c16c13e5d5615bd73d16664e562d895', - new Twilio_TestHTTPMock.Response(jsonPage1,200) - ); + // for the HTTP GET method and at the Twilio Call List instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json', + new Twilio_TestHTTPMock.Response(jsonPage0,200) + ); + + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Calls.json?PageSize=2&Page=1&AfterSid=CA5c16c13e5d5615bd73d16664e562d895', + new Twilio_TestHTTPMock.Response(jsonPage1,200) + ); // Get an API client and request the Twilio Call List - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeed179fcbf812a3',authToken); + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeed179fcbf812a3',authToken); TwilioCallList twcalls = client.getAccount().getCalls(); TwilioCall call; @@ -562,113 +562,113 @@ class Twilio_TestCalls { System.assert(!callIt.hasNext()); } - - static testmethod void testTwilioTranscription_get() { - String accountJsonResponseBody ='{' - +'"account_sid": "AC03c2fcd60e144e7cbeee413fcbf812a3",' - +'"api_version": "2010-04-01",' - +'"date_created": "Mon, 1 Feb 2012 10:49:17 +0000",' - +'"date_updated": "Mon, 1 Feb 2012 10:49:17 +0000",' - +'"duration": "6",' - +'"price": "-0.05000",' - +'"recording_sid": "REca11f06dc31b5515a2dfb1f5134361f2",' - +'"sid": "TR8c61027b709ffb038236612dc5af8723",' - +'"status": "completed",' - +'"transcription_text": "Tommy? Tommy is that you? I told you never to call me again.",' - +'"type": "fast",' - +'"uri": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Transcriptions/TR8c61027b709ffb038236612dc5af8723.json"' - +'}'; - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Transcriptions/TR8c61027b709ffb038236612dc5af8723.json', - new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) - ); - - // Get an API client and request the Twilio Account - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3', authToken); - Twiliotranscription twtransc = client.getAccount().getTranscription('TR8c61027b709ffb038236612dc5af8723'); - + + static testmethod void testTwilioTranscription_get() { + String accountJsonResponseBody ='{' + +'"account_sid": "AC03c2fcd60e144e7cbeee413fcbf812a3",' + +'"api_version": "2010-04-01",' + +'"date_created": "Mon, 1 Feb 2012 10:49:17 +0000",' + +'"date_updated": "Mon, 1 Feb 2012 10:49:17 +0000",' + +'"duration": "6",' + +'"price": "-0.05000",' + +'"recording_sid": "REca11f06dc31b5515a2dfb1f5134361f2",' + +'"sid": "TR8c61027b709ffb038236612dc5af8723",' + +'"status": "completed",' + +'"transcription_text": "Tommy? Tommy is that you? I told you never to call me again.",' + +'"type": "fast",' + +'"uri": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Transcriptions/TR8c61027b709ffb038236612dc5af8723.json"' + +'}'; + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Transcriptions/TR8c61027b709ffb038236612dc5af8723.json', + new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) + ); + + // Get an API client and request the Twilio Account + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3', authToken); + Twiliotranscription twtransc = client.getAccount().getTranscription('TR8c61027b709ffb038236612dc5af8723'); + System.assertEquals('TR8c61027b709ffb038236612dc5af8723', twtransc.getSid()); System.assertEquals('REca11f06dc31b5515a2dfb1f5134361f2', twtransc.getRecordingSid()); //System.assertEquals('CAfd61c7aff9ee4da8a053d49a35a5ff7f',twtransc.getcallsid()); System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twtransc.getDateCreated()); System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twtransc.getDateUpdated()); System.assertEquals('AC03c2fcd60e144e7cbeee413fcbf812a3',twtransc.getAccountSid()); - //System.assertEquals('2010-04-01',twtransc.getApiVersion()); + //System.assertEquals('2010-04-01',twtransc.getApiVersion()); System.assertEquals('completed',twtransc.getStatus()); System.assertEquals(6,twtransc.getduration()); - System.assertEquals('-0.05000',twtransc.getprice()); - System.assertEquals('Tommy? Tommy is that you? I told you never to call me again.',twtransc.getTranscriptionText()); - - Twiliotranscription twtransc1 = new Twiliotranscription(client); - Twiliotranscriptionlist twtransclist= new Twiliotranscriptionlist(client); - } + System.assertEquals('-0.05000',twtransc.getprice()); + System.assertEquals('Tommy? Tommy is that you? I told you never to call me again.',twtransc.getTranscriptionText()); + + Twiliotranscription twtransc1 = new Twiliotranscription(client); + Twiliotranscriptionlist twtransclist= new Twiliotranscriptionlist(client); + } static testmethod void testTwilioTranscriptionList_get_filter() { - String accountJsonResponseBody ='{"transcriptions": [{' - +'"account_sid": "AC03c2fcd60e144e7cbeee413fcbf812a3",' - +'"api_version": "2010-04-01",' - +'"date_created": "Mon, 1 Feb 2012 10:49:17 +0000",' - +'"date_updated": "Mon, 1 Feb 2012 10:49:17 +0000",' - +'"duration": "6",' - +'"price": "-0.05000",' - +'"recording_sid": "REca11f06dc31b5515a2dfb1f5134361f2",' - +'"sid": "TR8c61027b709ffb038236612dc5af8723",' - +'"status": "completed",' - +'"transcription_text": "Tommy? Tommy is that you? I told you never to call me again.",' - +'"type": "fast",' - +'"uri": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Transcriptions/TR8c61027b709ffb038236612dc5af8723.json"' - +'}],' - +'"page":0,"num_pages":1,"page_size":50,"total":2,"start":0,"end":1,"uri":' - +'"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json",' - +'"first_page_uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?Page=0&PageSize=50",'+ - +'"previous_page_uri":null,"next_page_uri":null,"last_page_uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?Page=0&PageSize=50"}'; + String accountJsonResponseBody ='{"transcriptions": [{' + +'"account_sid": "AC03c2fcd60e144e7cbeee413fcbf812a3",' + +'"api_version": "2010-04-01",' + +'"date_created": "Mon, 1 Feb 2012 10:49:17 +0000",' + +'"date_updated": "Mon, 1 Feb 2012 10:49:17 +0000",' + +'"duration": "6",' + +'"price": "-0.05000",' + +'"recording_sid": "REca11f06dc31b5515a2dfb1f5134361f2",' + +'"sid": "TR8c61027b709ffb038236612dc5af8723",' + +'"status": "completed",' + +'"transcription_text": "Tommy? Tommy is that you? I told you never to call me again.",' + +'"type": "fast",' + +'"uri": "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/Transcriptions/TR8c61027b709ffb038236612dc5af8723.json"' + +'}],' + +'"page":0,"num_pages":1,"page_size":50,"total":2,"start":0,"end":1,"uri":' + +'"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json",' + +'"first_page_uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?Page=0&PageSize=50",'+ + +'"previous_page_uri":null,"next_page_uri":null,"last_page_uri":"/2010-04-01/Accounts/AC03c2fcd60e144e7cbeed179fcbf812a3/Applications.json?Page=0&PageSize=50"}'; // register a mock Response with the Twilio_TestHTTPMock singleton service - // for the HTTP GET method and at the Twilio Account instance URI. - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Transcriptions.json', - new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) - ); - - // Get an API client and request the Twilio Account - TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3', authToken); - TwiliotranscriptionList twtrans = client.getAccount().gettranscriptions(); - System.assertNotEquals(null, twtrans); - - List twtranslist = twtrans.getPageData(); - System.assertNotEquals(null, twtranslist); - System.assertEquals(1, twtranslist.size()); - Twiliotranscription twtransc=twtranslist.get(0); + // for the HTTP GET method and at the Twilio Account instance URI. + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Transcriptions.json', + new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) + ); + + // Get an API client and request the Twilio Account + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3', authToken); + TwiliotranscriptionList twtrans = client.getAccount().gettranscriptions(); + System.assertNotEquals(null, twtrans); + + List twtranslist = twtrans.getPageData(); + System.assertNotEquals(null, twtranslist); + System.assertEquals(1, twtranslist.size()); + Twiliotranscription twtransc=twtranslist.get(0); System.assertEquals('TR8c61027b709ffb038236612dc5af8723', twtransc.getSid()); System.assertEquals('REca11f06dc31b5515a2dfb1f5134361f2', twtransc.getRecordingSid()); //System.assertEquals('CAfd61c7aff9ee4da8a053d49a35a5ff7f',twtransc.getcallsid()); System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twtransc.getDateCreated()); System.assertEquals(Datetime.newInstanceGmt(2012,2,1,10,49,17),twtransc.getDateUpdated()); System.assertEquals('AC03c2fcd60e144e7cbeee413fcbf812a3',twtransc.getAccountSid()); - //System.assertEquals('2010-04-01',twtransc.getApiVersion()); + //System.assertEquals('2010-04-01',twtransc.getApiVersion()); System.assertEquals('completed',twtransc.getStatus()); System.assertEquals(6,twtransc.getduration()); - System.assertEquals('-0.05000',twtransc.getprice()); - System.assertEquals('Tommy? Tommy is that you? I told you never to call me again.',twtransc.getTranscriptionText()); - - - Twilio_TestHTTPMock.getInstance().putResponse( - 'GET', - 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Transcriptions.json?sid=TR8c61027b709ffb038236612dc5af8723', - new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) - ); - - // Get an API client and request the Twilio Account - map params=new map(); - params.put('sid','TR8c61027b709ffb038236612dc5af8723'); - twtrans = client.getAccount().gettranscriptions(params); - System.assertNotEquals(null, twtrans); - - Iterator it = twtrans.iterator(); - - System.assertEquals(true, it.hasnext()); - twtransc=it.next(); + System.assertEquals('-0.05000',twtransc.getprice()); + System.assertEquals('Tommy? Tommy is that you? I told you never to call me again.',twtransc.getTranscriptionText()); + + + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/Transcriptions.json?sid=TR8c61027b709ffb038236612dc5af8723', + new Twilio_TestHTTPMock.Response(accountJsonResponseBody,200) + ); + + // Get an API client and request the Twilio Account + map params=new map(); + params.put('sid','TR8c61027b709ffb038236612dc5af8723'); + twtrans = client.getAccount().gettranscriptions(params); + System.assertNotEquals(null, twtrans); + + Iterator it = twtrans.iterator(); + + System.assertEquals(true, it.hasnext()); + twtransc=it.next(); System.assertEquals('TR8c61027b709ffb038236612dc5af8723', twtransc.getSid()); System.assertEquals('REca11f06dc31b5515a2dfb1f5134361f2', twtransc.getRecordingSid()); //System.assertEquals('CAfd61c7aff9ee4da8a053d49a35a5ff7f',twtransc.getcallsid()); @@ -678,8 +678,8 @@ class Twilio_TestCalls { // System.assertEquals('2010-04-01',twtransc.getApiVersion()); System.assertEquals('completed',twtransc.getStatus()); System.assertEquals(6,twtransc.getduration()); - System.assertEquals('-0.05000',twtransc.getprice()); - System.assertEquals('Tommy? Tommy is that you? I told you never to call me again.',twtransc.getTranscriptionText()); - system.assertEquals(false,it.hasnext()); - } + System.assertEquals('-0.05000',twtransc.getprice()); + System.assertEquals('Tommy? Tommy is that you? I told you never to call me again.',twtransc.getTranscriptionText()); + system.assertEquals(false,it.hasnext()); + } } \ No newline at end of file diff --git a/src/classes/Twilio_TestCapability.cls b/src/classes/Twilio_TestCapability.cls index 763917f..643a776 100644 --- a/src/classes/Twilio_TestCapability.cls +++ b/src/classes/Twilio_TestCapability.cls @@ -26,70 +26,48 @@ OTHER DEALINGS IN THE SOFTWARE. class Twilio_TestCapability { final static String ACCOUNT_SID = 'CA5ea9c5d78e1f35fc01c204682d056e22'; - final static String AUTH_TOKEN = '12345678901234567890123456789012'; - final static String APP_SID = 'AP9b2e38d8c592488c397fc871a82a74ec'; + final static String AUTH_TOKEN = '12345678901234567890123456789012'; + final static String APP_SID = 'AP9b2e38d8c592488c397fc871a82a74ec'; - static testMethod void testTwilioCapability_outgoing() { - TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN); - capability.allowClientOutgoing(APP_SID); - System.assertEquals(true, capability.test_buildOutgoingScope); - System.assertEquals(APP_SID, capability.test_appSid); - - String token = capability.generateToken(); - - Map filters = new Map {'foo' => 'bar'}; - capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN); - capability.allowClientOutgoing(APP_SID, filters); - System.assertEquals(true, capability.test_buildOutgoingScope); - System.assertEquals(APP_SID, capability.test_appSid); - System.assertEquals(filters, capability.test_outgoingParams); - String token2 = capability.generateToken(100); - } - - static testMethod void testTwilioCapability_incoming() { - TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN); - capability.allowClientIncoming('Jenny'); - System.assertEquals('Jenny',capability.test_incomingClientName); - String token = capability.generateToken(); - } - - static testMethod void testTwilioCapability_bidirectional() { - TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN); - capability.allowClientIncoming('Jenny'); - capability.allowClientOutgoing(APP_SID); - System.assertEquals('Jenny',capability.test_incomingClientName); - System.assertEquals(APP_SID,capability.test_appSid); - String token = capability.generateToken(); - } + static testMethod void testTwilioCapability_outgoing() { + TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN); + capability.allowClientOutgoing(APP_SID); + System.assertEquals(true, capability.test_buildOutgoingScope); + System.assertEquals(APP_SID, capability.test_appSid); + + String token = capability.generateToken(); + + Map filters = new Map {'foo' => 'bar'}; + capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN); + capability.allowClientOutgoing(APP_SID, filters); + System.assertEquals(true, capability.test_buildOutgoingScope); + System.assertEquals(APP_SID, capability.test_appSid); + System.assertEquals(filters, capability.test_outgoingParams); + String token2 = capability.generateToken(100); + } + + static testMethod void testTwilioCapability_incoming() { + TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN); + capability.allowClientIncoming('Jenny'); + System.assertEquals('Jenny',capability.test_incomingClientName); + String token = capability.generateToken(); + } + + static testMethod void testTwilioCapability_bidirectional() { + TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN); + capability.allowClientIncoming('Jenny'); + capability.allowClientOutgoing(APP_SID); + System.assertEquals('Jenny',capability.test_incomingClientName); + System.assertEquals(APP_SID,capability.test_appSid); + String token = capability.generateToken(); + } - static testMethod void testTwilioCapability_eventstream() { - Map filters = new Map {'foo' => 'bar'}; - TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN); - capability.allowEventStream(filters); - System.assertEquals(1, capability.test_scopes.size()); - System.assertEquals('scope:stream:subscribe?path=%2F2010-04-01%2FEvents¶ms=foo%3Dbar', capability.test_scopes.get(0)); - String token = capability.generateToken(); - } - - /* UNIT TESTS FOR PRIVATE METHODS */ - static testMethod void testGenerateParamString() { - System.assertEquals('', TwilioCapability.generateParamString(new Map())); - System.assertEquals('a=b', TwilioCapability.generateParamString(new Map {'a'=>'b'} )); - System.assertEquals('cat=dog&foo=bar', TwilioCapability.generateParamString(new Map {'foo'=>'bar', 'cat' => 'dog'} )); - System.assertEquals('e=f&c=d&a=b', TwilioCapability.generateParamString(new Map {'a'=>'b', 'c'=>'d', 'e'=>'f' } )); - System.assertEquals('split+key2=split+val2&split+key1=split+val1', TwilioCapability.generateParamString(new Map {'split key1'=>'split val1', 'split key2'=>'split val2'} )); - } - - static testMethod void testEncodeBase64() { - System.assertEquals('', TwilioCapability.urlSafeEncodeBase64('')); - System.assertEquals('QQ', TwilioCapability.urlSafeEncodeBase64('A')); - System.assertEquals('QUI', TwilioCapability.urlSafeEncodeBase64('AB')); - System.assertEquals('QUJDRA', TwilioCapability.urlSafeEncodeBase64('ABCD')); - } - - static testMethod void testJoin() { - System.assertEquals('', String.join(new List(),',')); - System.assertEquals('a', String.join(new List{'a'},',')); - System.assertEquals('a,b,c,d,e', String.join(new List{'a','b','c','d','e'},',')); - } + static testMethod void testTwilioCapability_eventstream() { + Map filters = new Map {'foo' => 'bar'}; + TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN); + capability.allowEventStream(filters); + System.assertEquals(1, capability.test_scopes.size()); + System.assertEquals('scope:stream:subscribe?path=%2F2010-04-01%2FEvents¶ms=foo%3Dbar', capability.test_scopes.get(0)); + String token = capability.generateToken(); + } } \ No newline at end of file diff --git a/src/classes/Twilio_TestPhoneNumbers.cls b/src/classes/Twilio_TestPhoneNumbers.cls index 9c6e796..22c7838 100644 --- a/src/classes/Twilio_TestPhoneNumbers.cls +++ b/src/classes/Twilio_TestPhoneNumbers.cls @@ -261,8 +261,8 @@ private class Twilio_TestPhoneNumbers { ); map params=new map(); - params.put('Contains','51034*****'); params.put('AreaCode','510'); + params.put('Contains','51034*****'); // Get an API client and request the Twilio Account TwilioRestClient client = new TwilioRestClient('ACba8bc05eacf94afdae398e642c9cc32d', authToken); diff --git a/src/classes/Twilio_TestQueue.cls b/src/classes/Twilio_TestQueue.cls index 6030caa..8c621cb 100644 --- a/src/classes/Twilio_TestQueue.cls +++ b/src/classes/Twilio_TestQueue.cls @@ -124,5 +124,4 @@ private class Twilio_TestQueue System.assertEquals('0',String.valueof(queue.getAverageWaitTime()));*/ } - } \ No newline at end of file diff --git a/src/classes/Twilio_TestShortCode.cls b/src/classes/Twilio_TestShortCode.cls new file mode 100644 index 0000000..f928e4e --- /dev/null +++ b/src/classes/Twilio_TestShortCode.cls @@ -0,0 +1,53 @@ +@istest +private class Twilio_TestShortCode { + final static String authToken = '12345678901234567890123456789012'; + static testmethod void testTwilioShortCodeList_get() + { + String shortcodeJsonResponseBody ='{"page": 0,"num_pages": 1,"page_size": 50,"total": 6,"start": 0,"end": 5,'+ + '"uri": "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/SMS/ShortCodes.json",'+ + '"first_page_uri": "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/SMS/ShortCodes.json?Page=0&PageSize=50",'+ + '"previous_page_uri": null,"next_page_uri": null,"last_page_uri": "/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/SMS/ShortCodes.json?Page=0&PageSize=50",'+ + '"short_codes": [{"sid": "SC6b20cb705c1e8f00210049b20b70fce2","account_sid": "AC03c2fcd60e144e7cbeee413fcbf812a3","friendly_name": "67898",'+ + '"short_code": "67898","date_created": "Thu, 13 Nov 2008 07:56:24 +0000","date_updated": "Thu, 13 Nov 2008 08:45:58 +0000",'+ + '"sms_url": "http://demo.twilio.com/docs/sms.xml","sms_method": "POST","sms_fallback_url": "http://smsapp.com/fallback","sms_fallback_method": "POST",'+ + '"api_version": "2010-04-01","uri": "/2010-04-01/Accounts/ACdc5f1e11047ebd6fe7a55f120be3a900/SMS/ShortCodes/SC6b20cb705c1e8f00210049b20b70fce2.json"}]}'; + + // register a mock Response with the Twilio_TestHTTPMock singleton service + // for the HTTP GET method and at the Twilio Account instance URI. + + Twilio_TestHTTPMock.getInstance().putResponse( + 'GET', + 'https://api.twilio.com/2010-04-01/Accounts/AC03c2fcd60e144e7cbeee413fcbf812a3/SMS/ShortCodes.json', + new Twilio_TestHTTPMock.Response(shortcodeJsonResponseBody,200) + ); + + // Get an API client and request the Twilio Account + TwilioRestClient client = new TwilioRestClient('AC03c2fcd60e144e7cbeee413fcbf812a3', authToken); + TwilioShortCodeList twshortcodes=client.getAccount().getShortCodes(); + + System.assertNotEquals(null, twshortcodes); + + List twshortcodesList = twshortcodes.getPageData(); + + System.assertNotEquals(null, twshortcodesList); + System.assertEquals(1, twshortcodesList.size()); + System.assertEquals('SC6b20cb705c1e8f00210049b20b70fce2', twshortcodesList[0].getSid()); + System.assertEquals(Datetime.newInstanceGmt(2008,11,13,07,56,24),twshortcodesList[0].getDateCreated()); + System.assertEquals(Datetime.newInstanceGmt(2008,11,13,08,45,58),twshortcodesList[0].getDateUpdated()); + System.assertEquals('67898',twshortcodesList[0].getFriendlyName()); + System.assertEquals('AC03c2fcd60e144e7cbeee413fcbf812a3',twshortcodesList[0].getAccountSid()); + System.assertEquals('67898',twshortcodesList[0].getShortCode()); + System.assertEquals('2010-04-01',twshortcodesList[0].getApiVersion()); + System.assertEquals('http://demo.twilio.com/docs/sms.xml',twshortcodesList[0].getSmsUrl()); + System.assertEquals('POST',twshortcodesList[0].getSmsMethod()); + System.assertEquals('http://smsapp.com/fallback',twshortcodesList[0].getSmsFallbackUrl()); + System.assertEquals('POST',twshortcodesList[0].getSmsFallbackMethod()); + + Iterator it = twshortcodes.iterator(); + System.assertEquals(true, it.hasNext()); + + TwilioShortCode s=it.next(); + System.assertEquals(false, it.hasNext()); + + } +} \ No newline at end of file diff --git a/src/classes/Twilio_TestShortCode.cls-meta.xml b/src/classes/Twilio_TestShortCode.cls-meta.xml new file mode 100644 index 0000000..b12420e --- /dev/null +++ b/src/classes/Twilio_TestShortCode.cls-meta.xml @@ -0,0 +1,5 @@ + + + 31.0 + Active + diff --git a/src/remoteSiteSettings/Twilio_Lookups.remoteSite b/src/remoteSiteSettings/Twilio_Lookups.remoteSite new file mode 100755 index 0000000..0240b4a --- /dev/null +++ b/src/remoteSiteSettings/Twilio_Lookups.remoteSite @@ -0,0 +1,7 @@ + + + URL endpoint for Lookups API + false + true + https://lookups.twilio.com + diff --git a/src/remoteSiteSettings/Twilio_TaskRouter.remoteSite b/src/remoteSiteSettings/Twilio_TaskRouter.remoteSite new file mode 100755 index 0000000..82d4e56 --- /dev/null +++ b/src/remoteSiteSettings/Twilio_TaskRouter.remoteSite @@ -0,0 +1,7 @@ + + + URL endpoint for TaskRouter API + false + true + https://taskrouter.twilio.com +